Sleeping Beauty problem: Difference between revisions

Added Easylang
(Add Red)
(Added Easylang)
(14 intermediate revisions by 10 users not shown)
Line 31:
 
 
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F sleeping_beauty_experiment(repetitions)
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
V gotheadsonwaking = 0
V wakenings = 0
L 0 .< repetitions
V coin_result = random:choice([‘heads’, ‘tails’])
 
// On Monday, we check if we got heads.
wakenings++
I coin_result == ‘heads’
gotheadsonwaking++
 
// If tails, we do this again, but of course we will not add as if it was heads..
I coin_result == ‘tails’
wakenings++
I coin_result == ‘heads’
gotheadsonwaking++ // never done
 
print(‘Wakenings over ’repetitions‘ experiments: ’wakenings)
 
R Float(gotheadsonwaking) / wakenings
 
V CREDENCE = sleeping_beauty_experiment(1'000'000)
print(‘Results of experiment: Sleeping Beauty should estimate a credence of: ’CREDENCE)</syntaxhighlight>
 
{{out}}
<pre>
Wakenings over 1000000 experiments: 1500892
Results of experiment: Sleeping Beauty should estimate a credence of: 0.332540916
</pre>
 
=={{header|Arturo}}==
Line 36 ⟶ 73:
{{trans|Wren}}
 
<langsyntaxhighlight lang="rebol">sleepingBeauty: function [reps][
wakings: 0
heads: 0
Line 50 ⟶ 87:
pc: sleepingBeauty 100000
print ["Percentage probability of heads on waking =" pc "%"]</langsyntaxhighlight>
 
{{out}}
Line 60 ⟶ 97:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
iteraciones = 1000000
cara = 0
Line 78 ⟶ 115:
print "Percentage probability of heads on waking = "; (cara/dormir*100); "%"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 85 ⟶ 122:
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">
Const iteraciones = 1000000
Randomize Timer
Line 99 ⟶ 136:
Print using "Percentage probability of heads on waking = ###.######%"; (cara/dormir*100)'; "%"
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 108 ⟶ 145:
==={{header|GW-BASIC}}===
In this simulation, Sleeping Beauty flips a coin of her own.
<langsyntaxhighlight lang="gwbasic">10 RANDOMIZE TIMER
20 MONDAY = 0 : TUESDAY = 1
30 HEADS = 0 : TAILS = 1
Line 134 ⟶ 171:
250 IF GUESS = HEADS THEN WHEADS = WHEADS + 1 ELSE CTAILS = CTAILS + 1
260 NEXT DAY
270 RETURN</langsyntaxhighlight>
{{out}}<pre>
Sleeping Beauty was put through this experiment 300000 times.
Line 146 ⟶ 183:
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">
<lang Yabasic>
iteraciones = 1000000
cara = 0
Line 160 ⟶ 197:
print "Percentage probability of heads on waking = ", (cara/dormir*100), "%"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 167 ⟶ 204:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
 
Line 192 ⟶ 229:
std::cout << "Sleeping Beauty should estimate a credence of: "
<< double(heads) / wakenings << '\n';
}</langsyntaxhighlight>
 
{{out}}
Line 201 ⟶ 238:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
 
Line 251 ⟶ 288:
chance: real := experiment$run(N)
stream$putl(po, f_form(chance, 1, 6))
end start_up </langsyntaxhighlight>
{{out}}
<pre>Chance of waking up with heads: 0.333758</pre>
Line 258 ⟶ 295:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">let experiments = 10000
var heads = 0
var wakenings = 0
Line 269 ⟶ 306:
}
print("Wakenings over \(experiments) experiments: \(wakenings)")
print("Sleeping Beauty should estimate a credence of: \(Float(heads) / Float(wakenings))")</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
reps = 1e6
for i to reps
coin = randint 2
wakings += 1
if coin = 1
heads += 1
else
wakings += 1
.
.
print "Chance of waking up with heads: " & heads / wakings * 100 & "%"
</syntaxhighlight>
 
=={{header|Excel}}==
Line 279 ⟶ 331:
 
{{Works with | Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">SLEEPINGB
=LAMBDA(n,
LET(
Line 296 ⟶ 348:
)
)
)</langsyntaxhighlight>
{{Out}}
 
Line 330 ⟶ 382:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Sleeping Beauty: Nigel Galloway. May 16th., 2021
let heads,woken=let n=System.Random() in {1..1000}|>Seq.fold(fun(h,w) g->match n.Next(2) with 0->(h+1,w+1) |_->(h,w+2))(0,0)
printfn "During 1000 tosses Sleeping Beauty woke %d times, %d times the toss was heads. %.0f%% of times heads had been tossed when she awoke" woken heads (100.0*float(heads)/float(woken))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 341 ⟶ 393:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: combinators.random io kernel math prettyprint ;
 
: sleeping ( n -- heads wakenings )
Line 348 ⟶ 400:
"Wakenings over 1,000,000 experiments: " write
1e6 sleeping dup . /f
"Sleeping Beauty should estimate a credence of: " write .</langsyntaxhighlight>
{{out}}
<pre>
Line 354 ⟶ 406:
Sleeping Beauty should estimate a credence of: 0.3332204540015612
</pre>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_iterations = 1000000
 
local fn SleepingBeauty
NSUInteger i
CGFloat heads = 0, sleep = 0
 
for i = 1 to _iterations
NSInteger coinToss = int( rnd(2) )
sleep++
if coinToss = 1 then heads++ else sleep++
next
 
printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep
printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100
end fn
 
randomize
 
fn SleepingBeauty
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Awakenings over 1000000 sleep cycles = 1499725
Percent probability of heads on waking = 33.3578%
</pre>
 
 
=={{header|Go}}==
{{trans|Wren}}
{{libheader|Go-rcu}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 387 ⟶ 472:
pc := sleepingBeauty(1e6)
fmt.Printf("Percentage probability of heads on waking = %f%%\n", pc)
}</langsyntaxhighlight>
 
{{out}}
Line 397 ⟶ 482:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Monoid (Sum(..))
import System.Random (randomIO)
import Control.Monad (replicateM)
Line 417 ⟶ 502:
let (Sum w, Sum h) = foldMap anExperiment tosses
let ratio = fromIntegral h / fromIntegral w
putStrLn $ "Ratio: " ++ show ratio</langsyntaxhighlight>
 
<pre>*Main> main
Ratio: 0.33339378051805013</pre>
 
=={{header|J}}==
Simulation code:
<syntaxhighlight lang="j">sb=: {{
monday=. ?2
if. -. monday do.
tuesday=. ?2
<monday,tuesday
else.
<monday
end.
}}</syntaxhighlight>
 
Results:<syntaxhighlight lang="j"> sample=: sb"0 i.1e6 NB. simulate a million mondays
#sample NB. number of experiments
1000000
#;sample NB. number of questions
1500433
+/;sample NB. number of heads
749617
+/0={.@>sample NB. how many times was sleeping beauty drugged?
500433
(+/%#);sample NB. odds of heads at time of question
0.4996
sample+&#;sample NB. total number of awakenings
2500433</syntaxhighlight>
 
It's probably worth noting here that the number of heads divided by the number of awakenings would be about 0.3 -- but Sleeping Beauty was not asked to guess whether the coin was heads on Wednesday.
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.concurrent.ThreadLocalRandom;
 
public final class SleepingBeauty {
 
public static void main(String[] aArgs) {
final int experiments = 1_000_000;
ThreadLocalRandom random = ThreadLocalRandom.current();
enum Coin { HEADS, TAILS }
int heads = 0;
int awakenings = 0;
for ( int i = 0; i < experiments; i++ ) {
Coin coin = Coin.values()[random.nextInt(0, 2)];
switch ( coin ) {
case HEADS -> { awakenings += 1; heads += 1; }
case TAILS -> awakenings += 2;
}
}
System.out.println("Awakenings over " + experiments + " experiments: " + awakenings);
String credence = String.format("%.3f", (double) heads / awakenings);
System.out.println("Sleeping Beauty should estimate a credence of: " + credence);
}
}
</syntaxhighlight>
{{ out }}
<pre>
Awakenings over 1000000 experiments: 1499522
Sleeping Beauty should estimate a credence of: 0.334
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
Line 458 ⟶ 607:
CREDENCE = sleeping_beauty_experiment(1_000_000)
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE)
</langsyntaxhighlight>{{out}}<pre>
Wakenings over 1000000 experiments: 1499534
Results of experiment: Sleeping Beauty should estimate a credence of: 0.33374768428058316
Line 464 ⟶ 613:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[SleepingBeautyExperiment]
SleepingBeautyExperiment[reps_Integer] := Module[{gotheadsonwaking, wakenings, coinresult},
gotheadsonwaking = 0;
Line 483 ⟶ 632:
]
out = N@SleepingBeautyExperiment[10^6];
Print["Results of experiment: Sleeping Beauty should estimate a credence of: ", out]</langsyntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499714
Line 489 ⟶ 638:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import random
 
const N = 1_000_000
Line 508 ⟶ 657:
 
echo "Wakenings over ", N, " experiments: ", wakenings
echo "Sleeping Beauty should estimate a credence of: ", onHeads / wakenings</langsyntaxhighlight>
 
{{out}}
Line 516 ⟶ 665:
=={{header|Pascal}}==
{{trans|Phix}}
<langsyntaxhighlight lang="pascal">
program sleepBeau;
uses
Line 538 ⟶ 687:
end;
writeln(Format(fmt,[iterations,wakings,heads/wakings*100]));
end.</langsyntaxhighlight>
{{out}}
<pre>Wakings over 1000000 repetitions = 1499741
Line 544 ⟶ 693:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 555 ⟶ 704:
 
my $trials = 1_000_000;
printf "Wakenings over $trials experiments: %d\nSleeping Beauty should estimate a credence of: %.4f\n", sleeping_beauty($trials);</langsyntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499816
Line 561 ⟶ 710:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">iterations</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Line 574 ⟶ 723:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">iterations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">heads</span><span style="color: #0000FF;">/</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<small>(You'll get the exact result less than 1% of the time!!)</small>
Line 584 ⟶ 733:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">from random import choice
 
def sleeping_beauty_experiment(repetitions):
Line 618 ⟶ 767:
CREDENCE = sleeping_beauty_experiment(1_000_000)
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE)
</langsyntaxhighlight>{{out}}<pre>
Wakenings over 1000000 experiments: 1499765
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333542254953276
Line 626 ⟶ 775:
===Functional===
 
<langsyntaxhighlight lang="python">'''Sleeping Beauty Problem'''
 
from random import choice
Line 685 ⟶ 834:
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
{{Out}}
<pre>1500188 wakenings over 1000000 experiments.
Line 694 ⟶ 843:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ say "Number of trials: "
Line 713 ⟶ 862:
10 round vulgar$ echo$ cr ] is trials ( n --> n/d )
 
1000000 trials</langsyntaxhighlight>
 
{{out}}
Line 726 ⟶ 875:
=={{header|R}}==
There's nothing complicated here. Pretty much every language that resembles C is going to use virtually the same solution.
<langsyntaxhighlight Rlang="rsplus">beautyProblem <- function(n)
{
wakeCount <- headCount <- 0
Line 736 ⟶ 885:
headCount/wakeCount
}
print(beautyProblem(10000000))</langsyntaxhighlight>
{{out}}
<pre>[1] 0.3335838</pre>
Line 742 ⟶ 891:
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>sub sleeping-beauty ($trials) {
my $gotheadsonwaking = 0;
my $wakenings = 0;
Line 756 ⟶ 905:
}
 
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);</langsyntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1500040
Line 762 ⟶ 911:
 
=={{header|Red}}==
<langsyntaxhighlight lang="rebol">Red ["Sleeping Beauty problem"]
 
experiments: 1'000'000
Line 771 ⟶ 920:
]
print ["Awakenings over" experiments "experiments:" awakenings]
print ["Probability of heads on waking:" heads / awakenings]</langsyntaxhighlight>
{{out}}
<pre>
Line 780 ⟶ 929:
=={{header|REXX}}==
When using Regina REXX, &nbsp; the seed specified &nbsp; (for '''random''') &nbsp; was &nbsp; '''46'''.
<langsyntaxhighlight lang="rexx">/*REXX pgm uses a Monte Carlo estimate for the results for the Sleeping Beauty problem. */
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/
Line 794 ⟶ 943:
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> , &nbsp; 46 </tt>}}
<pre>
Line 803 ⟶ 952:
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def sleeping_beauty_experiment(n)
coin = [:heads, :tails]
gotheadsonwaking = 0
Line 817 ⟶ 966:
puts "Results of experiment: Sleeping Beauty should estimate
a credence of: #{sleeping_beauty_experiment(1_000_000)}"
</syntaxhighlight>
</lang>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499604
Line 824 ⟶ 973:
</pre>
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">let experiments = 1000000
var heads = 0
var wakenings = 0
Line 837 ⟶ 986:
}
print("Wakenings over \(experiments) experiments: \(wakenings)")
print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")</langsyntaxhighlight>
 
{{out}}
Line 843 ⟶ 992:
Wakenings over 1000000 experiments: 1500036
Sleeping Beauty should estimate a credence of: 0.3333013341013149
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand
import rand.seed
 
fn sleeping_beauty(reps int) f64 {
mut wakings := 0
mut heads := 0
for _ in 0..reps {
coin := rand.intn(2) or {0} // heads = 0, tails = 1 say
wakings++
if coin == 0 {
heads++
} else {
wakings++
}
}
println("Wakings over $reps repetitions = $wakings")
return f64(heads) / f64(wakings) * 100
}
fn main() {
rand.seed(seed.time_seed_array(2))
pc := sleeping_beauty(1000000)
println("Percentage probability of heads on waking = $pc%")
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Wakings over 1000000 repetitions = 1500224
Percentage probability of heads on waking = 33.31342519517085%
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 869 ⟶ 1,052:
 
var pc = sleepingBeauty.call(1e6)
Fmt.print("Percentage probability of heads on waking = $f\%", pc)</langsyntaxhighlight>
 
{{out}}
Line 876 ⟶ 1,059:
Wakings over 1,000,000 repetitions = 1,500,321
Percentage probability of heads on waking = 33.304806%
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
func real SleepingBeauty(Reps);
int Reps, Wakings, Heads, Coin, I;
[Wakings:= 0; Heads:= 0;
for I:= 0 to Reps-1 do
[Coin:= Ran(2); \heads = 0, tails = 1 say
Wakings:= Wakings + 1;
if Coin = 0 then Heads:= Heads + 1
else Wakings:= Wakings + 1;
];
Print("Wakings over %d repetitions = %d\n", Reps, Wakings);
return float(Heads) / float(Wakings) * 100.;
];
 
real PC;
[PC:= SleepingBeauty(1_000_000);
Print("Percentage probability of heads on waking = %1.6f\%\n", PC);
]</syntaxhighlight>
{{out}}
<pre>
Wakings over 1000000 repetitions = 1500013
Percentage probability of heads on waking = 33.332178%
</pre>
1,980

edits