Chuck B Ihekwaba
Chuck B Ihekwaba

Reputation: 69

When given the index of coordinates to a multidimensional array, how can you calculate those coordinates?

Conversely, I have a function that gives you the index of inputted coordinates.

function generateBoard(rows, cols, initialValue) {
let arr = [];
for(var i = 0; i < rows;i++){
    arr.push(new Array(cols).fill(initialValue))
}
return arr;
}  

If given:

const board = generateBoard(3,3," ");

It should produce an array as such, ["","",""],["","",""],["","",""], with for example coordinates 2,1 should print out 7.

How can we write:

function indexToRowCol(board, i){}

If a sample input of indexToRowCol(board, 8) should give you the coordinates of rows = x and cols = x? I am not sure how to calculate the values of rows and cols simply by the index parameter.

Upvotes: 0

Views: 255

Answers (3)

Chuck B Ihekwaba
Chuck B Ihekwaba

Reputation: 69

This actually worked for me.

function indexToRowCol(board, i){
    var row = Math.floor((i/board.length));
    var col = (i - (row*(board.length)));

    return [row,col];
}   

I was getting negative integers for some of the other responses but this seems to stop that.

Upvotes: 0

Dij
Dij

Reputation: 9808

for row number divide i by board[0].length since that is number of elements you have to distribute in each row and take floor of that value, for column you have to find the leftover elements in last row, so

row = parseInt(i/board[0].length) and column = i - row*board[0].length -1

function generateBoard(rows, cols, initialValue) {
let arr = [];
for(var i = 0; i < rows;i++){
arr.push(new Array(cols).fill(initialValue))
}
return arr;
}  

const board = generateBoard(3,3," ");

function indexToRowCol(board, i){
var row = parseInt(i/board[0].length);
var column = i - row*board[0].length - 1;

console.log(row);
console.log(column);
}

indexToRowCol(board, 8)

Upvotes: 1

simple guy
simple guy

Reputation: 673

function indexToRowCol(board, i){
  var row = parseInt(i/board[0].length);
  var col = i%board[0].length -1;
  return board[row][col];
}

Upvotes: 1

Related Questions