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.
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.
This is working solution in java. Note that %
is mod
function.
public static void main(String[] args) throws IOException {
int[] oneD = {1,2,3,4,5,6};
int w = 3;
int h = 2;
int[][] twoD = new int[h][w];
int[] oneDReversed = new int[oneD.length];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
twoD[i][j] = oneD[i*w+j];
}
}
for (int i = 0; i < w*h; i++) {
oneDReversed[i] = twoD[(i / w)][(i%w)];
}
}
Why the twoD[i][j] = oneD[i*w+j]
? Because you have cycle in cycle doing "For every row i
selet all collumns j
and gives it to the array[num_of_rows][num_of_columns]
by the equaliation : row*width
+ column
.
The reserved means: The row
is counted as rounded down index
devide number_of_columns
. And the column
is the rest of deviding the same variables (mod).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With