[英]Find array index on a 1d array from a 2d grid javascript
假设我有以下网格,并且网格的每个单元格都有一个映射到一维数组的索引。
0, 1, 2
3, 4, 5,
6, 7, 8
我可以用1d数组来表示,例如: [0, 1, 2, 3, 4, 5, 6, 7, 8]
我想知道一种将(3,1)
类的2d坐标映射到数组中索引的简单方法,在这种情况下,将为2
。
经过大量研究后,我发现很多人建议使用以下公式: index = x + (y * width)
,但在我的测试中似乎不起作用。
例如对于(1, 1)
,结果将为index = 1 + (1 * 3) = 4
,而对于(3, 1)
将为index = 3 + (1 * 3) = 6
,这不会使对我来说没有任何意义。
是否可以通过简单的方式实现? 还是我需要像for那样使用迭代器?
二维矩阵符号通常为(row, col)
, 索引从0开始 。
因此, (3, 1)
是无效的:从0到2仅3行。 (1, 1)
表示第二行,第二列,在您的示例中为4
。 因此,公式为:
(row * width) + col
(2, 1) = 2*3+1 = index 7
再次在第一行/列中使用0。
如果您确实想继续从1开始的索引,只需将公式更改为:
((row - 1) * width) + (col - 1) = 1D index
在您的情况下,由于坐标系从1开始且数组从0开始,因此index = (x - 1) + ((y - 1) * width)
。
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]; function getPosition(x, y, width) { return x - 1 + (y - 1) * width; } console.log({ position: getPosition(3, 1, 3), element: arr[getPosition(3, 1, 3)] });
确实是index = x + y * width
(不需要括号)或index = y + x * width
,具体取决于您是否要让扁平数组将行保持在一起,就像在您的问题中一样[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
, index = x + y * width
),或将各列保持在一起( [0, 3, 6, 1, 4, 7, 2, 5, 8]
, index = y + x * width
)。 但是索引通常从0开始,而不是1。因此,(1,1)将是(0,0),而(3,1)将是(2,0)。
这是第一个:
// 0, 1, 2 // 3, 4, 5 // 6, 7, 8 const a = [0, 1, 2, 3, 4, 5, 6, 7, 8]; let x = 0, y = 1; let index = x + y * 3; console.log(`(${x}, ${y}) is index ${index}, value ${a[index]}`); x = 2; y = 0; index = x + y * 3; console.log(`(${x}, ${y}) is index ${index}, value ${a[index]}`);
这是第二个:
// 0, 1, 2 // 3, 4, 5 // 6, 7, 8 const a = [0, 3, 6, 1, 4, 7, 2, 5, 8]; let x = 0, y = 1; let index = y + x * 3; console.log(`(${x}, ${y}) is index ${index}, value ${a[index]}`); x = 2; y = 0; index = y + x * 3; console.log(`(${x}, ${y}) is index ${index}, value ${a[index]}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.