I could not find a solution from my book's website (student-level access) but I feel that I am missing something that I'm supposed to learn from this exercise.
Instructions: Balls are dropped from the opening of the board. Every time a ball hits a nail, it has a 50% chance of falling to the left or to the right. The piles of balls are accumulated in the slots at the bottom of the board.
Book's example:
Enter the number of balls to drop: 5 Enter the number of slots in the bean machine: 7 LRLRLRR RRLLLRR LLRLLRR RRLLLLL LRLRRLR 0 0 000
My attempt:
import java.util.*;
public class BeanMachine {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of balls to drop: ");
int numberOfBalls = input.nextInt();
System.out.print("Enter the number of slots in the bean machine: ");
int numberOfSlots = input.nextInt();
//Simulate drops
int[] slots = new int[numberOfSlots];
for (int i = 0; i < numberOfBalls; i++) {
simulateDrop(slots);
}
//Display histogram
for (int i = numberOfBalls; i > 0; i--) {
for (int j = 0; j < slots.length; j++) {
if (slots[j] >= i) {
System.out.print("0");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void simulateDrop(int[] slots) {
StringBuilder path = new StringBuilder(slots.length);
int slotIndex = 0;
int numberOfNails = slots.length - 1;
for (int i = 0; i < numberOfNails; i++) {
int direction = (int)(Math.random() * 2);
if (direction == 0) {
path.append("L");
}
else {
path.append("R");
slotIndex++;
}
}
System.out.println(path.toString());
slots[slotIndex]++;
}
}