Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place a string in a randomly-chosen locations in a 2D array

I'm learning Java and working on a guessingGame project based on a grid and I'm having some difficulties for my loadtargetGrid() method.

I have a 2D array of String named Grid, and what I want to place six symbols "X" in six randomly-chosen grid locations. I want to do nothing with the others location and leave them with null by default.

    public class Grid
{
public static final int ROWS      = 5;      // number of rows
public static final int COLUMNS   = 5;      // number of columns
public static final int NUMBER_OF_TARGETS = 6; // number of targets in the grid

private String[][] grid;                // the grid itself, a 2-D array of String
private Random random;                  // random number generator

//Constructor
public Grid()
{
    grid = new String[ROWS][COLUMNS];
    random = new Random();
}

//method
public void loadTargetGrid()
{
      int counter = 0;
      while(counter < NUMBER_OF_TARGETS){
           int randRow = random.nextInt(ROWS - 1);
           int randColumn = random.nextInt(COLUMNS - 1);
           grid[randRow][randColumn] = "X";
           ++ counter;
      }
}

That's what I have so far. I tried to use a while loop with a counter to place a "X" at 6 random positions. It compiles but I'm not sure if this works and I don't know how to check if my code is correct.

like image 220
Poupen Avatar asked Feb 08 '12 20:02

Poupen


2 Answers

You could potentially not have all 6 targets on the grid because you could get the same spot twice. Try this:

int counter = 0;
while(counter < NUMBER_OF_TARGETS){
    int randRow = random.nextInt(ROWS - 1);
    int randColumn = random.nextInt(COLUMNS - 1);
    if (grid[randRow][randColumn] == null) {
        grid[randRow][randColumn] = "X";
        ++ counter;
    }
}
like image 125
Dan W Avatar answered Oct 01 '22 21:10

Dan W


If you get the same randomly chosen coordinates more than once, you won't end up with NUMBER_OF_TARGETS distinct locations. You might try something like

int randRow, randColumn;
do {
  randRow = random.nextInt(ROWS);
  randColumn = random.nextInt(COLUMNS);
} while (grid[randRow][randColumn] != null);
grid[randRow][randColumn] = "X";
like image 40
Louis Wasserman Avatar answered Oct 01 '22 20:10

Louis Wasserman