首页 > 解决方案 > 使用网格中的单元格编号获取 X 和 Y 坐标

问题描述

网格

我有一个如上所示的网格,我想获取单元格 x 和 y 坐标及其编号。

例如:单元格编号 18 => x = 3, y = 4

我已经拥有的:

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 

console.log(getXYCoords(8, grid))

function getXYCoords(cell, grid) {

//This is where I can't figure out how to do it

}

标签: javascript

解决方案


简单的 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)。


推荐阅读