Skip to content

Instantly share code, notes, and snippets.

@randomsync
Created January 18, 2012 22:24
Show Gist options
  • Save randomsync/1636207 to your computer and use it in GitHub Desktop.
Save randomsync/1636207 to your computer and use it in GitHub Desktop.
Java code to demonstrate the solution to Prisoners & Hats puzzle (http://randomsync.net/2011/09/puzzler-prisoners-and-hats-and-jungle.html)
/*
* http://www.cartalk.com/content/puzzler/transcripts/201127/index.html
* http://www.cartalk.com/content/puzzler/transcripts/201127/answer.html
*/
import java.util.Random;
public class PrisonerPuzzler {
static int SIZE = 30;
public static void main(String[] args) {
int correctGuesses = 0;
StringBuffer pRow = new StringBuffer(SIZE);
StringBuffer prevGuesses = new StringBuffer(SIZE - 1);
char currGuess;
Random rnd = new Random(System.currentTimeMillis());
// ---print the series
System.out.print("Series:\t");
for (int i = 0; i < SIZE; i++) {
if (rnd.nextInt(2) == 0) // 0=black, 1=white
pRow.append('B');
else
pRow.append('W');
System.out.print(pRow.charAt(i) + " ");
}
// ---strategy
System.out.print("\nStrat:\t");
for (int i = 0; i < SIZE; i++) {
currGuess = guessStrategy(prevGuesses.toString(),
pRow.substring(i + 1));
System.out.print(currGuess + " ");
if (currGuess == pRow.charAt(i))
correctGuesses++;
prevGuesses.append(currGuess);
}
System.out.print("\nCorrect Guesses=" + correctGuesses);
}
public static char guessStrategy(String prevGuesses, String remArr) {
// random
// Random rnd = new Random(System.currentTimeMillis());
// if (rnd.nextInt(2) == 0) //0=black, 1=white
// return 'B';
// else return 'W';
int numB = getNumOfChars(remArr, 'B');
int numPrevB;
if (prevGuesses.length() == 0) { // initial guess
if (numB % 2 == 0)
return 'W'; // if B is even, return W
else
return 'B'; // else return B
} else {
// strategy: if previously even number of people have said black,
// and I see even black hats, I have a white hat, else black
numPrevB = getNumOfChars(prevGuesses, 'B');
if (numPrevB % 2 == 0) {
if (numB % 2 == 0)
return 'W';
else
return 'B';
} else {
if (numB % 2 == 0)
return 'B';
else
return 'W';
}
}
}
/**
* @param arr
* @param ch
* @return number of times the specified char appears in the array
*/
public static int getNumOfChars(String arr, char ch) {
int num = 0;
for (int i = 0; i < arr.length(); i++) {
if (arr.charAt(i) == ch)
num++;
}
return num;
}
}
@randomsync
Copy link
Author

Here's the output for one of the runs: (you're bound to get alteast 29 correct answers)

Series: B W B W B B B W W B W W W W B B W B B W W B B B W B W B W W
Strat: W W B W B B B W W B W W W W B B W B B W W B B B W B W B W W
Correct Guesses=29

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment