JAVA:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections;
public class Main {
public static void main(String[] args) {
int i=0;
ArrayList<Prisoner> prisoners = readFromFile("hats.txt");
Collections.reverse(prisoners);
/**
* What the first prisoner sees.
*/
boolean first = prisoners.get(0).getOddAhead();
boolean oddPassed= false;
boolean says = false;
for(Prisoner p: prisoners){
System.out.print("prisoner "+(i++)+": "+(p.getColor()?"white":"black"));
says = p.findColor(oddPassed, first);
System.out.println(" says : "+ (says?"white":"black")+" lives? "+(says==p.getColor()));
if(says!=p.getColor()){
System.err.println("DIED");
}
oddPassed = (oddPassed^says);
}
}
/** * * @param filename String, name of the file to read the data from. * @return */ static private ArrayList<Prisoner> readFromFile(String filename){
ArrayList<Prisoner> prisoners = new ArrayList<>();
BufferedReader in;
try {
in = new BufferedReader(new FileReader(filename));
String line;
int i=0;
while((line = in.readLine()) != null)
{
if(line.compareToIgnoreCase("white")==0){
prisoners.add(new Prisoner(true, (i++%2==1)));
}else{
prisoners.add(new Prisoner(false, (i%2==1)));
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return prisoners;
}
}
final class Prisoner {
/**
/** * True if the number of white hats the prisoner sees in front of him is odd */ private boolean oddAhead;
Prisoner(boolean white, boolean oddAhead){ this.white = white; this.oddAhead = oddAhead; }
/** * {(first XOR previousOdd) XOR oddAhead} * is equal to {(first + previousOdd + oddAhead)%2} * assuming true == 1 and false == 0 * * @param previousOdd If the number of passed white hats is Odd then takes true, false otherwise * @param first True if the first prisoner saw odd number of white hats * @return True if the color of the present prisoner is white, false otherwise */ public boolean findColor(boolean previousOdd, boolean first){ return (firstpreviousOdd)oddAhead; }
public boolean getColor(){
return white;
}
public boolean getOddAhead(){
return oddAhead;
}
}