100 prisoners: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 34:
{{trans|Python}}
<
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)))</
{{out}}
Line 89:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* 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>
<pre>
Random strategie : 0 sur 1000
Line 354:
=={{header|Ada}}==
<
package Prisoners is
Line 378:
end Prisoners;
</syntaxhighlight>
<
pragma Ada_2012;
with Ada.Numerics.Discrete_Random;
Line 508:
end Prisoners;
</syntaxhighlight>
<
with Prisoners; use Prisoners;
with Ada.Text_IO; use Ada.Text_IO;
Line 527:
Put ("%");
end Main;
</syntaxhighlight>
{{out}}
<pre>
Line 536:
{{works with|GNU APL|1.8}}
<
∇ R ← random Nnc; N; n; c
(N n c) ← Nnc
Line 562:
5000 timesSimPrisoners 100 50
</syntaxhighlight>
=={{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.
<
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>
{{out}}
Line 640:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program prisonniers.s */
Line 875:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
Random strategie : 0 sur 1000
Line 881:
</pre>
=={{header|AutoHotkey}}==
<
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"</
Outputs:<pre>Number Of Trials = 20000
Optimal Strategy: 33.275000 % success rate
Line 944:
=={{header|BASIC256}}==
{{works with|BASIC256|2.0.0.11}}
<
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>
{{out}}
<pre>
Line 1,034:
=={{header|BCPL}}==
<
manifest $(
Line 1,105:
run(d, " Random", randoms, size, simul, tries)
run(d, "Optimal", optimal, size, simul, tries)
$)</
{{out}}
<pre>
Line 1,112:
=={{header|C}}==
<syntaxhighlight lang=C>
#include<stdbool.h>
#include<stdlib.h>
Line 1,252:
}
</syntaxhighlight>
<pre>
$ gcc 100prisoners.c && ./a.out 100 50 10000
Line 1,270:
=={{header|C sharp|C#}}==
{{trans|D}}
<
using System.Linq;
Line 1,337:
}
}
}</
{{out}}
<pre># of executions: 1000000
Line 1,344:
=={{header|C++}}==
<
#include <algorithm> // for random_shuffle
#include <iostream> // for output
Line 1,419:
system("PAUSE"); // for Windows
return 0;
}</
{{out}}
<pre>Random strategy: 0 %
Line 1,425:
=={{header|Clojure}}==
<
(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))))))</
{{out}}
Line 1,498:
=={{header|CLU}}==
<
% 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</
{{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.
<
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>
{{out}}
Line 1,701:
{{trans|Racket}}
<
(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>
{{out}}
Line 1,760:
=={{header|Cowgol}}==
<
include "argv.coh";
Line 1,911:
RunAndPrint("Stupid", Stupid);
RunAndPrint("Optimal", Optimal);</
{{out}}
<pre>Stupid strategy: 0 out of 2000 - 0%
Line 1,919:
Based on the Ruby implementation
<
N = 100_000
generate_rooms = ->{ (1..100).to_a.shuffle }
Line 1,940:
end
end
puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)</
{{out}}
<pre>Random strategy : 0.0000 %
Line 1,947:
=={{header|D}}==
{{trans|Kotlin}}
<
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));
}</
{{out}}
<pre># of executions: 1000000
Line 2,007:
See [[#Pascal]].
=={{header|EasyLang}}==
<
drawer[] &= i
sampler[] &= i
Line 2,068:
pardoned += found
.
print "optimal: " & 100.0 * pardoned / n & "%"</
{{out}}
<pre>
Line 2,077:
=={{header|Elixir}}==
{{trans|Ruby}}
<
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}"</
{{out}}
<pre>
Line 2,117:
=={{header|F sharp|F#}}==
<
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>
{{out}}
<pre>Using Random Strategy: 0.00%
Line 2,161:
=={{header|Factor}}==
<
: 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@</
{{out}}
<pre>
Line 2,190:
=={{header|FOCAL}}==
<
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</
{{out}}
Line 2,246:
Run the two strategies (random and follow the card number) 10,000 times each, and show number or successes.
<
100 CONSTANT #drawers
Line 2,333:
0 trie . CR \ random strategy
1 trie . CR \ follow the card number strategy</
output:
Line 2,343:
=={{header|Fortran}}==
<
! 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</
output:
Line 2,507:
=={{header|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</
=={{header|Gambas}}==
Implementation of the '100 Prisoners' program written in VBA. Tested in Gambas 3.15.2
<
Public DrawerArray As Long[]
Line 2,712:
Return FoundOwnNumber
End</
{{out}}
Line 2,734:
=={{header|Go}}==
<
import (
Line 2,800:
}
}
}</
{{out}}
Line 2,819:
=={{header|Groovy}}==
{{trans|Java}}
<
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))
}
}</
{{out}}
<pre># of executions: 100000
Line 2,886:
=={{header|Haskell}}==
<
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>
{{out}}
<pre>Chance of winning when choosing randomly: 0.0
Line 2,967:
=={{header|J}}==
<syntaxhighlight 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),'%'
)</
{{out}}
<pre> simulate 10000000
Line 2,996:
=={{header|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>
Output:
Line 3,062:
=={{header|Java}}==
{{trans|Kotlin}}
<
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));
}
}</
{{out}}
<pre># of executions: 100000
Line 3,135:
{{trans|C#}}
{{Works with|Node.js}}
<
const _ = require('lodash');
Line 3,244:
console.log("Optimal Play Success Rate: " + execOptimal());
console.log("Random Play Success Rate: " + execRandom());
</syntaxhighlight>
===School example===
Line 3,250:
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}
<
// 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;
}</
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:
<
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq</
In the following jq program:
Line 3,374:
'''Preliminaries'''
<
# Output: a PRN in range(0;$n) where $n is .
Line 3,396:
| .a[$j] = $t)
| .a
end;</
'''np Prisoners'''
<
def optimalStrategy($drawers; np):
# Does prisoner $p succeed?
Line 3,453:
;
task(100000)</
{{out}}
<pre>
Line 3,467:
=={{header|Julia}}==
{{trans|Python}}
<
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.")
</
<pre>
Simulation count: 100000
Line 3,516:
=={{header|Kotlin}}==
<
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)}%")
}</
{{out}}
Line 3,580:
=={{header|Lua}}==
{{trans|lang}}
<
for i = #tbl, 2, -1 do
local j = math.random(i)
Line 3,662:
end
main()</
{{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:
<
# p=1/2</
Since all prisoners' attempts are independent, the probability that they all win is:
<
evalf(%);
# 1/1267650600228229401496703205376
# 7.888609052e-31</
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:
<
nops(select(n->n<=50,a))/nops(a);
evalf(%);
# 31239/100000
# 0.3123900000</
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:
<
evalf(%);
# 21740752665556690246055199895649405434183/69720375229712477164533808935312303556800
# 0.3118278207</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
Line 3,755:
];
PlayRandom[1000]
PlayOptimal[10000]</
{{out}}
Line 3,762:
=={{header|MATLAB}}==
<
%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</
{{out}}
<pre>
Line 3,828:
=={{header|MiniScript}}==
{{trans|Python}}
<
// using 0-99 instead of 1-100
pardoned = 0
Line 3,876:
print "Random: " + playRandom(10000) + "%"
print "Optimal: " + playOptimal(10000) + "%"</
{{out}}
<pre>Random: 0%
Line 3,883:
=={{header|Nim}}==
Imperative style.
<
type
Line 3,931:
randomize()
echo $massDrawings(prisonersWillBeReleasedSmart)
echo $massDrawings(prisonersWillBeReleasedRandom)</
{{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.
<
const
Line 4,097:
OneCompareRun(20);
OneCompareRun(100);
end.</
<pre>
Checking 20 prisoners
Line 4,150:
Randomly 0.00% get pardoned out of 100000 checking max 0</pre>
=== Alternative for optimized ===
<
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
Line 4,287:
OneCompareRun(100);
OneCompareRun(1000);
end.</
{{out}}
<pre "style height=35ex">
Line 4,332:
=={{header|Perl}}==
{{trans|Raku}}
<
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');</
{{out}}
<pre> Simulation count: 10000
Line 4,395:
Built so you could easily build and test your own strategies.
<
(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.") ) )</
Then run
<
(test-strategy-n-times '+Optimal 10000)</
{{out}}
Line 4,451:
=={{header|Phix}}==
<!--<
<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
<!--</
{{out}}
<pre>
Line 4,490:
=={{header|Phixmonti}}==
{{trans|Yabasic}}
<
by Galileo, 05/2022 #/
Line 4,536:
( "Optimal: " 100 10000 true play
" Random: " 100 10000 false play
" Prisoners: " prisoners ) lprint</
{{out}}
<pre>Please, be patient ...
Line 4,543:
=={{header|PL/M}}==
<
/* PARAMETERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
Line 4,697:
CALL RUN$AND$PRINT(.'OPTIMAL$', OPTIMAL, N$SIMS);
CALL EXIT;
EOF</
{{out}}
<pre>RANDOM STRATEGY: 0 OUT OF 2000 - 0%
Line 4,703:
=={{header|Pointless}}==
<
iterate(ind => drawers[ind - 1], n)
|> takeUntil(ind => drawers[ind - 1] == n)
Line 4,747:
randomCount, numTrials, randomCount / numTrials,
])
|> println</
{{out}}
Line 4,755:
=={{header|PowerShell}}==
{{trans|Chris}}
<
### Clear Screen from old Output
Clear-Host
Line 4,877:
Main
</syntaxhighlight>
{{out}}
Line 4,886:
=={{header|Processing}}==
<
int trials = 100000;
int succes_count;
Line 4,941:
println(" Succeses: " + succes_count);
print(" Succes rate: " + 100.0 * succes_count / trials + "%");
}</
{{out}}
Line 4,955:
=={{header|PureBasic}}==
<
#DRAWERS =100
#LOOPS = 50
Line 4,991:
PrintN(~"\tFIN =q.") : inp$=Input()
w1=0 : w2=0
If inp$<>"q" : Goto Start : EndIf</
{{out}}
<pre>TRIALS: 10000 RANDOM= 0.00% STATEGY= 30.83% FIN =q.
Line 5,001:
=={{header|Python}}==
===Procedural===
<
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")</
{{out}}
Line 5,058:
Or, an alternative procedural approach:
<
import random
Line 5,136:
if __name__ == '__main__':
main()</
{{Out}}
<pre>With 10 drawers (100k runs)
Line 5,160:
{{Works with|Python|3.7}}
<
from random import randint, sample
Line 5,336:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>10000 tests of optimal vs random drawer-sampling with 10 boxes:
Line 5,354:
=={{header|R}}==
<
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="")</
{{Out}}
<pre>Random method resulted in a success rate of 0%.
Line 5,391:
=={{header|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>
=={{header|Quackery}}==
<
[ 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 ( --> )</
'''Output:'''
<
... simulate
...
Line 5,529:
100 smart prisoners were pardoned 3158 times out of 10000 simulations.
Stack empty.</
=={{header|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)))</
{{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.
<
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;</
{{out}}
'''With defaults'''
Line 5,633:
</pre>
=={{header|Red}}==
<
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>
{{out}}<pre>
runs 100000
Line 5,684:
=={{header|REXX}}==
<
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.*/</
{{out|output|text= when using the default inputs:}}
<pre>
Line 5,744:
=={{header|Ruby}}==
<
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
Line 5,766:
end
puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)
</syntaxhighlight>
{{out}}
<pre>Random strategy : 0.0000 %
Line 5,777:
Cargo.toml
<
rand = '0.7.2'</
src/main.rs
<
use rand::prelude::*;
Line 5,822:
println!("{} / {} ({:.02}%) successes in random", random_successes, trials, random_successes as f64 * 100.0 / trials as f64);
}</
{{out}}
Line 5,829:
=={{header|Sather}}==
<
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;</
{{out}}
<pre>100 prisoners, 100 drawers, 50 tries:
Line 5,899:
=={{header|Scala}}==
{{trans|Java}}
<
import scala.util.control.Breaks._
Line 5,958:
printf("Random play success rate: %f%%\n", exec(n, p, playRandom))
}
}</
{{out}}
<pre># of executions: 100,000
Line 5,966:
=={{header|Swift}}==
<
struct PrisonersGame {
Line 6,046:
}
dispatchMain()</
{{out}}
Line 6,056:
=={{header|Tcl}}==
{{trans|Common Lisp}}
<
set Prisoners 100
set MaxGuesses 50
Line 6,162:
}
compareStrategies $Strategies</
{{Out}}
Line 6,174:
{{works with|Transact-SQL|SQL Server 2017}}
<
GO
Line 6,350:
DROP TABLE dbo.drawers;
DROP TABLE dbo.numbers;
GO</
Output:
Line 6,360:
=={{header|VBA}}/{{header|Visual Basic}}==
<
NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100))
Line 6,504:
Next Counter
End Sub</
{{out}}
Line 6,514:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function PlayOptimal() As Boolean
Line 6,578:
End Sub
End Module</
{{out}}
<pre># of executions: 1000000
Line 6,585:
=={{header|VBScript}}==
<syntaxhighlight lang=VB>
option explicit
const npris=100
Line 6,647:
next
trystrat=false
end function </
Output:
<pre>
Line 6,656:
=={{header|Vlang}}==
{{trans|Wren}}
<
import rand.seed
// Uses 0-based numbering rather than 1-based numbering throughout.
Line 6,718:
}
}
}</
{{out}}
Line 6,739:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
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)
}</
{{out}}
Line 6,814:
=={{header|XPL0}}==
<
proc KShuffle; \Randomly rearrange the cards in the drawers
Line 6,871:
Text(0, "Optimal strategy success rate: ");
Strategy(2);
]</
{{out}}
Line 6,881:
=={{header|Yabasic}}==
{{trans|Phix}}
<
// by Galileo, 05/2022
Line 6,913:
optimal = play(prisoners, iterations, true)
print "Prisoners: ", prisoners, ", random: ", random, ", optimal: ", optimal
next</
{{out}}
<pre>Simulation count: 10000
Line 6,921:
=={{header|zkl}}==
<
fcn oneHundredJDI{ // just do it strategy
cupboard,picks := [0..SLOTS-1].walk().shuffle(), cupboard.copy();
Line 6,936:
}
True // all found their number
}</
<
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));</
{{out}}
<pre>
Line 6,948:
</pre>
And a sanity check (from the Raku entry):
<
{{out}}
<pre>
|