Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 1d array to 2d array?

Say, I have a 1d array with 30 elements:

array1d[0] = 1  
array1d[1] = 2  
array1d[2] = 3  
.  
.  
.  
array1[29] = 30

How to convert the 1d array to 2d array?
Say 10x3?

array2d[0][0] = 1 array2d[0][1] =2 array2d[0][2] =3
.
.
.
array2d[9][0] = 28 array2d[9][1] =29 array2d[9][2] =30

Should I use a for loop?
But I cannot work it out.

like image 984
kafter2 Avatar asked Feb 27 '11 17:02

kafter2


2 Answers

This is just a pseudo code. ROWS represent the length of the 2d array, and COLUMNS represent the length of the 1st element in the array

for(i=0; i<ROWS; i++)
   for(j=0; j<COLUMNS; j++)
       array2d[i][j] = array1d[ (i*COLUMNS) + j];
like image 182
Anex Johnson Avatar answered Sep 20 '22 13:09

Anex Johnson


Without writing any code for you...

  • Think about how big your 2d array needs to be.
  • Recognize that you'll need to loop over the contents of your source array to get each value into your destination array.

So it will look something like...

  • Create a 2d array of appropriate size.
  • Use a for loop to loop over your 1d array.
  • Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.

I'm being intentionally vague, seeing as this is homework. Try posting some code so we can see where you get stuck.

like image 25
epalm Avatar answered Sep 20 '22 13:09

epalm