Hi Guys,

I need to convert a 1D array into a 2D array. Usually a easy problem but my problem is the way data is stored in the 1D array
The structure of the 1D array is

r0c0, r0c1, r1c0, r1c1, etc etc

so for example if my 1D array is
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

the corresponding 2D array is
1 2 9 10 17 18
3 4 11 12 19 20
5 6 13 14 21 22
7 8 15 16 23 24

The sode I have that worked only partially is

``````int rows = 4;
int cols = 6;
int array1D[rows*cols] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}
int array2D[rows][cols];
int offset = 2;  //Offset is always going to be 2
for(int i = 0; i < cols; i++)
for(int j = 0; j < rows; i++)
array2D[j][i] = array1D[i + j*offset];``````

this is the latest that I have tried. This gave me only the first 2 coulumns in the right order. I have tried many other combinations, but just can't seem to get the math right. Any help will be appreciated.

Fun. :) How about something brute force to get you going?

``````for (int i = 0; i < rows; ++i) {
int k = i * 2, m = 0;

for (int j = 0; j < cols; j += 2) {
int offset = k + (rows * gap * m++);

array2d[i][j] = array1d[offset];
array2d[i][j + 1] = array1d[offset + 1];
}
}``````

Fun. :) How about something brute force to get you going?

``````for (int i = 0; i < rows; ++i) {
int k = i * 2, m = 0;

for (int j = 0; j < cols; j += 2) {
int offset = k + (rows * gap * m++);

array2d[i][j] = array1d[offset];
array2d[i][j + 1] = array1d[offset + 1];
}
}``````

What is gap?
I assumed its a typo. I used the code without the gap variable and my output looks like
1 2 5 6 9 10
3 4 7 8 11 12
5 6 9 10 13 14
7 8 11 12 15 16

offset in your code was renamed to gap. It is an integer initialized to 2. Apologies for forgetting to include that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.