I am trying to generate 2d random array similar to:
array[random][random2]
{
{1, 2},
{6, 4},
{-1, 5},
{-2}
}
the values in the array are also random, It may have -9 to -1 to 1 to 9 numbers.
Here's what i got:
public class gen2dArray {
public static void main(String args[]) {
Random random = new Random();
int n = 0;
int max = 5, min = 1;
n = random.nextInt(max - min + 1) + min;
int maxRowCol = (int)Math.pow(2,n);
int RandMaxRows = random.nextInt(maxRowCol);
int RandMaxColums = random.nextInt(maxRowCol);
int [][] array = new int [RandMaxRows][RandMaxColums];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < random.nextInt(array[i].length)+1; j++) {
array[i][j] = random.nextInt(9) + 1;
}
}
System.out.println(Arrays.deepToString(array));
}
}
Output 1:
[
[4, 4, 5, 0],
[2, 3, 0, 0]
]
Output 2:
[
[5, 2, 1, 0, 0],
[3, 4, 2, 0, 0],
[3, 1, 5, 0, 0, 0],
[4, 3, 2, 0, 0]
]
There are few problems,
- Some outputs are just [[]] or []
2.
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300)
at gen2dArray.main(gen2dArray.java:23)
- Getting the zeros in the array. There should be no zeros.
Output one has to be like:
[
[4, 4, 5],
[2, 3]
]