Question

For example if I have 5 x 5 grid and I have position 13. I want to find the absolute distance of each edge in every direction excluding diagonally. So from 13 to the left would be 3, to the right it would be 1, to the bottom it would be two and to the top it would be 2. How would I approach this?

 0  1  2  3  4 
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Was it helpful?

Solution

Distance from the top would be row,

int row = (int)(13/5); // 2

Distance from the left would be column, take the remainder of 13 by 5.

int col = (int)(13%5); // 3

Distance from the right would be the column minus total columns (5)

int colFromRight = 5-col-1; // 1

Distance from the bottom would be the row minus total rows (5)

int rowFromBottom = 5-row-1; // 2

Edit:

Heres a little diagram th at may help

heres an 1 dimensional array that we want to treat as a 2d array. It has 2 rows and 3 columns for a total of 6 elements. In our program it is a 1d array like this, I am using brackets[] for looks not syntax.

[1][2][3][4][5][6]

visually it would be like this

[1][2][3]
[4][5][6]

So to get the row of say location 5 we say

int location = 5;
int row = floor(location/3);

As you can see every time the row becomes 1+ a multiple of 3 the row number will increase.


for columns its the same thing but with a remainder.

int location = 5;
int column = location%3;

Here every time the location reaches 3 the remainder returns to 0 and the columns start over (essential signaling a new row).

OTHER TIPS

Treat it as a 1-dimensional array and use modulus, division, and subtraction.

row_length = 5
col_length = 5
index = 13

x = (index % row_length);
y = (index - x) / col_length;

distance from left edge = row_length - x
distance from bottom = col_length - y

EDIT: I was actually asked this during an interview a few months ago and botched it. I wrote about it in a blog post here: http://tmblr.co/ZSJA4p18C4Ow0

EDIT 2: Fixed the subtraction to find left/bottom edges.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top