# Dynamic generation of a 2D array with different column lengths

For testing purposes I currently ran into a situation, where I had to randomly create a two dimensional array with columns of potentially different lengths for each row. For example consider this illustration:

0.0    0.1           length = 2

1.0    1.1    1.2    length = 3

2.0                  length = 1

I know how to create such an array in a non random way:

new Float[][] {
{ 0.0, 0.1 },
{ 1.0, 1.1, 1.2 },
{ 2.0 }
};

And generating each value of the matrix randomly, given a method anyFloat() which returns a randomly generated Float value, is easy as well:

new Float[][] {
{ anyFloat(), anyFloat() },
{ anyFloat(), anyFloat(), anyFloat() },
{ anyFloat() }
};

But the challenge is to do something like this for arrays (which I guess is not possible due to the fact, that we have to know the amount of required memory when we create an array):

List<List<Float>> matrix = new ArrayList<List<Float>>();
int rows = anyRows();
for (int row = 0; row < rows; row++) {
}

Now my question is: can we achieve this for arrays or convert the matrix into an array?

Yes, it can be done.

The trick is knowing that an n-dimensional array only needs to have the size of its first dimension initialized immediately. For example:

float[][] matrix = new float[randSz()][];

You can then populate that first dimension of the n-dimensional array with pointers to other arrays in a for-loop:

for (int i = 0; i < matrix.length; ++i) {
matrix[i] = new float[randSz()];
}

Here's why this is possible. An n-dimensional array in Java is stored as an array of pointers to other arrays. So in memory you'd have something like this:

2d_array:
[ arr_pointer_1 ][ arr_pointer_2 ][ arr_pointer_3 ]

arr_pointer_1:
[ 0.0 ][ 0.1 ]

arr_pointer_2:
[ 1.0 ][ 1.1 ][ 1.2 ]

arr_pointer_3:
[ 2.0 ]

Keep in mind that the pointers in the first dimension don't need to be initialized immediately - they can start off as null pointers.

matrix_array:
[ null ][ null ][ null ]

Here's a full example that matches the format in which you posed the problem:

private static final Random RAND = new Random(new Date().getTime());
private static final int ROW_UPPER_BOUND = 10;
private static final int COL_UPPER_BOUND = 8;

/**
* @param args
*/
public static void main(String[] args) {
float[][] matrix;
int rows = anyRows();
// Create array of null "pointers".
matrix = new float[rows][];
for (int row = 0; row < rows; ++row) {
// Assign array "pointers" to first dimension of matrix.
matrix[row] = anyArrayOfFloats();
}
System.out.println(matrixToString(matrix));
}

public static int anyRows() {
return RAND.nextInt(ROW_UPPER_BOUND) + 1;
}

public static float anyFloat() {
return RAND.nextFloat();
}

public static float[] anyArrayOfFloats() {
int sz = RAND.nextInt(COL_UPPER_BOUND) + 1;
float[] arr = new float[sz];
for (int i = 0; i < sz; ++i) arr[i] = anyFloat();
return arr;
}

public static String matrixToString(float[][] matrix) {
StringBuilder builder = new StringBuilder();
builder.append("[");
boolean first = true;
for (float[] fArr: matrix) {
if (first) {first = false;} else {builder.append(", ");}
builder.append(Arrays.toString(fArr));
}
builder.append("]");
return builder.toString();
}