Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a number at random spots in 2D array

I have a 2D Array that has 5 rows and 5 columns. I want it so that at 8 random spots in that 2D array (make it pick a random row and column) to put a char of '1'.

What I did was call the Random class and generate a number between 0 and 4 (for the 5 spots of the array) then I have two for loops that run 8 times (for the 8 random spots I want), one that goes through the row, the other through the column.

This is the code I have 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 issue I am getting is that instead of it putting the '1' at 8 random spots, it's putting in 5 spots back to back.

How do I correct this?

Here 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

The '1' isn't in 8 random spots.

Where did I go wrong?

like image 832
Edwin Torres Avatar asked Dec 08 '25 05:12

Edwin Torres


1 Answers

Having nested loop running 8 times each will iterate it 64 times. You don't need nested loops to do that. One of the easy ways will be using a while-loop and distribute the 8 random spots till all 8 spots are taken:

int occupiedSpots = 0;
Random random = new Random();

while(occupiedSpots < 8){
    int x = random.nextInt(array.length);
    int y = random.nextInt(array[0].length);
    if(battleship[x][y] == 0){
        battleship[x][y] = 1;
        occupiedSpots++;
    }
}

Also ensure you are generating new random numbers in every iteration, else you will always be using the same random values.

Using a while-loop also ensures all 8 spots are on different locations. If you simply implement it with a for-loop without checking, there is a tendency some spots may fall on the same location twice.

like image 122
user3437460 Avatar answered Dec 09 '25 19:12

user3437460