import java.util.Random; // Random number module in Java /* Author: Atul Prakash. */ /* * This code simulates a well-known game that is played as follows. * You put in some * unknown number of red and blue balls in a bag. You then take out two * balls at random from the bag. If they are both the same color, you toss * both of them and put in a blue ball back in the bag (assume * infinite supply of extra balls). If they are * different colors, you toss the blue one aside and put in the red ball * back in the bag. * You keep repeating the above process till only one ball is left. Note * that the # of balls reduces by one at every round, so eventually, you * will end up with one ball. * If the final color of the ball is red, Reds win. Else Blues win * The goal is to discover a loop invariant that helps us precisely * predict who will win, based on the initial counts of the balls. */ enum Color {RED, BLUE}; class BallGame { public static void main(String[] args) { // initialize the # of balls in the bag for each color // to random values // between 0 and 99. Could be any random integers. Random r = new Random(); int redcount = r.nextInt(100); int bluecount = r.nextInt(100); System.out.println("redcount = " + redcount); System.out.println("bluecount = " + bluecount); /* as long as the number of balls in the bag is more than 1, * keep taking out two balls. If they are both of the same * color, toss them away and put a blue ball back in the bag. * If different, then toss away the blue ball. Put the red * one back */ Color firstballcolor; Color secondballcolor; assert (redcount >= 0 && bluecount >= 0); while (redcount + bluecount > 1) { // pick a value between 0 and the # of balls. If // the value is less than redcount, assume that a red // ball was taken out. Else, a blue ball. int pickone = r.nextInt(redcount + bluecount); if (pickone < redcount) { // red ball taken out firstballcolor = Color.RED; redcount--; } else { // blue ball taken out firstballcolor = Color.BLUE; bluecount--; } int picktwo = r.nextInt(redcount + bluecount); if (picktwo < redcount) { // red ball taken out secondballcolor = Color.RED; redcount--; } else { // blue ball taken out secondballcolor = Color.BLUE; bluecount--; } if (firstballcolor == secondballcolor) { // same colors. Put back a blue one bluecount++; } else { // different colors. Put back the red one. redcount++; } } // end of loop. // Exactly one ball must remain at the end. assert ((redcount == 1 && bluecount == 0) || (redcount == 0 && bluecount == 1)); // Declare the winner. if (redcount == 1) { System.out.println("Reds win"); } else { System.out.println("Blues win"); } } }