Skip to content

Instantly share code, notes, and snippets.

@toriannnn
Created November 23, 2017 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toriannnn/b07673856ad9e67b0cf190816f9a83f1 to your computer and use it in GitHub Desktop.
Save toriannnn/b07673856ad9e67b0cf190816f9a83f1 to your computer and use it in GitHub Desktop.
//Import a Scanner
import java.util.Scanner;
public class Bean {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Add a scanner
Scanner input = new Scanner(System.in);
//Ask how many balls are being dropped
System.out.print("Enter the number of balls to drop: ");
int numberOfBalls = input.nextInt();
String[] ballPaths = new String[numberOfBalls];
//Ask how many slots are in the bean machine
System.out.print("Enter the number of slots in the bean machine: ");
int numberOfSlots = input.nextInt();
int[] slots = new int[numberOfSlots];
// display the ball paths
for (int i = 0; i < numberOfBalls; i++) {
ballPaths[i] = printPath(slots);
System.out.printf("%10s\n", ballPaths[i]);
}
// display the game
System.out.println("");
printHistogram(slots, numberOfBalls);
}
public static String printPath(int[] slot) {
StringBuilder ballPath = new StringBuilder();
for (int i = 0; i < slot.length - 1; i++) {
int random = (int)(Math.random() * 10) % 2;
if (random > 0) ballPath.append("R");
else ballPath.append("L");
}
int position = onePath(ballPath.toString(), 'R');
slot[position]++;
return ballPath.toString();
}
public static int onePath(String str, char a) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == a) count++;
}
return count;
}
public static void printHistogram(int[] slots, int numberOfBalls) {
while (!max(slots)) {
if (isRowEmpty(slots, numberOfBalls)) {
numberOfBalls--;
continue;
}
for (int i = 0; i < slots.length; i++) {
if (slots[i] >= numberOfBalls) {
System.out.printf("%2c", 'O');
slots[i]--;
}
else System.out.printf("%2c", ' ');
}
numberOfBalls--;
System.out.println("");
}
}
public static boolean max(int[] slots) {
for (int slot : slots) {
if (slot != 0) {
return false;
}
}
return true;
}
public static boolean isRowEmpty(int[] slots, int rowNum) {
for (int slot : slots) {
if (slot == rowNum) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment