Search code examples
javainitializer

Random Array generation


I am trying to create an array and have it filled with 0 or 1's randomly throughout the array. Below you will find the code. I am very new to java so any help would be greatly appreciated.

private static void randHouse() {
    int rows = 4;
    int columns = 5;
    int i = 0;
    int y = 0;
    int [][] myList = {
            {0,0,0,0,0},
            {0,0,0,0,0},
            {0,0,0,0,0},
            {0,0,0,0,0}
    };
    System.out.println(Arrays.deepToString(myList)); // just prints the array

    for (i : rows); {
        for (y : columns);{
            myList[i][y] = (int)random() * 10;
        }
    }
}

I am currently getting the error : java: bad initializer for for-loop


Solution

  • It is easiest (imo) to use streams.

    int r = 4;
    int c = 5;
    int[][] result = randHouse(r,c);
    for (int[] row : result) {
        System.out.println(Arrays.toString(row));
    }
    

    Prints something like

    [1, 1, 0, 1, 1]
    [0, 1, 0, 0, 1]
    [1, 0, 1, 1, 1]
    [1, 0, 1, 0, 0]
    
    • The IntStream iterates over the rows
    • the inner rand call generates each row of 1's and 0's.
    • then they are combined into an array of arrays.
    private static int[][] randHouse(int r, int c) {
        Random rand = new Random();
        return IntStream.range(0, r)
                .mapToObj(i -> rand.ints(c, 0, 2).toArray())
                .toArray(int[][]::new);
    }
    

    Note: In your original problem, (int)Math.random()*10 will first convert the random value to 0 and then multiply by 10. So all you get are zeros. If you did the following (int)(Math.random()*10) you would get a value between 0 and 9 inclusive. Instead of 10, you should use 2.