So, what I am trying to do is to fill a 2D array with zeros in random places a specific amount of times. Let's say that it has to be 20 zeros in an array of 90 places. What I have done so far is to declare a 2D array and fill it with random numbers. And my next thought was to simply choose random positions and replace them with zeros. Any idea how I could do that?
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i ) {
for (int j = 0; j < myboard[i].length; j ) {
myboard[i][j] = (int) (Math.random() * 10);
}
}
CodePudding user response:
A pseudo code would look like:
while (num_zeros_filled < 20):
row = random()%total_rows
col = random()%total_cols
if (arr[row][col] == 0): # already filled in with 0
continue
else:
arr[row][col] = 0
num_zeros_filled = 1
This, however, could take infinite time theoretically if only those cells are generated which have already been filled with 0. A better approach would be to map the two-dimensional array into a 1-d array, and then sample out only from those cells which haven't been filled with 0 yet.
CodePudding user response:
It is a rather simple way to achieve the goal, but it should do the job. So you need to get the length of each row. After you have done that you can call a function that will give you a random number between some start point and the length of the row. Here is some code sample to show you what I mean:
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
public class Example {
public static void main(String []args) {
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i ) {
for (int j = 0; j < myboard[i].length; j ) {
// fill the row with random vals
myboard[i][j] = GetRandomNumber(0, myboard[i].length);
}
// sneak as much zeros as your heart content
int random = GetRandomNumber(0, myboard[i].length);
myboard[i][random] = 0;
}
System.out.println(Arrays.deepToString(myboard));
}
private static int GetRandomNumber(int min, int max) {
/*
min is the start point
max is the curr row len
*/
return ThreadLocalRandom.current().nextInt(min, max);
}
}