Reputation: 125
I have 2D array and want to convert it into 1D array.
The 2D array is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
to 1D array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
How do I access nearest neighbor of the element number 6 in 1D array, so that I can get the same result when I access in 2D array, such as
1 2 3
5 6 7
9 10 11
in C++?
Upvotes: 4
Views: 2630
Reputation: 7336
If you have a 2D array that is M
items long by N
items tall, you need a 1D array that has M*N
elements.
When trying to find the neighbors of element x
:
left(x) = (x - 1) % M
right(x) = (x + 1) % M
above(x) = (x - M) % (M * N)
below(x) = (x + M) % (M * N)
Note that the above solution makes the bottom and top of your array adjacent, as well as the right edge and left edge. To get rid of that, simply omit the modular math and detect when your index has moved past the right / left / top / bottom edges.
Upvotes: 3