0

I need to create a multidimensional array in Java but with a random lenght of colums.

For example let's suppose the random lengths are 3, 2, 4 and 1, so we would have something like this:

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

I have tried this, but it does not create a random length for each column:

int articles[][] = new int[50][(int) Math.floor(Math.random() * 30 + 1)];

Does anyone know how to achieve this?

Note: The array will always have 50 rows, I just need each column to be random.

3 Answers 3

1

Try to initialize your arrays in array, inside any loop, for example:

int articles[][] = new int[50][];
for (int i = 0; i < 50; i++) {
    articles[i] = new int[(int) Math.floor(Math.random() * 30 + 1)];
}
Sign up to request clarification or add additional context in comments.

Comments

0

To create an array with a constant count of rows, but a random row length, and fill it with random numbers:

int rows = 5;
int[][] arr = IntStream
        .range(0, rows)
        .mapToObj(i -> IntStream
                .range(0, (int) (Math.random() * 10))
                .map(j -> (int) (Math.random() * 10))
                .toArray())
        .toArray(int[][]::new);
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
[3, 8]
[2, 7, 6, 8, 4, 9, 3, 4, 9]
[5, 4]
[0, 2, 8, 3]
[]

Comments

0
  1. I recommend you study the utility methods in java.util.Arrays. It is a goldmine of helper methods for working with arrays. Since 1.8 it has this one:

    int articles[][] = new int[50][];
    Arrays.setAll(articles, i -> new int[(int)Math.floor(Math.random() * 30 + 1)]);
    

    Using a lambda is not more efficient than a plain loop in this problem case but often lends itself to neater overall solutions.

  2. I would also recommend not scaling double to int yourself (see the source of Random.nextInt() and decide for yourself).

    Random r = new Random();
    int articles[][] = new int[50][];
    Arrays.setAll(articles, i -> new int[r.nextInt(30)]);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.