user6217303
user6217303

Reputation: 27

Placing Random Characters on an Array Board in Java

I'm making a simple array board. I'm trying to make the character '$' appear 10 times in random places, and 'R' appear only once in random places. I've continued to change the randomization, but I know I'm approaching this the wrong way. The characters appear in random places and in random amounts.

Edit: I forgot to mention that I am trying to maintain my nested for loop.

Edit: I placed my the last if statements I tried in the code instead of my placeholders.

Here is my code:

import java.util.*;
public class board
{
    public static void main(String[] args)
    {
        char $;
        char R;
        char board[][] = new char[10][10];

        for(int x = 0; x < board.length; x++)
        {
            for(int i = 0; i < board.length; i++)
            {
                double random = Math.random();
                if(random >.01 && random <=.10)
                {
                    board[x][i] = 'R';
                }
                else if(random > .01 && random <= .15)
                {
                    board[x][i] = '$';
                }
                else {
                    board[x][i] = '.';
                }
                System.out.print(board[x][i] + " ");
            }
            System.out.println("");
        }
    }
}

Upvotes: 0

Views: 1330

Answers (2)

a.deshpande012
a.deshpande012

Reputation: 744

What happens is that it places it randomly, but you have no code that controls how many are generated. You should have a counter for $ and a counter for R, and when you have enough, it shouldn't print that character anymore. Also, the current code can overwrite previously placed characters. You should probably add in an if-statement that checks the current value of the address that is about to be replaced, and make sure it's empty first.

Upvotes: 0

sprinter
sprinter

Reputation: 27966

You won't get random placing by iterating through all positions and comparing to a probability. What happens if too many are placed or not enough? A better algorithm is to generate random positions until you have enough on the board. Something like:

while (count < target) {
    int x = rand.getInt(size);
    int y = rand.getInt(size);
    if (board[x][y] == '.') {
        board[x][y] = '$';
        count++;
    }
}

That will automatically skip positions that have already been assigned the character and will continue until enough have been placed.

This can be made into a method that is used for both placements:

private void place(char toPlace, int target) {
    int count = 0;
    while (count < target) {
        int x = rand.getInt(size);
        int y = rand.getInt(size);
        if (board[x][y] == '.') {
            board[x][y] = toPlace;
            count++;
        }
    }
}

place('M', 1);
place('$', 10);

Upvotes: 1

Related Questions