亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用網格中的單元格編號獲取 X 和 Y 坐標

使用網格中的單元格編號獲取 X 和 Y 坐標

慕蓋茨4494581 2023-05-19 14:53:02
我有一個如上所示的網格,我想獲取單元格的 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 lengthconst height = grid.length console.log(getXYCoords(8, grid))function getXYCoords(cell, grid) {//This is where I can't figure out how to do it}
查看完整描述

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))


查看完整回答
反對 回復 2023-05-19
?
千巷貓影

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)。



查看完整回答
反對 回復 2023-05-19
  • 2 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號