Chutes and Ladders Game Random Placement Issue
java, methods, random
Solution
Firstly, you wrote:
for(int i = 0; i <= chutes; i++)
board[rand.nextInt(board.length)] = "C" + chutes;
The assignment statement in the loop will run chutes+1 times. (Eleven times in your case.) [Use `i < chutes` instead.] This is the same in your ladders code. This explains why you might have up to 11 chutes or ladders when the code is done running.
Secondly, you do not take care to prevent the same space being assigned a chute or ladder multiple times. `rand.nextInt(board.length)` is not guaranteed to generate unique values each time it is run (otherwise it wouldn't really be random.) This explains why you may not see as many as 11 chutes and ladders when the code is done running.
To make this clearer, put a constant value in there:
for(int i = 0; i < chutes; i++)
board[11] = "C" + chutes;
and notice that you end up with one chute (at space eleven)--unless the ladder code overwrites it with a ladder.
Hope that helps.
Good luck!
Problem
I'm a student, working on a Chutes and Ladders game. I'm using methods to determine how many chutes and ladders should be placed on the game board. I'm specifying 10 for each in main using parameters but I keep getting anywhere from 6 to 11 placed across the board. Is there something going on with the two methods interfering with each other? Or is there a problem with the way I set up the for loops for random placement? I'm new to this site, please let me know if you need more clarification, I didn't want to place the whole program in here. Thanks. ``` //main ChutesAndLadders cl = new ChutesAndLadders(); cl.setBoard(new String[100]); cl.makeChutes(10); cl.makeLadders(10); //methods public String [] board; private int chutes, ladders; public int position; public Random rand = new Random(); //set board public void setBoard(String [] n){ board = n; for(int i = 0; i < board.length; i++) board[i] = " "; } //set and place chutes public void makeChutes(int n){ chutes = n; for(int i = 0; i <= chutes; i++) board[rand.nextInt(board.length)] = "C" + chutes; } //set and place ladders public void makeLadders(int n){ ladders = n; int lcell = 0; for(int i = 0; i <= ladders; i++) board[rand.nextInt(board.length)] = "L" + ladders; ```