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

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.


int array2d[][] = new int[10][3];


for(int i=0; i<10;i++)
   for(int j=0;j<3;j++)
       array2d[i][j] = array1d[(j*10) + i]; 

Here a generic function to convert from 1D -> 2D array:

public int[][] monoToBidi( final int[] array, final int rows, final int cols ) {
    if (array.length != (rows*cols))
        throw new IllegalArgumentException("Invalid array length");

    int[][] bidi = new int[rows][cols];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array, (i*cols), bidi[i], 0, cols);

    return bidi;
}

If you want to do the contrary (2D -> 1D), here the function:

public int[] bidiToMono( final int[][] array ) {
    int rows = array.length, cols = array[0].length;
    int[] mono = new int[(rows*cols)];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array[i], 0, mono, (i*cols), cols);    
        return mono;
}

public class Test{

    public static void main(String[] argv)
    {
        int x,y;
        for(int num =0; num<81;num++)
        {
            if((num % 9)>0)
            {
                x = num/9;
                y = num%9;

            }else
            {
                x = num/9;
                y = 0;
            }

            System.out.println("num ["+num+"]---["+x+","+y+"]");

        }
    }
}
/* Replace  9 by the size of single row of your 2D array */