Skip to content

Instantly share code, notes, and snippets.

@markrendle
Created July 6, 2022 17:50
Show Gist options
  • Save markrendle/c711e4472cc89fd5ed7a3709af4488b6 to your computer and use it in GitHub Desktop.
Save markrendle/c711e4472cc89fd5ed7a3709af4488b6 to your computer and use it in GitHub Desktop.
Prisoners Riddle
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