Home > front end >  Add an element in a random position in a 2d array
Add an element in a random position in a 2d array

Time:12-07

I have a 2d array and I want to place in a random position, of this 2d array, an element. What I basically want to accomplish is this:

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

Where "1" is my element in a random position. What I have written so far is this:

 public void StartingLocations(){
    int[][] world = new int[5][5];
    Random randomPosition = new Random();
    int taxi = 1;
    // code to place it in a random position
    for(int i=0; i<5; i  ){
        for(int j=0; j<5; j  ){
            System.out.printf("]",world[i][j]);
        }
        System.out.println();
    }

  }
}

Any help?

CodePudding user response:

Just fill the array with zeros & then, generate random x y coordinates to fill with whatever value you like.

int randomX = randomPosition.nextInt(world.length);
int randomY = randomPosition.nextInt(world[0].length);
        
world[randomX][randomY] = 1;

Also you may want to use this as your inner print() instead of printf()

System.out.print(world[i][j]   " "); 

CodePudding user response:

Create a random number between 1 and 25 and check if i*j in your nested loop is equals to this random number. If yes, set this value to 1.

But note that you have to loop from 1 until 5, not from 0 to 4.

  • Related