logo CodeStepByStep logo

unflatten

Write a method named unflatten that accepts three parameters: a 1-D array of integers, and a number of rows and columns. Your method should convert the 1-D array into a 2-D array with the given number of rows and columns, where values are transferred in row-major order into the two-dimensional array. For example, if the given array is declared:

int[] a = {3, 8, 12, 2, 9, 17, 43, -8, 46, 203, 14, 97};

Then the call of unflatten(a, 4, 3) should return the following 2-D array:

{{  3,   8,  12},
 {  2,   9,  17},
 { 43,  -8,  46},
 {203,  14,  97}}

The call of unflatten(a, 6, 2) should return the following 2-D array:

{{  3,   8},
 { 12,   2},
 {  9   17},
 { 43,  -8},
 { 46, 203},
 { 14,  97}}

If the array's contents do not fit exactly into a 2-D array of the given dimensions, your method should throw an IllegalArgumentException. Your code should work for an array of any size. Your method should not modify the array that is passed in.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.