0

I have a multidimensional array where the second dimension is not always the same length.

Is it possible to initialize an array where you first create the first part like this

I am using this array to define the length of each row in the matrix.

int[] config = {4,4,4,3,2,4};
boolean[][] array = new boolean[config.lenght][];

and then after loop over the array and create the subarrays with the desired length?

for(int i = 0; i<config.length; i++)
    boolean[i][] = new boolean[config[i]];

PS: I will not use ArrayList

mama
  • 2,046
  • 1
  • 7
  • 24

4 Answers4

1
public static int[][] generate(int[] config) {
    int[][] arr = new int[config.length][];
    Random random = new Random();

    for (int row = 0; row < arr.length; row++) {
        arr[row] = new int[config[row]];

        for (int col = 0; col < arr[row].length; col++)
            arr[row][col] = random.nextInt(100);
    }

    return arr;
}

Output:

[
  [97, 80, 78, 88],
  [31, 97, 34, 39],
  [67, 92, 89, 0],
  [29, 96, 72],
  [68, 77],
  [7, 65, 68, 51]
]
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

You can assign any single D array to a 2D array of the same type.


int[] s = {1,2,3,4,5,6};

int[][] twoD = new int[s.length][];

for (int i = 0; i < v.length; i++) {
   twoD[i] = new int[]{s[i]}; // new array of one element of the `s` array
}

for ( int[] s : twoD) {
  System.out.println(s);
}

Prints

[1]
[2]
[3]
[4]
[5]
[6]

or

System.out.println(Arrays.deepToString(twoD));

Prints

[[1], [2], [3], [4], [5], [6]]
WJS
  • 36,363
  • 4
  • 24
  • 39
0

I do not fully understand the question, but I have a suggestion for a solution like this.

            int[] config = {4,4,4,3,2,4};
            int[][] array = new int[config.length][config.length];
            for(int i = 0 ; i<config.length ; i++){
                array[i][0] = config[i];
            }

array output:

400000
400000
400000
300000
200000
400000
0

You can also use streams:

int[] config = {4,4,4,3,2,4};
boolean[][] myArr = Arrays.stream(config).mapToObj(i -> new boolean[i]).toArray(boolean[][]::new);
    
for(boolean[] b : myArr){
    System.out.println(Arrays.toString(b));
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28