100 prisoners: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup)
Line 34: Line 34:
{{trans|Python}}
{{trans|Python}}


<syntaxhighlight lang=11l>F play_random(n)
<syntaxhighlight lang="11l">F play_random(n)
V pardoned = 0
V pardoned = 0
V in_drawer = Array(0.<100)
V in_drawer = Array(0.<100)
Line 89: Line 89:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64 Assembly>
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program prisonniex64.s */
/* program prisonniex64.s */
Line 354: Line 354:


=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=Ada>
<syntaxhighlight lang="ada">
package Prisoners is
package Prisoners is


Line 379: Line 379:
end Prisoners;
end Prisoners;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang=Ada>
<syntaxhighlight lang="ada">
pragma Ada_2012;
pragma Ada_2012;
with Ada.Numerics.Discrete_Random;
with Ada.Numerics.Discrete_Random;
Line 509: Line 509:
end Prisoners;
end Prisoners;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang=Ada>
<syntaxhighlight lang="ada">
with Prisoners; use Prisoners;
with Prisoners; use Prisoners;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
Line 536: Line 536:
{{works with|GNU APL|1.8}}
{{works with|GNU APL|1.8}}


<syntaxhighlight lang=Ada>
<syntaxhighlight lang="ada">
∇ R ← random Nnc; N; n; c
∇ R ← random Nnc; N; n; c
(N n c) ← Nnc
(N n c) ← Nnc
Line 588: Line 588:
Actual test of 4000 trials for each method were run on the KEGSMAC emulator with MHz set to No Limit.
Actual test of 4000 trials for each method were run on the KEGSMAC emulator with MHz set to No Limit.


<syntaxhighlight lang=gwbasic>0 GOTO 9
<syntaxhighlight 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
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 640: Line 640:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program prisonniers.s */
/* program prisonniers.s */
Line 881: Line 881:
</pre>
</pre>
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey>NumOfTrials := 20000
<syntaxhighlight lang="autohotkey">NumOfTrials := 20000
randomFailTotal := 0, strategyFailTotal := 0
randomFailTotal := 0, strategyFailTotal := 0
prisoners := [], drawers := [], Cards := []
prisoners := [], drawers := [], Cards := []
Line 944: Line 944:
=={{header|BASIC256}}==
=={{header|BASIC256}}==
{{works with|BASIC256|2.0.0.11}}
{{works with|BASIC256|2.0.0.11}}
<syntaxhighlight lang=BASIC256>
<syntaxhighlight lang="basic256">
O = 50
O = 50
N = 2*O
N = 2*O
Line 1,034: Line 1,034:


=={{header|BCPL}}==
=={{header|BCPL}}==
<syntaxhighlight lang=bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


manifest $(
manifest $(
Line 1,112: Line 1,112:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=C>
<syntaxhighlight lang="c">
#include<stdbool.h>
#include<stdbool.h>
#include<stdlib.h>
#include<stdlib.h>
Line 1,270: Line 1,270:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|D}}
{{trans|D}}
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 1,344: Line 1,344:


=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang=cpp>#include <cstdlib> // for rand
<syntaxhighlight lang="cpp">#include <cstdlib> // for rand
#include <algorithm> // for random_shuffle
#include <algorithm> // for random_shuffle
#include <iostream> // for output
#include <iostream> // for output
Line 1,425: Line 1,425:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure>(ns clojure-sandbox.prisoners)
<syntaxhighlight lang="clojure">(ns clojure-sandbox.prisoners)


(defn random-drawers []
(defn random-drawers []
Line 1,498: Line 1,498:


=={{header|CLU}}==
=={{header|CLU}}==
<syntaxhighlight lang=clu>% This program needs to be merged with PCLU's "misc" library
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
% to use the random number generator.
%
%
Line 1,618: Line 1,618:
The key here is avoiding the use of GOTO as a means of exiting a loop early.
The key here is avoiding the use of GOTO as a means of exiting a loop early.


<syntaxhighlight lang=gwbasic>
<syntaxhighlight lang="gwbasic">
10 rem 100 prisoners
10 rem 100 prisoners
20 rem set arrays
20 rem set arrays
Line 1,701: Line 1,701:
{{trans|Racket}}
{{trans|Racket}}


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(defparameter *samples* 10000)
(defparameter *samples* 10000)
(defparameter *prisoners* 100)
(defparameter *prisoners* 100)
Line 1,760: Line 1,760:
=={{header|Cowgol}}==
=={{header|Cowgol}}==


<syntaxhighlight lang=cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
include "argv.coh";


Line 1,919: Line 1,919:
Based on the Ruby implementation
Based on the Ruby implementation


<syntaxhighlight lang=crystal>prisoners = (1..100).to_a
<syntaxhighlight lang="crystal">prisoners = (1..100).to_a
N = 100_000
N = 100_000
generate_rooms = ->{ (1..100).to_a.shuffle }
generate_rooms = ->{ (1..100).to_a.shuffle }
Line 1,947: Line 1,947:
=={{header|D}}==
=={{header|D}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<syntaxhighlight lang=d>import std.array;
<syntaxhighlight lang="d">import std.array;
import std.random;
import std.random;
import std.range;
import std.range;
Line 2,007: Line 2,007:
See [[#Pascal]].
See [[#Pascal]].
=={{header|EasyLang}}==
=={{header|EasyLang}}==
<syntaxhighlight lang=EasyLang>for i range 100
<syntaxhighlight lang="easylang">for i range 100
drawer[] &= i
drawer[] &= i
sampler[] &= i
sampler[] &= i
Line 2,077: Line 2,077:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<syntaxhighlight lang=elixir>defmodule HundredPrisoners do
<syntaxhighlight lang="elixir">defmodule HundredPrisoners do
def optimal_room(_, _, _, []), do: []
def optimal_room(_, _, _, []), do: []
def optimal_room(prisoner, current_room, rooms, [_ | tail]) do
def optimal_room(prisoner, current_room, rooms, [_ | tail]) do
Line 2,117: Line 2,117:


=={{header|F sharp|F#}}==
=={{header|F sharp|F#}}==
<syntaxhighlight lang=fsharp>let rnd = System.Random()
<syntaxhighlight lang="fsharp">let rnd = System.Random()
let shuffled min max =
let shuffled min max =
[|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))
[|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))
Line 2,161: Line 2,161:


=={{header|Factor}}==
=={{header|Factor}}==
<syntaxhighlight lang=factor>USING: arrays formatting fry io kernel math random sequences ;
<syntaxhighlight lang="factor">USING: arrays formatting fry io kernel math random sequences ;


: setup ( -- seq seq ) 100 <iota> dup >array randomize ;
: setup ( -- seq seq ) 100 <iota> dup >array randomize ;
Line 2,190: Line 2,190:
=={{header|FOCAL}}==
=={{header|FOCAL}}==


<syntaxhighlight lang=FOCAL>01.10 T %5.02," RANDOM";S CU=0
<syntaxhighlight lang="focal">01.10 T %5.02," RANDOM";S CU=0
01.20 F Z=1,2000;D 5;S CU=CU+SU
01.20 F Z=1,2000;D 5;S CU=CU+SU
01.30 T CU/20,!,"OPTIMAL";S CU=0
01.30 T CU/20,!,"OPTIMAL";S CU=0
Line 2,246: Line 2,246:
Run the two strategies (random and follow the card number) 10,000 times each, and show number or successes.
Run the two strategies (random and follow the card number) 10,000 times each, and show number or successes.


<syntaxhighlight lang=forth>INCLUDE ran4.seq
<syntaxhighlight lang="forth">INCLUDE ran4.seq


100 CONSTANT #drawers
100 CONSTANT #drawers
Line 2,343: Line 2,343:


=={{header|Fortran}}==
=={{header|Fortran}}==
<syntaxhighlight lang=FORTRAN>SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)
<syntaxhighlight lang="fortran">SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)
! Takes an input array and shuffles the elements by swapping them
! Takes an input array and shuffles the elements by swapping them
! in pairs in turn 10 times
! in pairs in turn 10 times
Line 2,507: Line 2,507:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>#include once "knuthshuf.bas" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC
<syntaxhighlight 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
function gus( i as long, strat as boolean ) as long
Line 2,552: Line 2,552:
=={{header|Gambas}}==
=={{header|Gambas}}==
Implementation of the '100 Prisoners' program written in VBA. Tested in Gambas 3.15.2
Implementation of the '100 Prisoners' program written in VBA. Tested in Gambas 3.15.2
<syntaxhighlight lang=gambas>' Gambas module file
<syntaxhighlight lang="gambas">' Gambas module file


Public DrawerArray As Long[]
Public DrawerArray As Long[]
Line 2,734: Line 2,734:


=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,819: Line 2,819:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=groovy>import java.util.function.Function
<syntaxhighlight lang="groovy">import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.Collectors
import java.util.stream.IntStream
import java.util.stream.IntStream
Line 2,886: Line 2,886:


=={{header|Haskell}}==
=={{header|Haskell}}==
<syntaxhighlight lang=haskell>import System.Random
<syntaxhighlight lang="haskell">import System.Random
import Control.Monad.State
import Control.Monad.State


Line 2,967: Line 2,967:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang=J>
<syntaxhighlight lang="j">
NB. game is solvable by optimal strategy when the length (#) of the
NB. game is solvable by optimal strategy when the length (#) of the
NB. longest (>./) cycle (C.) is at most 50.
NB. longest (>./) cycle (C.) is at most 50.
Line 2,996: Line 2,996:


=={{header|Janet}}==
=={{header|Janet}}==
<syntaxhighlight lang=janet>
<syntaxhighlight lang="janet">
(math/seedrandom (os/cryptorand 8))
(math/seedrandom (os/cryptorand 8))


Line 3,062: Line 3,062:
=={{header|Java}}==
=={{header|Java}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<syntaxhighlight lang=java>import java.util.Collections;
<syntaxhighlight lang="java">import java.util.Collections;
import java.util.List;
import java.util.List;
import java.util.Objects;
import java.util.Objects;
Line 3,135: Line 3,135:
{{trans|C#}}
{{trans|C#}}
{{Works with|Node.js}}
{{Works with|Node.js}}
<syntaxhighlight lang=javascript>
<syntaxhighlight lang="javascript">
const _ = require('lodash');
const _ = require('lodash');


Line 3,250: Line 3,250:
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}


<syntaxhighlight lang=JavaScript>"use strict";
<syntaxhighlight lang="javascript">"use strict";


// Simulate several thousand instances of the game:
// Simulate several thousand instances of the game:
Line 3,366: 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:
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:
<syntaxhighlight lang=sh>export LC_ALL=C
<syntaxhighlight lang="sh">export LC_ALL=C
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq</syntaxhighlight>
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq</syntaxhighlight>


Line 3,374: Line 3,374:


'''Preliminaries'''
'''Preliminaries'''
<syntaxhighlight lang=jq>def count(s): reduce s as $x (0; .+1);
<syntaxhighlight lang="jq">def count(s): reduce s as $x (0; .+1);


# Output: a PRN in range(0;$n) where $n is .
# Output: a PRN in range(0;$n) where $n is .
Line 3,399: Line 3,399:


'''np Prisoners'''
'''np Prisoners'''
<syntaxhighlight lang=jq># Output: if all the prisoners succeed, emit true, otherwise false
<syntaxhighlight lang="jq"># Output: if all the prisoners succeed, emit true, otherwise false
def optimalStrategy($drawers; np):
def optimalStrategy($drawers; np):
# Does prisoner $p succeed?
# Does prisoner $p succeed?
Line 3,467: Line 3,467:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=julia>using Random, Formatting
<syntaxhighlight lang="julia">using Random, Formatting


function randomplay(n, numprisoners=100)
function randomplay(n, numprisoners=100)
Line 3,516: Line 3,516:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang=scala>val playOptimal: () -> Boolean = {
<syntaxhighlight lang="scala">val playOptimal: () -> Boolean = {
val secrets = (0..99).toMutableList()
val secrets = (0..99).toMutableList()
var ret = true
var ret = true
Line 3,580: Line 3,580:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|lang}}
{{trans|lang}}
<syntaxhighlight lang=lua>function shuffle(tbl)
<syntaxhighlight lang="lua">function shuffle(tbl)
for i = #tbl, 2, -1 do
for i = #tbl, 2, -1 do
local j = math.random(i)
local j = math.random(i)
Line 3,671: Line 3,671:


Don"t bother to simulate the random method: each prisoner has a probability p to win with:
Don"t bother to simulate the random method: each prisoner has a probability p to win with:
<syntaxhighlight lang=maple>p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));
<syntaxhighlight lang="maple">p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));
# p=1/2</syntaxhighlight>
# p=1/2</syntaxhighlight>


Since all prisoners' attempts are independent, the probability that they all win is:
Since all prisoners' attempts are independent, the probability that they all win is:


<syntaxhighlight lang=maple>p^100;
<syntaxhighlight lang="maple">p^100;
evalf(%);
evalf(%);


Line 3,688: Line 3,688:
Here is a simulation based on this, assuming that the permutation of numbers in boxes is random:
Here is a simulation based on this, assuming that the permutation of numbers in boxes is random:


<syntaxhighlight lang=maple>a:=[seq(max(GroupTheory[PermCycleType](Perm(Statistics[Shuffle]([$1..100])))),i=1..100000)]:
<syntaxhighlight lang="maple">a:=[seq(max(GroupTheory[PermCycleType](Perm(Statistics[Shuffle]([$1..100])))),i=1..100000)]:
nops(select(n->n<=50,a))/nops(a);
nops(select(n->n<=50,a))/nops(a);
evalf(%);
evalf(%);
Line 3,698: 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:
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:


<syntaxhighlight lang=maple>1-(harmonic(100)-harmonic(50));
<syntaxhighlight lang="maple">1-(harmonic(100)-harmonic(50));
evalf(%);
evalf(%);


Line 3,705: Line 3,705:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>ClearAll[PlayRandom, PlayOptimal]
<syntaxhighlight lang="mathematica">ClearAll[PlayRandom, PlayOptimal]
PlayRandom[n_] :=
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
Module[{pardoned = 0, sampler, indrawer, found, reveal},
Line 3,762: Line 3,762:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<syntaxhighlight lang=MATLAB>function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)
<syntaxhighlight lang="matlab">function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)
%numP is the number of prisoners
%numP is the number of prisoners
%numG is the number of guesses
%numG is the number of guesses
Line 3,828: Line 3,828:
=={{header|MiniScript}}==
=={{header|MiniScript}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=MiniScript>playRandom = function(n)
<syntaxhighlight lang="miniscript">playRandom = function(n)
// using 0-99 instead of 1-100
// using 0-99 instead of 1-100
pardoned = 0
pardoned = 0
Line 3,883: Line 3,883:
=={{header|Nim}}==
=={{header|Nim}}==
Imperative style.
Imperative style.
<syntaxhighlight lang=Nim>import random, sequtils, strutils
<syntaxhighlight lang="nim">import random, sequtils, strutils


type
type
Line 3,939: Line 3,939:
{{works with|Free Pascal}}
{{works with|Free Pascal}}
searching the longest cycle length as stated on talk page and increment an counter for that cycle length.
searching the longest cycle length as stated on talk page and increment an counter for that cycle length.
<syntaxhighlight lang=pascal>program Prisoners100;
<syntaxhighlight lang="pascal">program Prisoners100;


const
const
Line 4,150: Line 4,150:
Randomly 0.00% get pardoned out of 100000 checking max 0</pre>
Randomly 0.00% get pardoned out of 100000 checking max 0</pre>
=== Alternative for optimized ===
=== Alternative for optimized ===
<syntaxhighlight lang=pascal>program Prisoners100;
<syntaxhighlight lang="pascal">program Prisoners100;
{$IFDEF FPC}
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
Line 4,332: Line 4,332:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 4,395: Line 4,395:
Built so you could easily build and test your own strategies.
Built so you could easily build and test your own strategies.


<syntaxhighlight lang=picolisp>(de shuffle (Lst)
<syntaxhighlight lang="picolisp">(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )
(by '(NIL (rand)) sort Lst) )


Line 4,441: Line 4,441:


Then run
Then run
<syntaxhighlight lang=picolisp>(test-strategy-n-times '+Random 10000)
<syntaxhighlight lang="picolisp">(test-strategy-n-times '+Random 10000)
(test-strategy-n-times '+Optimal 10000)</syntaxhighlight>
(test-strategy-n-times '+Optimal 10000)</syntaxhighlight>


Line 4,451: Line 4,451:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight 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: #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>
<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,490: Line 4,490:
=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
{{trans|Yabasic}}
{{trans|Yabasic}}
<syntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
by Galileo, 05/2022 #/
by Galileo, 05/2022 #/


Line 4,543: Line 4,543:


=={{header|PL/M}}==
=={{header|PL/M}}==
<syntaxhighlight lang=plm>100H:
<syntaxhighlight lang="plm">100H:
/* PARAMETERS */
/* PARAMETERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
Line 4,703: Line 4,703:


=={{header|Pointless}}==
=={{header|Pointless}}==
<syntaxhighlight lang=pointless>optimalSeq(drawers, n) =
<syntaxhighlight lang="pointless">optimalSeq(drawers, n) =
iterate(ind => drawers[ind - 1], n)
iterate(ind => drawers[ind - 1], n)
|> takeUntil(ind => drawers[ind - 1] == n)
|> takeUntil(ind => drawers[ind - 1] == n)
Line 4,755: Line 4,755:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{trans|Chris}}
{{trans|Chris}}
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
### Clear Screen from old Output
### Clear Screen from old Output
Clear-Host
Clear-Host
Line 4,886: Line 4,886:


=={{header|Processing}}==
=={{header|Processing}}==
<syntaxhighlight lang=Processing>IntList drawers = new IntList();
<syntaxhighlight lang="processing">IntList drawers = new IntList();
int trials = 100000;
int trials = 100000;
int succes_count;
int succes_count;
Line 4,955: Line 4,955:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>#PRISONERS=100
<syntaxhighlight lang="purebasic">#PRISONERS=100
#DRAWERS =100
#DRAWERS =100
#LOOPS = 50
#LOOPS = 50
Line 5,001: Line 5,001:
=={{header|Python}}==
=={{header|Python}}==
===Procedural===
===Procedural===
<syntaxhighlight lang=python>import random
<syntaxhighlight lang="python">import random


def play_random(n):
def play_random(n):
Line 5,058: Line 5,058:


Or, an alternative procedural approach:
Or, an alternative procedural approach:
<syntaxhighlight lang=python># http://rosettacode.org/wiki/100_prisoners
<syntaxhighlight lang="python"># http://rosettacode.org/wiki/100_prisoners


import random
import random
Line 5,160: Line 5,160:


{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<syntaxhighlight lang=python>'''100 Prisoners'''
<syntaxhighlight lang="python">'''100 Prisoners'''


from random import randint, sample
from random import randint, sample
Line 5,354: Line 5,354:


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang=R>t = 100000 #number of trials
<syntaxhighlight 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.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
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,391: Line 5,391:


=={{header|QB64}}==
=={{header|QB64}}==
<syntaxhighlight lang=QB64>
<syntaxhighlight lang="qb64">
Const Found = -1, Searching = 0, Status = 1, Tries = 2
Const Found = -1, Searching = 0, Status = 1, Tries = 2
Const Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2
Const Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2
Line 5,475: Line 5,475:


=={{header|Quackery}}==
=={{header|Quackery}}==
<syntaxhighlight lang=Quackery> [ this ] is 100prisoners.qky
<syntaxhighlight lang="quackery"> [ this ] is 100prisoners.qky


[ dup size 2 / split ] is halve ( [ --> [ [ )
[ dup size 2 / split ] is halve ( [ --> [ [ )
Line 5,523: Line 5,523:


'''Output:'''
'''Output:'''
<syntaxhighlight lang=Quackery>/O> [ $ '100prisoners.qky' loadfile ] now!
<syntaxhighlight lang="quackery">/O> [ $ '100prisoners.qky' loadfile ] now!
... simulate
... simulate
...
...
Line 5,532: Line 5,532:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(require srfi/1)
(require srfi/1)


Line 5,576: 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.
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.


<syntaxhighlight lang=perl6>unit sub MAIN (:$prisoners = 100, :$simulations = 10000);
<syntaxhighlight lang="raku" line>unit sub MAIN (:$prisoners = 100, :$simulations = 10000);
my @prisoners = ^$prisoners;
my @prisoners = ^$prisoners;
my $half = floor +@prisoners / 2;
my $half = floor +@prisoners / 2;
Line 5,633: Line 5,633:
</pre>
</pre>
=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang=Rebol>
<syntaxhighlight lang="rebol">
Red []
Red []


Line 5,684: Line 5,684:


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>/*REXX program to simulate the problem of 100 prisoners: random, and optimal strategy.*/
<syntaxhighlight 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*/
parse arg men trials seed . /*obtain optional arguments from the CL*/
if men=='' | men=="," then men= 100 /*number of prisoners for this run.*/
if men=='' | men=="," then men= 100 /*number of prisoners for this run.*/
Line 5,744: Line 5,744:


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang=ruby>prisoners = [*1..100]
<syntaxhighlight lang="ruby">prisoners = [*1..100]
N = 10_000
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
generate_rooms = ->{ [nil]+[*1..100].shuffle }
Line 5,777: Line 5,777:


Cargo.toml
Cargo.toml
<syntaxhighlight lang=toml>[dependencies]
<syntaxhighlight lang="toml">[dependencies]
rand = '0.7.2'</syntaxhighlight>
rand = '0.7.2'</syntaxhighlight>


src/main.rs
src/main.rs
<syntaxhighlight lang=rust>extern crate rand;
<syntaxhighlight lang="rust">extern crate rand;


use rand::prelude::*;
use rand::prelude::*;
Line 5,829: Line 5,829:


=={{header|Sather}}==
=={{header|Sather}}==
<syntaxhighlight lang=sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
shuffle (a: ARRAY{INT}) is
shuffle (a: ARRAY{INT}) is
ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);
ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);
Line 5,899: Line 5,899:
=={{header|Scala}}==
=={{header|Scala}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=scala>import scala.util.Random
<syntaxhighlight lang="scala">import scala.util.Random
import scala.util.control.Breaks._
import scala.util.control.Breaks._


Line 5,966: Line 5,966:
=={{header|Swift}}==
=={{header|Swift}}==


<syntaxhighlight lang=swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


struct PrisonersGame {
struct PrisonersGame {
Line 6,056: Line 6,056:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}
<syntaxhighlight lang=tcl>set Samples 10000
<syntaxhighlight lang="tcl">set Samples 10000
set Prisoners 100
set Prisoners 100
set MaxGuesses 50
set MaxGuesses 50
Line 6,174: Line 6,174:
{{works with|Transact-SQL|SQL Server 2017}}
{{works with|Transact-SQL|SQL Server 2017}}


<syntaxhighlight lang=Transact-SQL>USE rosettacode;
<syntaxhighlight lang="transact-sql">USE rosettacode;
GO
GO


Line 6,360: Line 6,360:
=={{header|VBA}}/{{header|Visual Basic}}==
=={{header|VBA}}/{{header|Visual Basic}}==


<syntaxhighlight lang=vb>Sub HundredPrisoners()
<syntaxhighlight lang="vb">Sub HundredPrisoners()


NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100))
NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100))
Line 6,514: Line 6,514:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function PlayOptimal() As Boolean
Function PlayOptimal() As Boolean
Line 6,585: Line 6,585:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang=VB>
<syntaxhighlight lang="vb">
option explicit
option explicit
const npris=100
const npris=100
Line 6,656: Line 6,656:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Wren}}
{{trans|Wren}}
<syntaxhighlight lang=vlang>import rand
<syntaxhighlight lang="vlang">import rand
import rand.seed
import rand.seed
// Uses 0-based numbering rather than 1-based numbering throughout.
// Uses 0-based numbering rather than 1-based numbering throughout.
Line 6,739: Line 6,739:
{{trans|Go}}
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 6,814: Line 6,814:


=={{header|XPL0}}==
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0>int Drawer(100);
<syntaxhighlight lang="xpl0">int Drawer(100);


proc KShuffle; \Randomly rearrange the cards in the drawers
proc KShuffle; \Randomly rearrange the cards in the drawers
Line 6,881: Line 6,881:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|Phix}}
{{trans|Phix}}
<syntaxhighlight lang=Yabasic>// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
// by Galileo, 05/2022
// by Galileo, 05/2022


Line 6,921: Line 6,921:


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000;
<syntaxhighlight lang="zkl">const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000;
fcn oneHundredJDI{ // just do it strategy
fcn oneHundredJDI{ // just do it strategy
cupboard,picks := [0..SLOTS-1].walk().shuffle(), cupboard.copy();
cupboard,picks := [0..SLOTS-1].walk().shuffle(), cupboard.copy();
Line 6,937: Line 6,937:
True // all found their number
True // all found their number
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>s:=N.pump(Ref(0).incN,oneHundredJDI).value.toFloat()/N*100;
<syntaxhighlight lang="zkl">s:=N.pump(Ref(0).incN,oneHundredJDI).value.toFloat()/N*100;
println("Just do it strategy (%,d simulatations): %.2f%%".fmt(N,s));
println("Just do it strategy (%,d simulatations): %.2f%%".fmt(N,s));


Line 6,948: Line 6,948:
</pre>
</pre>
And a sanity check (from the Raku entry):
And a sanity check (from the Raku entry):
<syntaxhighlight lang=zkl>const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;</syntaxhighlight>
<syntaxhighlight lang="zkl">const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>