@anonymous/

AltruisticEminentGalago

Java

No description

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * Monte Carlo estimation for Joe Z's solution here:
 * 
 * http://puzzling.stackexchange.com/questions/16/100-prisoners-names-in-boxes?rq=1
 *
 * Created by Brian Risk on 5/25/16.
 */
class Main
{
	public static int totalRuns = 100000;
	public static int numberOfPrisoners = 100;
	public static int numberOfGuesses = 50;
	
	/**
	 * Prints the probability (where 1 == 100%) that this strategy
	 * will be successful.
	 */
    public static void main(String [] args) {
        Random random = new Random(1);
        int successCount = 0;
        for (int i = 0; i < totalRuns; i++) {
            if (findsName(random)) successCount++;
        }
        double ratio = (double) successCount / totalRuns;
        System.out.println(ratio);
    }

	/**
	 * The order that the prisoners go in corresponds to their box index.
	 * The first prisoner starts with the first box (0th index) and so on.
	 * If they do not find their number in their box, then they move to the
	 * ntext box dictated by the number they just found.  For example, prisoner
	 * 1 opens the first box but finds the number 3.  That prisoner moves then to the 3rd box.
	 * 
	 * returns true if and only if each prisoner ended up finding their number within
	 * the limited amount of guesses.
	 */
    public static boolean findsName(Random random) {
    	// create a list of randomly ordered numbers
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < numberOfPrisoners; i++) {list.add(i); }
        Collections.shuffle(list, random);
        int trueCount = 0;
        for (int prisonerNumber = 0; prisonerNumber < numberOfPrisoners; prisonerNumber++) {
        	// the first guess is the prisoner's own number
            int guessNumber = prisonerNumber;
            boolean found = false;
            for (int guessIndex = 0; guessIndex < numberOfGuesses; guessIndex++) {
                if (list.get(guessNumber) == prisonerNumber) {
                    trueCount++;
                    found = true;
                    break;
                }
                guessNumber = list.get(guessNumber);
            }
            if (found) continue;
        }
        return trueCount == numberOfPrisoners;
    }
}