【发布时间】:2020-08-13 23:43:45
【问题描述】:
我正在尝试通过根据下面列出的坐标将“a”坐标处的值映射到旋转图像来旋转图像 (a)。为什么这不起作用?
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
// Desired result:
// rotateImage(a) =
// [[7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]]
// aCoords = [[00,01,02],
// [10, 11, 12],
// [20,21,22]]
// rotatedImageCoordsRelatingToa = [[20, 10, 00],
// [21, 11, 01],
// [22,12,02]]
function rotateImage(a) {
const image = [...a]
const length = a.length
const rotatedImage = [...a]
for(let i=0;i<length;i++){
for(let j=0;j<length;j++){
let toRotateCoord = length-(1+j)
console.log("Original coordinates:" + i,j + " should map to rotated coordinates:"+ toRotateCoord, i)
rotatedImage[i][j] = image[toRotateCoord][i]
}
}
return rotatedImage;
}
rotateImage(a);
当我运行它时,我得到了
//[[7,4,7],
// [8,5,4],
// [9,4,7]]
// Not
// [[7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]]
我知道这可能有更好的算法,但我很好奇为什么这种方法不起作用。这似乎与访问数组的方式有关。
【问题讨论】:
-
我不懂 JS,但从你的输出来看,在我看来
rotatedImage和image可能指向同一个内存。 -
看起来更像这个问题:stackoverflow.com/q/60508865/1447675
标签: javascript arrays algorithm image-processing