Search code examples
arraysalgorithm

1D array to 2D array mapping


This may sound like a homework problem, but I swear it isn't.

I'm trying to build an iterator for this 2D-array wrapper class. I figured that if I am able to solve this problem, then I can build my iterator.

I have this 1D array of 9 consecutive integers starting at 0 and ending at 8.

[0, 1, 2, 3, 4, 5, 6, 7, 8]

I am given two variables horizontal_size = 3 and vertical_size = 3

I want to make this array into a 2D array that is horizontal_size by vertical_size. let's call them h and v for brevity.

The result that I want to generate is this:

0 1 2
3 4 5
6 7 8

Given the value in the 1D array, which tells me the index, Also given h and v, which are both 3 in this case. Is there a way to generate the indices on the 2D array?

For example, the first element in the 1D array is 0, which maps to array[0][0]. The second element is 1, which maps to array[0][1]

I figured out that I can get the vertical index by doing array1d[i] mod vertical_size.

           for getting the vertical index ::: th 

0 = [0][0] 0 mod 3 = 0 1 = [0][1] 1 mod 3 = 1 2 = [0][2] 2 mod 3 = 2

3 = [1][0] and so on... 4 = [1][1] 5 = [1][2]

6 = [2][0] 7 = [2][1] 8 = [2][2]

But I'm not sure how to get the horizontal index.


Solution

  • The horizontal index is given by floor(i / v), or as just i/v if your programming language implements integer division by truncation.

    For example, floor(7/3) = 2, so 7 is on the row 2.