If I use a 1d array to represent a square board, how can I take my index and check the squares above, below and on the sides?

If I have a 4x4 playground, which I represent in my program as an array of size 1d with size 16.

How can I get the indices of the squares above, below, left and right at any given index?

So for example:

A = { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 }

What is this board?

 0   1   2   3
 4   5   6   7
 8   9  10  11
12  13  14  15  

Suppose I am now at index number 8 on the board (value = 7). How can I get the index for 4 (value = 3), 5 (value = 6), 10 (value = 11) and understand that there is no right square, because it is on the right edge of the board.

I know that I need to use some mathematical formula, but I cannot come up with the right way to get indices for adjacent squares.

I think something like ...

if ((i % 4) + 1 < 3) right = i + 1;
if ((i % 4) - 1 > 0) left = i - 1;
if ((i % 4) + 4 < 15) bottom = i + 4;
if ((i % 4) - 4 > 0 ) top = i - 4;

, ?

+3
1

, :

row = index/num_columns;
column = index % num_columns;

,

index = row * num_columns + column;

, .

above = (row-1, column)
left = (row, column-1)
etc...
+7

Source: https://habr.com/ru/post/1741691/


All Articles