1

The Grid

I have a grid like shown above, and I want to get the cell x and y coordinates with its number.

For example: cell number 18 => x = 3, y = 4

What I've already got:

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

}
cstef
  • 47
  • 8

2 Answers2

2

A nested for loop would solve this. First loop through all the rows, then through the columns of each row. y will indicate the current row and x the current column.

Check for a match within the second loop. If a match is found, then return an object with the x and y coordinates in an object.

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))
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • var fieldWidth = parseInt(width / columns); var columnXY = parseInt(x / fieldWidth); var rowXY = parseInt(y / fieldWidth); return parseInt(columnXY + (rowXY * columns)); – Andy Gee Mar 10 '22 at 07:20
  • @AndyGee care to elaborate? – Emiel Zuurbier Mar 10 '22 at 08:37
  • Hi, it was just a suggestion for an alternate way to calculate this without any loops. Actually I use a grid starting with zero so my initial calculation is invalid. There's a permanent gist below to a working variant as I can't add an answer. https://gist.github.com/andyg2/a907a263dafbd2565e9eb26e242de9df – Andy Gee Mar 11 '22 at 22:09
1

Simple 2 loops solution would get you get the result.

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 };
      }
    }
  }
}

You can also improve the performance of your function, currently at O(n^2) by memoizing the function.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70