我有像游戏 2048 中那样的 4x4 矩阵,我需要打印向右移动一步的结果。例如我们有矩阵:
0 0 2 2
4 4 8 4
64 64 8 4
16 8 64 8
Result is:
0 0 0 4
0 8 8 4
0 128 8 4
16 8 64 8
我的代码:
function solution(x){
for (let i = 0; i < x.length; i++){
for (let j = 0; j < x.length; j++){
if (x[i][j] == x[i][j+1]){
x[i][j+1] = x[i][j+1] * 2;
x[i][j] = 0;
}
}
}
return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))
在第二个版本中,我在第一行得到错误的结果 [0,0,0,16],正确的结果是 [0, 4, 4, 8]
最佳答案
您正在修改前面的数字,然后您检查下一个数字。因此,您实际上创建了一个临时结果和最终结果,因此,在某种程度上,是正确的:
[ 2, 2, 4, 8] -> [ 0, 4, 4, 8 ] -> [ 0, 0, 8, 8 ] -> [ 0, 0, 0, 16 ]
^ ^ ^ ^ ^ ^ ^
如果您想忽略在同一运行中所做的更改,则可以在发现更改后将 j
增加 1
:
对每行执行所有组合的示例,不考虑当前修改
function solution(x) {
for (let i = 0; i < x.length; i++) {
for (let j = 0; j < x.length; j++) {
if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
x[i][j + 1] = x[i][j] * 2;
x[i][j] = 0;
j += 1;
}
}
}
return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))
如果您只想每行进行 1 次更改,则可以使用 break
使用 break
的示例,每行仅更新 1
function solution(x) {
for (let i = 0; i < x.length; i++) {
for (let j = 0; j < x.length; j++) {
if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
x[i][j + 1] = x[i][j] * 2;
x[i][j] = 0;
// If you only want one move, you can break here
break;
}
}
}
return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))
关于javascript - 在 2048 游戏中只向右移动一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56327639/