user2616079
user2616079

Reputation: 33

Get 1D item with 2D coordinates with 1D array beginning at bottom left of 2D array

How do I get a 1D item which starts at the bottom left of a 2D array after providing 2D coordinates?

var width = 3; // the 2D array width
var height = 3; // the 2D array height
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]; // 1D array

console.log(getIndex(0,2));
console.log(getIndex(1,2));
console.log(getIndex(2,2));
console.log(getIndex(0,1));
console.log(getIndex(1,1));
console.log(getIndex(2,1));
console.log(getIndex(0,0));
console.log(getIndex(1,0));
console.log(getIndex(2,0));

//Desired output: 0 1 2 3 4 5 6 7 8


function getIndex(x, y) {
  return ... ;   // how????????
}

To illustrate, here's the 2D array of the 1D array in the code above:

           X
         0---2

   0     6 7 8
Y  |     3 4 5
   2     0 1 2

*The numbers in the 2D array represent the position within the 1D index.

Upvotes: 0

Views: 174

Answers (1)

MBo
MBo

Reputation: 80232

To provide needed access (with reverse row order), you can use such formula:

indx =  (height - 1 - y) * width + x

Upvotes: 1

Related Questions