Java – place numbers on random points in a 2D array

I have a 2D array with 5 rows and 5 columns I want it to place a '1' character at 8 random points in the 2D array (making it select a random row and column)

What I do is call the random class and generate a number between 0 and 4 (for the five points of the array). Then I have two for loops to run eight times (for the eight random points I want), one through the row and the other through the column

This is my code so far:

char[][] battleship = new char[5][5];
//I didn't include this but I have a for loop that populates all the rows and columns with a char of '0'
        Random random = new Random();
        int randomNum = random.nextInt(4);

        for (int i = 0; i < 8; i++)
        {
              for (int o = 0; o < 8; o++)
        {

            battleship[randomNum][randomNum] = '1';

        }
        }

The problem I get is that instead of putting '1' in eight random positions, it puts it in five consecutive positions

How can I correct it?

The following is an example of the output:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0

'1' is not in the 8 random points

What did I do wrong?

Solution

The nested loop runs 8 times at a time and iterates 64 times You do not need nested loops to do this One simple method is to use the while loop and assign 8 random points until all 8 points are photographed:

int occupiedSpots = 0;

while(occupieedSpots < 8){
    int x = random.nextInt(rows);
    int y = random.nextInt(cols);
    if(battleship[x][y] == 0){
        battleShip[x][y] = 1;
        occupiedSpots ++;
    }
}

Also make sure to generate a new random number in each iteration, otherwise you will always use the same random value

Using the while loop also ensures that all eight points are in different locations If you just use the for loop to implement it without checking, some trends may fall twice in the same position

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>