Random matrix fill between 1 and 0 in java

时间:2017-04-10 02:47:29

标签: java arrays random

I'm trying to fill randomly a two-dimensional int array with just 0's and 1's this is the method i'm using to fill my array

   private void buildMaze(){
           maze=new int[this.mazeSize][this.mazeSize];
       for(int i=0;i<this.mazeSize;i++){
            for(int j=0;j<this.mazeSize;j++){
                this.maze[i][j]=r.nextInt(2)-1;    
            }
        }
}

The problem that I'm facing is that everytime that i run my tests i get something like this:

| -1 ||  0 ||  0  |
|  0 || -1 || -1  |
|  0 || -1 || -1  |

My question here is: How could i fill the array correctly with random values ​​between 0 and 1?

3 个答案:

答案 0 :(得分:2)

Random.nextInt(int bound) method return int value between 0 (inclusive) and the specified value (exclusive). For your case It's returning value between 0 to 1, but you subtract 1 from that. So when this method return 0, you subtract 1, so It's giving you -1.

Update your code Like the below one :

this.maze[i][j]=r.nextInt(2);  

答案 1 :(得分:0)

Assuming you are using a Random, you might consider using nextBoolean() (it won't consume entropy as quickly). And you might also use a for-each loop.

private void buildMaze() {
    maze = new int[this.mazeSize][this.mazeSize];
    for (int[] row : maze) {
        for (int j = 0; j < row.length; j++) {
            row[j] = r.nextBoolean() ? 1 : 0;
        }
    }
}

Your current method r.nextInt(2)-1; generates either 0 or 1 and then subtracts one yielding the range -1, 0. You could also write

private void buildMaze() {
    maze = new int[this.mazeSize][this.mazeSize];
    for (int[] row : maze) {
        for (int j = 0; j < row.length; j++) {
            row[j] = r.nextInt(2); // <-- 0 (inclusive) to 2 (exclusive)
        }
    }
}

答案 2 :(得分:0)

you can try something like this

Math.random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0

            double j=Math.random();
            j=(j>0.5)?1:0;