2 回答

TA貢獻2051條經驗 獲得超10個贊
嵌套for循環可以解決這個問題。首先遍歷所有行,然后遍歷每一行的列。y將指示當前行和x當前列。
檢查第二個循環中的匹配項。如果找到匹配項,則返回對象中具有x和坐標的對象。y
const grid = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
];
const rows = grid.length;
const columns = grid[0].length;
function getXYCoords(grid, cell) {
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
if (grid[y][x] === cell) {
return ({x, y});
}
}
}
return null;
}
console.log(getXYCoords(grid, 8))
console.log(getXYCoords(grid, 19))
console.log(getXYCoords(grid, 22))

TA貢獻1829條經驗 獲得超7個贊
簡單的 2 循環解決方案會讓你得到結果。
const grid = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
const width = grid[0].length //As my grid will always be regular, I just pick the first row's length
const height = grid.length
const res = getXYCoords(8, grid);
console.log(res, grid[res.x][res.y]) // verifies the results
function getXYCoords(cell, grid) {
let x, y;
for(x in grid) {
for(y in grid[x]){
if (grid[x][y] === cell) {
return { x, y };
}
}
}
}
您還可以通過記憶函數來提高函數的性能,目前為 O(n^2)。
添加回答
舉報