我正在尝试解决一个机器人爪杆难题,它应该将所有的盒子均匀地分布在所有可用堆栈上。

问题是,当它到达最后一个盒子时,它会向左移动,然后向右移动,无限循环:
function solve(clawPos, boxes, boxInClaw) {
// Calculate a maximum number of boxes per stack
let max = (boxes.reduce((a, b) => a + b) + ~~boxInClaw) / boxes.length
// Current stack number
const current = boxes[clawPos]
// Helpers
const bigger = current > max
const lower = current < max
const equal = current === max
const last = clawPos === boxes.length - 1
// Command to return for a claw
let command = ''
// Actions for claw
const R = () => command = 'RIGHT'
const L = () => command = 'LEFT'
const U = () => command = 'PICK'
const D = () => command = 'PLACE'
// Automatically select where to move the claw
const autoDirection = () => {
const value = boxes[clawPos]
const left = boxes.slice(0, clawPos)
const right = boxes.slice(clawPos, -1)
const target = max - 1
if (boxInClaw) {
if (left.includes(target)) L()
else if (right.includes(target)) R()
} else {
R()
}
}
autoDirection()
if (boxInClaw) {
if (lower) D()
} else {
if (bigger) U()
}
return command;
}我尝试了许多不同的方法来使它动态化,有没有更聪明的方法来知道它应该往哪个方向走?
这是一个直接链接(请不要提交):https://www.codingame.eu/evaluate/18917274?id=427696529803c1cd24e9258b89d01a98a72126e
发布于 2021-12-03 04:07:00
这是我对此的解决方案:
function createStack(length, totalBoxes) {
const boxPerStack = Math.floor(totalBoxes / length);
let newStack = new Array(length).fill(boxPerStack);
const remainder = totalBoxes % length;
if (remainder !== 0) {
for (let i = 0; i < remainder; i++) {
newStack[i]++;
}
}
return newStack;
}
function solve(clawPos, boxes, boxInClaw) {
// Write your code here
const totalBoxes = boxes.reduce((prev, acc) => prev + acc);
let targetPos;
if (boxInClaw) {
const targetStack = createStack(boxes.length, totalBoxes + 1);
// Move to place
for (let i = 0; i < boxes.length; i++) {
if (boxes[i] < targetStack[i]) {
targetPos = i;
break;
}
}
if (clawPos === targetPos) return 'PLACE';
else if (clawPos < targetPos) return 'RIGHT';
else return 'LEFT';
} else {
const targetStack = createStack(boxes.length, totalBoxes);
// Move to pick
for (let i = 0; i < boxes.length; i++) {
if (boxes[i] > targetStack[i]) {
targetPos = i;
break;
}
}
if (clawPos === targetPos) return 'PICK';
else if (clawPos < targetPos) return 'RIGHT';
else return 'LEFT';
}
return '';
}https://stackoverflow.com/questions/67926162
复制相似问题