简体   繁体   中英

Java - random digits inside an array of 5x5

int[][] array = new int[5][5];
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            System.out.print(1);
        }
        System.out.println();
    }

Hi guys, i have this array which prints a 5x5 1's

11111
11111
11111
11111
11111

What i would like to do is to make three (3) of those 1's as 0 randomly. Example

11101
11111
11011
10111
11111

How do I do that? Thank you in advance!

For random stuff, you can use Math.random() . It returns a random double between 0 included and 1 excluded. You could do this :

int w = 5, h = 5;
int[][] array = new int[w][h]; 
for (int i = 0; i < w; i++) { 
  for (int j = 0; j < h; j++) {  
    array[i][j] = 1;
  }  
}
for (int c = 0; c < 3; c++) {
  int i, j;
    do {
      int index = (int)(Math.random() * w * h);
      i = index / w;
      j = index % w;
    } while (array[i][j] == 0);
    array[i][j] = 0;
  }

This solution is acceptable only if the number of 0 is low compared to the total size of the array. If the number of 0 is too high this code is going to be very inefficient because we will search randomly for a value of 1

You would have to firstly initialize the array with 1s:

int[][] array = new int[5][5];
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        array[i][j] = 1;
    }
}

Then set 0s in 3 random positions:

Random random = new Random();
int a = 0;
while (a < 3) {
    int i = random.nextInt(array.length);
    int j = random.nextInt(array[0].length);
    if(array[i][j] != 0) {
        array[i][j] = 0;
        a++;
    }
}

Using this approach each entry in the array has the same chance of becoming a 0. Finally you should print the array:

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        System.out.print(array[i][j]);
    }
    System.out.println();
}

Here is a slightly different solution for fun. Create an list with numbers from 0 to 24, shuffle the list and pick the the 3 first elements from it to update the 2D array. The sequence of numbers means that not the same position in the array will be set to 0 more than once.

List<Integer> sequence = IntStream.rangeClosed(0, 24)
    .boxed()
    .collect(Collectors.toList());

Collections.shuffle(sequence);

for (int i = 0; i < 3; i++) {
    int value = sequence.get(i);
    int row  = value / 5;
    int  column = value % 5;

    array[row][column] = 0;
}

The code for generating the sequence came from this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM