RosettaCodeData/Task/100-prisoners/Mathematica/100-prisoners.math
2023-07-01 13:44:08 -04:00

51 lines
880 B
Text

ClearAll[PlayRandom, PlayOptimal]
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
sampler = indrawer = Range[100];
Do[
indrawer //= RandomSample;
found = 0;
Do[
reveal = RandomSample[sampler, 50];
If[MemberQ[indrawer[[reveal]], p],
found++;
]
,
{p, 100}
];
If[found == 100, pardoned++];
,
{n}
];
N[pardoned/n]
]
PlayOptimal[n_] :=
Module[{pardoned = 0, indrawer, reveal, found, card},
indrawer = Range[100];
Do[
indrawer //= RandomSample;
Do[
reveal = p;
found = False;
Do[
card = indrawer[[reveal]];
If[card == p,
found = True;
Break[];
];
reveal = card;
,
{g, 50}
];
If[! found, Break[]];
,
{p, 100}
];
If[found, pardoned++];
,
{n}
];
N[pardoned/n]
];
PlayRandom[1000]
PlayOptimal[10000]