How to resolve the algorithm 100 prisoners step by step in the D programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm 100 prisoners step by step in the D programming language
Table of Contents
Problem Statement
Show and compare the computed probabilities of success for the two strategies, here, on this page.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm 100 prisoners step by step in the D programming language
Source code in the d programming language
import std.array;
import std.random;
import std.range;
import std.stdio;
import std.traits;
bool playOptimal() {
auto secrets = iota(100).array.randomShuffle();
prisoner:
foreach (p; 0..100) {
auto choice = p;
foreach (_; 0..50) {
if (secrets[choice] == p) continue prisoner;
choice = secrets[choice];
}
return false;
}
return true;
}
bool playRandom() {
auto secrets = iota(100).array.randomShuffle();
prisoner:
foreach (p; 0..100) {
auto choices = iota(100).array.randomShuffle();
foreach (i; 0..50) {
if (choices[i] == p) continue prisoner;
}
return false;
}
return true;
}
double exec(const size_t n, bool function() play) {
size_t success = 0;
for (int i = n; i > 0; i--) {
if (play()) {
success++;
}
}
return 100.0 * success / n;
}
void main() {
enum N = 1_000_000;
writeln("# of executions: ", N);
writefln("Optimal play success rate: %11.8f%%", exec(N, &playOptimal));
writefln(" Random play success rate: %11.8f%%", exec(N, &playRandom));
}
You may also check:How to resolve the algorithm Base64 decode data step by step in the Wren programming language
You may also check:How to resolve the algorithm Extend your language step by step in the ABAP programming language
You may also check:How to resolve the algorithm Generic swap step by step in the AmigaE programming language
You may also check:How to resolve the algorithm Accumulator factory step by step in the Sidef programming language
You may also check:How to resolve the algorithm Introspection step by step in the Factor programming language