Simulation of the Prisoners riddle as seen on Veritasium YouTube
Created
July 6, 2022 17:50
-
-
Save ThatRendle/c711e4472cc89fd5ed7a3709af4488b6 to your computer and use it in GitHub Desktop.
Prisoners Riddle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Cryptography; | |
var random = RandomNumberGenerator.Create(); | |
var boxes = Enumerable.Range(0, 100).OrderBy(_ => Randomize()).ToArray(); | |
for (int i = 0; i < 100; i++) | |
{ | |
int opened = 0; | |
int b = i; | |
while (true) | |
{ | |
++opened; | |
if (boxes[b] == i) break; | |
b = boxes[b]; | |
} | |
if (opened > 50) | |
{ | |
Console.WriteLine($"Prisoner {i+1} failed."); | |
return; | |
} | |
} | |
Console.WriteLine("All prisoners succeeded."); | |
long Randomize() | |
{ | |
Span<byte> span = stackalloc byte[8]; | |
random.GetNonZeroBytes(span); | |
return BitConverter.ToInt64(span); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment