100 prisoners: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 34:
{{trans|Python}}
 
<langsyntaxhighlight lang=11l>F play_random(n)
V pardoned = 0
V in_drawer = Array(0.<100)
Line 78:
print(‘ Simulation count: ’n)
print(‘ Random play wins: #2.1% of simulations’.format(play_random(n)))
print(‘Optimal play wins: #2.1% of simulations’.format(play_optimal(n)))</langsyntaxhighlight>
 
{{out}}
Line 89:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program prisonniex64.s */
Line 347:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
Random strategie : 0 sur 1000
Line 354:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=Ada>
package Prisoners is
 
Line 378:
 
end Prisoners;
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Ada>
pragma Ada_2012;
with Ada.Numerics.Discrete_Random;
Line 508:
 
end Prisoners;
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Ada>
with Prisoners; use Prisoners;
with Ada.Text_IO; use Ada.Text_IO;
Line 527:
Put ("%");
end Main;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 536:
{{works with|GNU APL|1.8}}
 
<langsyntaxhighlight lang=Ada>
∇ R ← random Nnc; N; n; c
(N n c) ← Nnc
Line 562:
5000 timesSimPrisoners 100 50
 
</syntaxhighlight>
</lang>
 
=={{header|Applesoft BASIC}}==
Line 588:
Actual test of 4000 trials for each method were run on the KEGSMAC emulator with MHz set to No Limit.
 
<langsyntaxhighlight lang=gwbasic>0 GOTO 9
 
1 FOR X = 0 TO N:J(X) = X: NEXT: FOR I = 0 TO N:FOR X = 0 TO N:T = J(X):NP = INT ( RND (1) * H):J(X) = J(NP):J(NP) = T: NEXT :FOR G = 1 TO W:IF D(J(G)) = I THEN IP = IP + 1: NEXT I: RETURN
Line 616:
1110 GET K$
1120 Q = K$ <> "Y" AND K$ <> CHR$(ASC("Y") + 32) : NEXT Q
</syntaxhighlight>
</lang>
 
{{out}}
Line 640:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* program prisonniers.s */
Line 875:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
Random strategie : 0 sur 1000
Line 881:
</pre>
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>NumOfTrials := 20000
randomFailTotal := 0, strategyFailTotal := 0
prisoners := [], drawers := [], Cards := []
Line 937:
MsgBox % "Number Of Trials = " NumOfTrials
. "`nOptimal Strategy:`t" (1 - strategyFailTotal/NumOfTrials) *100 " % success rate"
. "`nRandom Trials:`t" (1 - randomFailTotal/NumOfTrials) *100 " % success rate"</langsyntaxhighlight>
Outputs:<pre>Number Of Trials = 20000
Optimal Strategy: 33.275000 % success rate
Line 944:
=={{header|BASIC256}}==
{{works with|BASIC256|2.0.0.11}}
<langsyntaxhighlight lang=BASIC256>
O = 50
N = 2*O
Line 1,023:
print "Smart choices: "; total;" out of ";iterations
print "Observed ratio: "; total/iterations; ", expected ratio with N=2*O: greater than about 0.30685": REM for N=100, O=50 particularly, about 0.3118
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,034:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang=bcpl>get "libhdr"
 
manifest $(
Line 1,105:
run(d, " Random", randoms, size, simul, tries)
run(d, "Optimal", optimal, size, simul, tries)
$)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,112:
 
=={{header|C}}==
<syntaxhighlight lang=C>
<lang C>
#include<stdbool.h>
#include<stdlib.h>
Line 1,252:
}
 
</syntaxhighlight>
</lang>
<pre>
$ gcc 100prisoners.c && ./a.out 100 50 10000
Line 1,270:
=={{header|C sharp|C#}}==
{{trans|D}}
<langsyntaxhighlight lang=csharp>using System;
using System.Linq;
 
Line 1,337:
}
}
}</langsyntaxhighlight>
{{out}}
<pre># of executions: 1000000
Line 1,344:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <cstdlib> // for rand
#include <algorithm> // for random_shuffle
#include <iostream> // for output
Line 1,419:
system("PAUSE"); // for Windows
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Random strategy: 0 %
Line 1,425:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=Clojure>(ns clojure-sandbox.prisoners)
 
(defn random-drawers []
Line 1,489:
(let [{:keys [random-successes optimal-successes run-count]} (simulate-n-runs 5000)]
(println (str "Probability of survival with random search: " (float (/ random-successes run-count))))
(println (str "Probability of survival with ordered search: " (float (/ optimal-successes run-count))))))</langsyntaxhighlight>
 
{{out}}
Line 1,498:
 
=={{header|CLU}}==
<langsyntaxhighlight lang=clu>% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
Line 1,598:
show(" Random", simulations, prisoners, tries, rand_strat)
show("Optimal", simulations, prisoners, tries, opt_strat)
end start_up</langsyntaxhighlight>
{{out}}
<pre> Random: 0 out of 50000, 0.00%
Line 1,618:
The key here is avoiding the use of GOTO as a means of exiting a loop early.
 
<langsyntaxhighlight lang=gwbasic>
10 rem 100 prisoners
20 rem set arrays
Line 1,678:
4030 r=int(rnd(1)*100)+1:t=dr(i):dr(i)=dr(r):dr(r)=t:next
4040 return
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,701:
{{trans|Racket}}
 
<langsyntaxhighlight lang=lisp>
(defparameter *samples* 10000)
(defparameter *prisoners* 100)
Line 1,751:
(format t "Using a random strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-1) *samples*) 100))
(format t "Using an optimal strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-2) *samples*) 100)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,760:
=={{header|Cowgol}}==
 
<langsyntaxhighlight lang=cowgol>include "cowgol.coh";
include "argv.coh";
 
Line 1,911:
 
RunAndPrint("Stupid", Stupid);
RunAndPrint("Optimal", Optimal);</langsyntaxhighlight>
{{out}}
<pre>Stupid strategy: 0 out of 2000 - 0%
Line 1,919:
Based on the Ruby implementation
 
<langsyntaxhighlight lang=crystal>prisoners = (1..100).to_a
N = 100_000
generate_rooms = ->{ (1..100).to_a.shuffle }
Line 1,940:
end
end
puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)</langsyntaxhighlight>
{{out}}
<pre>Random strategy : 0.0000 %
Line 1,947:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=d>import std.array;
import std.random;
import std.range;
Line 1,999:
writefln("Optimal play success rate: %11.8f%%", exec(N, &playOptimal));
writefln(" Random play success rate: %11.8f%%", exec(N, &playRandom));
}</langsyntaxhighlight>
{{out}}
<pre># of executions: 1000000
Line 2,007:
See [[#Pascal]].
=={{header|EasyLang}}==
<langsyntaxhighlight lang=EasyLang>for i range 100
drawer[] &= i
sampler[] &= i
Line 2,068:
pardoned += found
.
print "optimal: " & 100.0 * pardoned / n & "%"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,077:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=elixir>defmodule HundredPrisoners do
def optimal_room(_, _, _, []), do: []
def optimal_room(prisoner, current_room, rooms, [_ | tail]) do
Line 2,109:
end)
 
IO.puts "Optimal strategy: #{optimal_strategy} / #{n |> Range.size}"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,117:
 
=={{header|F sharp|F#}}==
<langsyntaxhighlight lang=fsharp>let rnd = System.Random()
let shuffled min max =
[|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))
Line 2,154:
printfn $"Using Random Strategy: {(outcomeOfRandom 20000):p2}"
printfn $"Using Optimum Strategy: {(outcomeOfOptimize 20000):p2}"
</syntaxhighlight>
</lang>
{{out}}
<pre>Using Random Strategy: 0.00%
Line 2,161:
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: arrays formatting fry io kernel math random sequences ;
 
: setup ( -- seq seq ) 100 <iota> dup >array randomize ;
Line 2,180:
10,000 [ rand ] simulate "Random play success: "
10,000 [ optimal ] simulate "Optimal play success: "
[ write "%.2f%%\n" printf ] 2bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 2,190:
=={{header|FOCAL}}==
 
<langsyntaxhighlight lang=FOCAL>01.10 T %5.02," RANDOM";S CU=0
01.20 F Z=1,2000;D 5;S CU=CU+SU
01.30 T CU/20,!,"OPTIMAL";S CU=0
Line 2,227:
06.20 I (X-101)6.3,6.4
06.30 D 4;S X=X+1;I (SU),6.4,6.2
06.40 R</langsyntaxhighlight>
 
{{out}}
Line 2,246:
Run the two strategies (random and follow the card number) 10,000 times each, and show number or successes.
 
<langsyntaxhighlight lang=forth>INCLUDE ran4.seq
 
100 CONSTANT #drawers
Line 2,333:
 
0 trie . CR \ random strategy
1 trie . CR \ follow the card number strategy</langsyntaxhighlight>
 
output:
Line 2,343:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang=FORTRAN>SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)
! Takes an input array and shuffles the elements by swapping them
! in pairs in turn 10 times
Line 2,496:
CALL RUN_RANDOM(N_ROUNDS)
CALL RUN_OPTIMAL(N_ROUNDS)
END PROGRAM HUNDRED_PRISONERS</langsyntaxhighlight>
 
output:
Line 2,507:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>#include once "knuthshuf.bas" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC
 
function gus( i as long, strat as boolean ) as long
Line 2,548:
trials( c_success, c_fail, true )
 
print using "For prisoners using the strategy we had ####### successes and ####### failures.";c_success;c_fail</langsyntaxhighlight>
 
=={{header|Gambas}}==
Implementation of the '100 Prisoners' program written in VBA. Tested in Gambas 3.15.2
<langsyntaxhighlight lang=gambas>' Gambas module file
 
Public DrawerArray As Long[]
Line 2,712:
Return FoundOwnNumber
End</langsyntaxhighlight>
 
{{out}}
Line 2,734:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 2,800:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,819:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang=groovy>import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.IntStream
Line 2,879:
System.out.printf("Random play success rate: %f%%\n", exec(n, p, Prisoners.&playRandom))
}
}</langsyntaxhighlight>
{{out}}
<pre># of executions: 100000
Line 2,886:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import System.Random
import Control.Monad.State
 
Line 2,961:
allM func [] = return True
allM func (x:xs) = func x >>= \res -> if res then allM func xs else return False
</syntaxhighlight>
</lang>
{{out}}
<pre>Chance of winning when choosing randomly: 0.0
Line 2,967:
 
=={{header|J}}==
<syntaxhighlight lang=J>
<lang J>
NB. game is solvable by optimal strategy when the length (#) of the
NB. longest (>./) cycle (C.) is at most 50.
Line 2,983:
'o r'=. y %~ 100 * +/ ((rand,opt)@?~)"0 y # 100
('strategy';'win rate'),('random';(":o),'%'),:'optimal';(":r),'%'
)</langsyntaxhighlight>
{{out}}
<pre> simulate 10000000
Line 2,996:
 
=={{header|Janet}}==
<langsyntaxhighlight lang=janet>
(math/seedrandom (os/cryptorand 8))
 
Line 3,051:
(printf "Optimal play wins: %.1f%%" (* (/ optimal-success sims) 100))
(printf "Random play wins: %.1f%%" (* (/ random-success sims) 100)))
</syntaxhighlight>
</lang>
 
Output:
Line 3,062:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=java>import java.util.Collections;
import java.util.List;
import java.util.Objects;
Line 3,126:
System.out.printf("Random play success rate: %f%%\n", exec(n, p, Main::playRandom));
}
}</langsyntaxhighlight>
{{out}}
<pre># of executions: 100000
Line 3,135:
{{trans|C#}}
{{Works with|Node.js}}
<langsyntaxhighlight lang=javascript>
const _ = require('lodash');
 
Line 3,244:
console.log("Optimal Play Success Rate: " + execOptimal());
console.log("Random Play Success Rate: " + execRandom());
</syntaxhighlight>
</lang>
 
===School example===
Line 3,250:
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}
 
<langsyntaxhighlight lang=JavaScript>"use strict";
 
// Simulate several thousand instances of the game:
Line 3,354:
function computeProbability(results, gamesCount) {
return Math.round(results.filter(x => x == true).length * 10000 / gamesCount) / 100;
}</langsyntaxhighlight>
 
Output:
Line 3,366:
 
jq does not have a built-in PRNG and so the jq program used here presupposes an external source of entropy such as /dev/urandom. The output shown below was obtained by invoking jq as follows:
<langsyntaxhighlight lang=sh>export LC_ALL=C
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq</langsyntaxhighlight>
 
In the following jq program:
Line 3,374:
 
'''Preliminaries'''
<langsyntaxhighlight lang=jq>def count(s): reduce s as $x (0; .+1);
 
# Output: a PRN in range(0;$n) where $n is .
Line 3,396:
| .a[$j] = $t)
| .a
end;</langsyntaxhighlight>
 
'''np Prisoners'''
<langsyntaxhighlight lang=jq># Output: if all the prisoners succeed, emit true, otherwise false
def optimalStrategy($drawers; np):
# Does prisoner $p succeed?
Line 3,453:
;
 
task(100000)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,467:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang=julia>using Random, Formatting
 
function randomplay(n, numprisoners=100)
Line 3,508:
println("Random play wins: ", format(randomplay(N), precision=8), "% of simulations.")
println("Optimal play wins: ", format(optimalplay(N), precision=8), "% of simulations.")
</langsyntaxhighlight>{{out}}
<pre>
Simulation count: 100000
Line 3,516:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>val playOptimal: () -> Boolean = {
val secrets = (0..99).toMutableList()
var ret = true
Line 3,569:
println("Optimal play success rate: ${exec(N, playOptimal)}%")
println("Random play success rate: ${exec(N, playRandom)}%")
}</langsyntaxhighlight>
 
{{out}}
Line 3,580:
=={{header|Lua}}==
{{trans|lang}}
<langsyntaxhighlight lang=lua>function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
Line 3,662:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre># of executions: 1000000
Line 3,671:
 
Don"t bother to simulate the random method: each prisoner has a probability p to win with:
<langsyntaxhighlight lang=maple>p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));
# p=1/2</langsyntaxhighlight>
 
Since all prisoners' attempts are independent, the probability that they all win is:
 
<langsyntaxhighlight lang=maple>p^100;
evalf(%);
 
# 1/1267650600228229401496703205376
# 7.888609052e-31</langsyntaxhighlight>
 
Even with billions of simulations, chances are we won't find even one successful escape.
Line 3,688:
Here is a simulation based on this, assuming that the permutation of numbers in boxes is random:
 
<langsyntaxhighlight lang=maple>a:=[seq(max(GroupTheory[PermCycleType](Perm(Statistics[Shuffle]([$1..100])))),i=1..100000)]:
nops(select(n->n<=50,a))/nops(a);
evalf(%);
# 31239/100000
# 0.3123900000</langsyntaxhighlight>
 
The probability of success is now better than 30%, which is far better than the random approach.
Line 3,698:
It can be [https://en.wikipedia.org/wiki/Random_permutation_statistics#One_hundred_prisoners proved] that the probability with the second strategy is in fact:
 
<langsyntaxhighlight lang=maple>1-(harmonic(100)-harmonic(50));
evalf(%);
 
# 21740752665556690246055199895649405434183/69720375229712477164533808935312303556800
# 0.3118278207</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>ClearAll[PlayRandom, PlayOptimal]
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
Line 3,755:
];
PlayRandom[1000]
PlayOptimal[10000]</langsyntaxhighlight>
 
{{out}}
Line 3,762:
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang=MATLAB>function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)
%numP is the number of prisoners
%numG is the number of guesses
Line 3,819:
disp(['Probability of success with random strategy: ' num2str(randSuccess*100) '%']);
disp(['Probability of success with ideal strategy: ' num2str(idealSuccess*100) '%']);
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,828:
=={{header|MiniScript}}==
{{trans|Python}}
<langsyntaxhighlight lang=MiniScript>playRandom = function(n)
// using 0-99 instead of 1-100
pardoned = 0
Line 3,876:
 
print "Random: " + playRandom(10000) + "%"
print "Optimal: " + playOptimal(10000) + "%"</langsyntaxhighlight>
{{out}}
<pre>Random: 0%
Line 3,883:
=={{header|Nim}}==
Imperative style.
<langsyntaxhighlight lang=Nim>import random, sequtils, strutils
 
type
Line 3,931:
randomize()
echo $massDrawings(prisonersWillBeReleasedSmart)
echo $massDrawings(prisonersWillBeReleasedRandom)</langsyntaxhighlight>
{{out}}
<pre>Succs: 312225 Fails: 687775 Total: 1000000 Success Rate: 31.2225%.
Line 3,939:
{{works with|Free Pascal}}
searching the longest cycle length as stated on talk page and increment an counter for that cycle length.
<langsyntaxhighlight lang=pascal>program Prisoners100;
 
const
Line 4,097:
OneCompareRun(20);
OneCompareRun(100);
end.</langsyntaxhighlight>{{out}}
<pre>
Checking 20 prisoners
Line 4,150:
Randomly 0.00% get pardoned out of 100000 checking max 0</pre>
=== Alternative for optimized ===
<langsyntaxhighlight lang=pascal>program Prisoners100;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
Line 4,287:
OneCompareRun(100);
OneCompareRun(1000);
end.</langsyntaxhighlight>
{{out}}
<pre "style height=35ex">
Line 4,332:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang=perl>use strict;
use warnings;
use feature 'say';
Line 4,382:
say " Simulation count: $trials\n" .
(sprintf " Random strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'random' ) .
(sprintf "Optimal strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'optimal');</langsyntaxhighlight>
{{out}}
<pre> Simulation count: 10000
Line 4,395:
Built so you could easily build and test your own strategies.
 
<langsyntaxhighlight lang=picolisp>(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )
 
Line 4,438:
(inc 'Successes) ) )
(prinl "We have a " (/ (* 100 Successes) N) "% success rate with " N " trials.")
(prinl "This is using the " (str> Strategy) " strategy.") ) )</langsyntaxhighlight>
 
Then run
<langsyntaxhighlight lang=picolisp>(test-strategy-n-times '+Random 10000)
(test-strategy-n-times '+Optimal 10000)</langsyntaxhighlight>
 
{{out}}
Line 4,451:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">play<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">prisoners<span style="color: #0000FF;">,</span> <span style="color: #000000;">iterations<span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">optimal<span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">drawers</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
Line 4,480:
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"Prisoners:%d, random:%g, optimal:%g\n"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">prisoners<span style="color: #0000FF;">,<span style="color: #000000;">random<span style="color: #0000FF;">,<span style="color: #000000;">optimal<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,490:
=={{header|Phixmonti}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
by Galileo, 05/2022 #/
 
Line 4,536:
( "Optimal: " 100 10000 true play
" Random: " 100 10000 false play
" Prisoners: " prisoners ) lprint</langsyntaxhighlight>
{{out}}
<pre>Please, be patient ...
Line 4,543:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang=plm>100H:
/* PARAMETERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
Line 4,697:
CALL RUN$AND$PRINT(.'OPTIMAL$', OPTIMAL, N$SIMS);
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>RANDOM STRATEGY: 0 OUT OF 2000 - 0%
Line 4,703:
 
=={{header|Pointless}}==
<langsyntaxhighlight lang=pointless>optimalSeq(drawers, n) =
iterate(ind => drawers[ind - 1], n)
|> takeUntil(ind => drawers[ind - 1] == n)
Line 4,747:
randomCount, numTrials, randomCount / numTrials,
])
|> println</langsyntaxhighlight>
 
{{out}}
Line 4,755:
=={{header|PowerShell}}==
{{trans|Chris}}
<langsyntaxhighlight lang=PowerShell>
### Clear Screen from old Output
Clear-Host
Line 4,877:
 
Main
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,886:
 
=={{header|Processing}}==
<langsyntaxhighlight lang=Processing>IntList drawers = new IntList();
int trials = 100000;
int succes_count;
Line 4,941:
println(" Succeses: " + succes_count);
print(" Succes rate: " + 100.0 * succes_count / trials + "%");
}</langsyntaxhighlight>
 
{{out}}
Line 4,955:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>#PRISONERS=100
#DRAWERS =100
#LOOPS = 50
Line 4,991:
PrintN(~"\tFIN =q.") : inp$=Input()
w1=0 : w2=0
If inp$<>"q" : Goto Start : EndIf</langsyntaxhighlight>
{{out}}
<pre>TRIALS: 10000 RANDOM= 0.00% STATEGY= 30.83% FIN =q.
Line 5,001:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang=python>import random
 
def play_random(n):
Line 5,049:
print(" Simulation count:", n)
print(f" Random play wins: {play_random(n):4.1f}% of simulations")
print(f"Optimal play wins: {play_optimal(n):4.1f}% of simulations")</langsyntaxhighlight>
 
{{out}}
Line 5,058:
 
Or, an alternative procedural approach:
<langsyntaxhighlight lang=python># http://rosettacode.org/wiki/100_prisoners
 
import random
Line 5,136:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>With 10 drawers (100k runs)
Line 5,160:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang=python>'''100 Prisoners'''
 
from random import randint, sample
Line 5,336:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>10000 tests of optimal vs random drawer-sampling with 10 boxes:
Line 5,354:
 
=={{header|R}}==
<langsyntaxhighlight lang=R>t = 100000 #number of trials
success.r = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the random method
success.o = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the optimal method
Line 5,385:
 
cat("Random method resulted in a success rate of ",100*mean(success.r==100),
"%.\nOptimal method resulted in a success rate of ",100*mean(success.o==100),"%.",sep="")</langsyntaxhighlight>
{{Out}}
<pre>Random method resulted in a success rate of 0%.
Line 5,391:
 
=={{header|QB64}}==
<langsyntaxhighlight lang=QB64>
Const Found = -1, Searching = 0, Status = 1, Tries = 2
Const Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2
Line 5,472:
End Sub
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
<langsyntaxhighlight lang=Quackery> [ this ] is 100prisoners.qky
 
[ dup size 2 / split ] is halve ( [ --> [ [ )
Line 5,520:
say "100 smart prisoners were pardoned "
0 10000 times [ 100 prisoners smart + ] echo
say " times out of 10000 simulations." cr ] is simulate ( --> )</langsyntaxhighlight>
 
'''Output:'''
<langsyntaxhighlight lang=Quackery>/O> [ $ '100prisoners.qky' loadfile ] now!
... simulate
...
Line 5,529:
100 smart prisoners were pardoned 3158 times out of 10000 simulations.
 
Stack empty.</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>#lang racket
(require srfi/1)
 
Line 5,562:
(module+ main
(print-sample-percentage "random" (evaluate-strategy 100-prisoners-problem strategy-1))
(print-sample-percentage "optimal" (evaluate-strategy 100-prisoners-problem strategy-2)))</langsyntaxhighlight>
 
{{out}}
Line 5,576:
Also test with 10 prisoners to verify that the logic is correct for random selection. Random selection should succeed with 10 prisoners at a probability of (1/2)**10, so in 100_000 simulations, should get pardons about .0977 percent of the time.
 
<langsyntaxhighlight lang=perl6>unit sub MAIN (:$prisoners = 100, :$simulations = 10000);
my @prisoners = ^$prisoners;
my $half = floor +@prisoners / 2;
Line 5,620:
say "Testing $simulations simulations with $prisoners prisoners.";
printf " Random play wins: %.3f%% of simulations\n", random $simulations;
printf "Optimal play wins: %.3f%% of simulations\n", optimal $simulations;</langsyntaxhighlight>
{{out}}
'''With defaults'''
Line 5,633:
</pre>
=={{header|Red}}==
<langsyntaxhighlight lang=Rebol>
Red []
 
Line 5,676:
print ["runs" k_runs newline "Percent saved opt.strategy:" saved * 100.0 / k_runs ]
print ["Percent saved random strategy:" saved_rand * 100.0 / k_runs ]
</syntaxhighlight>
</lang>
{{out}}<pre>
runs 100000
Line 5,684:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>/*REXX program to simulate the problem of 100 prisoners: random, and optimal strategy.*/
parse arg men trials seed . /*obtain optional arguments from the CL*/
if men=='' | men=="," then men= 100 /*number of prisoners for this run.*/
Line 5,727:
end /* [↑] indicate success for prisoner. */
?= @.? /*choose next drawer from current card.*/
end /*try*/; return 1 /*choose half of the number of drawers.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 5,744:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang=ruby>prisoners = [*1..100]
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
Line 5,766:
end
puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)
</syntaxhighlight>
</lang>
{{out}}
<pre>Random strategy : 0.0000 %
Line 5,777:
 
Cargo.toml
<langsyntaxhighlight lang=toml>[dependencies]
rand = '0.7.2'</langsyntaxhighlight>
 
src/main.rs
<langsyntaxhighlight lang=rust>extern crate rand;
 
use rand::prelude::*;
Line 5,822:
println!("{} / {} ({:.02}%) successes in random", random_successes, trials, random_successes as f64 * 100.0 / trials as f64);
 
}</langsyntaxhighlight>
 
{{out}}
Line 5,829:
 
=={{header|Sather}}==
<langsyntaxhighlight lang=sather>class MAIN is
shuffle (a: ARRAY{INT}) is
ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);
Line 5,887:
try("optimal", 100000, 10, 10, 5, bind(try_optimal(_, _, _)));
end;
end;</langsyntaxhighlight>
{{out}}
<pre>100 prisoners, 100 drawers, 50 tries:
Line 5,899:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>import scala.util.Random
import scala.util.control.Breaks._
 
Line 5,958:
printf("Random play success rate: %f%%\n", exec(n, p, playRandom))
}
}</langsyntaxhighlight>
{{out}}
<pre># of executions: 100,000
Line 5,966:
=={{header|Swift}}==
 
<langsyntaxhighlight lang=swift>import Foundation
 
struct PrisonersGame {
Line 6,046:
}
 
dispatchMain()</langsyntaxhighlight>
 
{{out}}
Line 6,056:
=={{header|Tcl}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang=tcl>set Samples 10000
set Prisoners 100
set MaxGuesses 50
Line 6,162:
}
 
compareStrategies $Strategies</langsyntaxhighlight>
 
{{Out}}
Line 6,174:
{{works with|Transact-SQL|SQL Server 2017}}
 
<langsyntaxhighlight lang=Transact-SQL>USE rosettacode;
GO
 
Line 6,350:
DROP TABLE dbo.drawers;
DROP TABLE dbo.numbers;
GO</langsyntaxhighlight>
 
Output:
Line 6,360:
=={{header|VBA}}/{{header|Visual Basic}}==
 
<langsyntaxhighlight lang=vb>Sub HundredPrisoners()
 
NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100))
Line 6,504:
Next Counter
End Sub</langsyntaxhighlight>
 
{{out}}
Line 6,514:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang=vbnet>Module Module1
 
Function PlayOptimal() As Boolean
Line 6,578:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre># of executions: 1000000
Line 6,585:
 
=={{header|VBScript}}==
<syntaxhighlight lang=VB>
<lang VB>
option explicit
const npris=100
Line 6,647:
next
trystrat=false
end function </langsyntaxhighlight>
Output:
<pre>
Line 6,656:
=={{header|Vlang}}==
{{trans|Wren}}
<langsyntaxhighlight lang=vlang>import rand
import rand.seed
// Uses 0-based numbering rather than 1-based numbering throughout.
Line 6,718:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 6,739:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "random" for Random
import "/fmt" for Fmt
 
Line 6,795:
Fmt.print("Results from $,d trials with $d prisoners:\n", trials, np)
for (strategy in ["random", "optimal"]) doTrials.call(trials, np, strategy)
}</langsyntaxhighlight>
 
{{out}}
Line 6,814:
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>int Drawer(100);
 
proc KShuffle; \Randomly rearrange the cards in the drawers
Line 6,871:
Text(0, "Optimal strategy success rate: ");
Strategy(2);
]</langsyntaxhighlight>
 
{{out}}
Line 6,881:
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight lang=Yabasic>// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
// by Galileo, 05/2022
 
Line 6,913:
optimal = play(prisoners, iterations, true)
print "Prisoners: ", prisoners, ", random: ", random, ", optimal: ", optimal
next</langsyntaxhighlight>
{{out}}
<pre>Simulation count: 10000
Line 6,921:
 
=={{header|zkl}}==
<langsyntaxhighlight lang=zkl>const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000;
fcn oneHundredJDI{ // just do it strategy
cupboard,picks := [0..SLOTS-1].walk().shuffle(), cupboard.copy();
Line 6,936:
}
True // all found their number
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>s:=N.pump(Ref(0).incN,oneHundredJDI).value.toFloat()/N*100;
println("Just do it strategy (%,d simulatations): %.2f%%".fmt(N,s));
 
s:=N.pump(Ref(0).incN,oneHundredO).value.toFloat()/N*100;
println("Optimal strategy (%,d simulatations): %.2f%%".fmt(N,s));</langsyntaxhighlight>
{{out}}
<pre>
Line 6,948:
</pre>
And a sanity check (from the Raku entry):
<langsyntaxhighlight lang=zkl>const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits