100 prisoners: Difference between revisions

m
Automated syntax highlighting fixup
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup)
Line 34:
{{trans|Python}}
 
<syntaxhighlight lang="11l">F play_random(n)
V pardoned = 0
V in_drawer = Array(0.<100)
Line 89:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program prisonniex64.s */
Line 354:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">
package Prisoners is
 
Line 379:
end Prisoners;
</syntaxhighlight>
<syntaxhighlight lang=Ada"ada">
pragma Ada_2012;
with Ada.Numerics.Discrete_Random;
Line 509:
end Prisoners;
</syntaxhighlight>
<syntaxhighlight lang=Ada"ada">
with Prisoners; use Prisoners;
with Ada.Text_IO; use Ada.Text_IO;
Line 536:
{{works with|GNU APL|1.8}}
 
<syntaxhighlight lang=Ada"ada">
∇ R ← random Nnc; N; n; c
(N n c) ← Nnc
Line 588:
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
 
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:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program prisonniers.s */
Line 881:
</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">NumOfTrials := 20000
randomFailTotal := 0, strategyFailTotal := 0
prisoners := [], drawers := [], Cards := []
Line 944:
=={{header|BASIC256}}==
{{works with|BASIC256|2.0.0.11}}
<syntaxhighlight lang=BASIC256"basic256">
O = 50
N = 2*O
Line 1,034:
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
manifest $(
Line 1,112:
 
=={{header|C}}==
<syntaxhighlight lang=C"c">
#include<stdbool.h>
#include<stdlib.h>
Line 1,270:
=={{header|C sharp|C#}}==
{{trans|D}}
<syntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,344:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <cstdlib> // for rand
#include <algorithm> // for random_shuffle
#include <iostream> // for output
Line 1,425:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">(ns clojure-sandbox.prisoners)
 
(defn random-drawers []
Line 1,498:
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
Line 1,618:
The key here is avoiding the use of GOTO as a means of exiting a loop early.
 
<syntaxhighlight lang="gwbasic">
10 rem 100 prisoners
20 rem set arrays
Line 1,701:
{{trans|Racket}}
 
<syntaxhighlight lang="lisp">
(defparameter *samples* 10000)
(defparameter *prisoners* 100)
Line 1,760:
=={{header|Cowgol}}==
 
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
 
Line 1,919:
Based on the Ruby implementation
 
<syntaxhighlight lang="crystal">prisoners = (1..100).to_a
N = 100_000
generate_rooms = ->{ (1..100).to_a.shuffle }
Line 1,947:
=={{header|D}}==
{{trans|Kotlin}}
<syntaxhighlight lang="d">import std.array;
import std.random;
import std.range;
Line 2,007:
See [[#Pascal]].
=={{header|EasyLang}}==
<syntaxhighlight lang=EasyLang"easylang">for i range 100
drawer[] &= i
sampler[] &= i
Line 2,077:
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="elixir">defmodule HundredPrisoners do
def optimal_room(_, _, _, []), do: []
def optimal_room(prisoner, current_room, rooms, [_ | tail]) do
Line 2,117:
 
=={{header|F sharp|F#}}==
<syntaxhighlight lang="fsharp">let rnd = System.Random()
let shuffled min max =
[|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))
Line 2,161:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: arrays formatting fry io kernel math random sequences ;
 
: setup ( -- seq seq ) 100 <iota> dup >array randomize ;
Line 2,190:
=={{header|FOCAL}}==
 
<syntaxhighlight lang=FOCAL"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,246:
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
 
100 CONSTANT #drawers
Line 2,343:
 
=={{header|Fortran}}==
<syntaxhighlight lang=FORTRAN"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,507:
 
=={{header|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
Line 2,552:
=={{header|Gambas}}==
Implementation of the '100 Prisoners' program written in VBA. Tested in Gambas 3.15.2
<syntaxhighlight lang="gambas">' Gambas module file
 
Public DrawerArray As Long[]
Line 2,734:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 2,819:
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.IntStream
Line 2,886:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import System.Random
import Control.Monad.State
 
Line 2,967:
 
=={{header|J}}==
<syntaxhighlight lang=J"j">
NB. game is solvable by optimal strategy when the length (#) of the
NB. longest (>./) cycle (C.) is at most 50.
Line 2,996:
 
=={{header|Janet}}==
<syntaxhighlight lang="janet">
(math/seedrandom (os/cryptorand 8))
 
Line 3,062:
=={{header|Java}}==
{{trans|Kotlin}}
<syntaxhighlight lang="java">import java.util.Collections;
import java.util.List;
import java.util.Objects;
Line 3,135:
{{trans|C#}}
{{Works with|Node.js}}
<syntaxhighlight lang="javascript">
const _ = require('lodash');
 
Line 3,250:
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}
 
<syntaxhighlight lang=JavaScript"javascript">"use strict";
 
// Simulate several thousand instances of the game:
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:
<syntaxhighlight lang="sh">export LC_ALL=C
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq</syntaxhighlight>
 
Line 3,374:
 
'''Preliminaries'''
<syntaxhighlight lang="jq">def count(s): reduce s as $x (0; .+1);
 
# Output: a PRN in range(0;$n) where $n is .
Line 3,399:
 
'''np Prisoners'''
<syntaxhighlight lang="jq"># Output: if all the prisoners succeed, emit true, otherwise false
def optimalStrategy($drawers; np):
# Does prisoner $p succeed?
Line 3,467:
=={{header|Julia}}==
{{trans|Python}}
<syntaxhighlight lang="julia">using Random, Formatting
 
function randomplay(n, numprisoners=100)
Line 3,516:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">val playOptimal: () -> Boolean = {
val secrets = (0..99).toMutableList()
var ret = true
Line 3,580:
=={{header|Lua}}==
{{trans|lang}}
<syntaxhighlight lang="lua">function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
Line 3,671:
 
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));
# p=1/2</syntaxhighlight>
 
Since all prisoners' attempts are independent, the probability that they all win is:
 
<syntaxhighlight lang="maple">p^100;
evalf(%);
 
Line 3,688:
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)]:
nops(select(n->n<=50,a))/nops(a);
evalf(%);
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:
 
<syntaxhighlight lang="maple">1-(harmonic(100)-harmonic(50));
evalf(%);
 
Line 3,705:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">ClearAll[PlayRandom, PlayOptimal]
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
Line 3,762:
 
=={{header|MATLAB}}==
<syntaxhighlight lang=MATLAB"matlab">function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)
%numP is the number of prisoners
%numG is the number of guesses
Line 3,828:
=={{header|MiniScript}}==
{{trans|Python}}
<syntaxhighlight lang=MiniScript"miniscript">playRandom = function(n)
// using 0-99 instead of 1-100
pardoned = 0
Line 3,883:
=={{header|Nim}}==
Imperative style.
<syntaxhighlight lang=Nim"nim">import random, sequtils, strutils
 
type
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.
<syntaxhighlight lang="pascal">program Prisoners100;
 
const
Line 4,150:
Randomly 0.00% get pardoned out of 100000 checking max 0</pre>
=== Alternative for optimized ===
<syntaxhighlight lang="pascal">program Prisoners100;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
Line 4,332:
=={{header|Perl}}==
{{trans|Raku}}
<syntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 4,395:
Built so you could easily build and test your own strategies.
 
<syntaxhighlight lang="picolisp">(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )
 
Line 4,441:
 
Then run
<syntaxhighlight lang="picolisp">(test-strategy-n-times '+Random 10000)
(test-strategy-n-times '+Optimal 10000)</syntaxhighlight>
 
Line 4,451:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"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,490:
=={{header|Phixmonti}}==
{{trans|Yabasic}}
<syntaxhighlight lang=Phixmonti"phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
by Galileo, 05/2022 #/
 
Line 4,543:
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
/* PARAMETERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
Line 4,703:
 
=={{header|Pointless}}==
<syntaxhighlight lang="pointless">optimalSeq(drawers, n) =
iterate(ind => drawers[ind - 1], n)
|> takeUntil(ind => drawers[ind - 1] == n)
Line 4,755:
=={{header|PowerShell}}==
{{trans|Chris}}
<syntaxhighlight lang=PowerShell"powershell">
### Clear Screen from old Output
Clear-Host
Line 4,886:
 
=={{header|Processing}}==
<syntaxhighlight lang=Processing"processing">IntList drawers = new IntList();
int trials = 100000;
int succes_count;
Line 4,955:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">#PRISONERS=100
#DRAWERS =100
#LOOPS = 50
Line 5,001:
=={{header|Python}}==
===Procedural===
<syntaxhighlight lang="python">import random
 
def play_random(n):
Line 5,058:
 
Or, an alternative procedural approach:
<syntaxhighlight lang="python"># http://rosettacode.org/wiki/100_prisoners
 
import random
Line 5,160:
 
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''100 Prisoners'''
 
from random import randint, sample
Line 5,354:
 
=={{header|R}}==
<syntaxhighlight lang=R"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,391:
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
Const Found = -1, Searching = 0, Status = 1, Tries = 2
Const Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2
Line 5,475:
 
=={{header|Quackery}}==
<syntaxhighlight lang=Quackery"quackery"> [ this ] is 100prisoners.qky
 
[ dup size 2 / split ] is halve ( [ --> [ [ )
Line 5,523:
 
'''Output:'''
<syntaxhighlight lang=Quackery"quackery">/O> [ $ '100prisoners.qky' loadfile ] now!
... simulate
...
Line 5,532:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(require srfi/1)
 
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.
 
<syntaxhighlight lang=perl6"raku" line>unit sub MAIN (:$prisoners = 100, :$simulations = 10000);
my @prisoners = ^$prisoners;
my $half = floor +@prisoners / 2;
Line 5,633:
</pre>
=={{header|Red}}==
<syntaxhighlight lang=Rebol"rebol">
Red []
 
Line 5,684:
 
=={{header|REXX}}==
<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*/
if men=='' | men=="," then men= 100 /*number of prisoners for this run.*/
Line 5,744:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">prisoners = [*1..100]
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
Line 5,777:
 
Cargo.toml
<syntaxhighlight lang="toml">[dependencies]
rand = '0.7.2'</syntaxhighlight>
 
src/main.rs
<syntaxhighlight lang="rust">extern crate rand;
 
use rand::prelude::*;
Line 5,829:
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
shuffle (a: ARRAY{INT}) is
ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);
Line 5,899:
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="scala">import scala.util.Random
import scala.util.control.Breaks._
 
Line 5,966:
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
struct PrisonersGame {
Line 6,056:
=={{header|Tcl}}==
{{trans|Common Lisp}}
<syntaxhighlight lang="tcl">set Samples 10000
set Prisoners 100
set MaxGuesses 50
Line 6,174:
{{works with|Transact-SQL|SQL Server 2017}}
 
<syntaxhighlight lang=Transact"transact-SQLsql">USE rosettacode;
GO
 
Line 6,360:
=={{header|VBA}}/{{header|Visual Basic}}==
 
<syntaxhighlight lang="vb">Sub HundredPrisoners()
 
NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100))
Line 6,514:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Function PlayOptimal() As Boolean
Line 6,585:
 
=={{header|VBScript}}==
<syntaxhighlight lang=VB"vb">
option explicit
const npris=100
Line 6,656:
=={{header|Vlang}}==
{{trans|Wren}}
<syntaxhighlight lang="vlang">import rand
import rand.seed
// Uses 0-based numbering rather than 1-based numbering throughout.
Line 6,739:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 6,814:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">int Drawer(100);
 
proc KShuffle; \Randomly rearrange the cards in the drawers
Line 6,881:
=={{header|Yabasic}}==
{{trans|Phix}}
<syntaxhighlight lang=Yabasic"yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
// by Galileo, 05/2022
 
Line 6,921:
 
=={{header|zkl}}==
<syntaxhighlight 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,937:
True // all found their number
}</syntaxhighlight>
<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));
 
Line 6,948:
</pre>
And a sanity check (from the Raku entry):
<syntaxhighlight lang="zkl">const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;</syntaxhighlight>
{{out}}
<pre>
10,333

edits