Skip to content

Instantly share code, notes, and snippets.

@msouth
Created June 9, 2016 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msouth/efdd87c34067ff8d0c4a9e27f4b19c50 to your computer and use it in GitHub Desktop.
Save msouth/efdd87c34067ff8d0c4a9e27f4b19c50 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
my $flips = shift @ARGV // 1000;
print "I'm going to flip a coin [$flips] times...\n";
my @thresholds = (5, 10);
my $max;
my @results;
push @results, rand for 1..$flips;
my $t_run;
my $h_run;
my %count;
my %runs;
my $first_flip = shift @results;
my $last_flip = $first_flip > .5 ? 'h' : 't';
if ($last_flip eq 'h') {
$h_run = 1;
}
else {
$t_run = 1;
}
foreach my $flip (@results) {
my $th = 't';
$th = 'h' if $flip > .5;
$count{$th}++;
if ($t_run and $th eq 't') {
$t_run++;
}
if ($h_run and $th eq 'h') {
$h_run++;
}
if ($last_flip ne $th) {
# a run has just ended
$runs{$h_run}++ if $h_run;
$runs{$t_run}++ if $t_run;
$h_run = $t_run = 0;
$h_run = 1 if $th eq 'h';
$t_run = 1 if $th eq 't';
}
$last_flip = $th;
}
$runs{$h_run}++ if $h_run;
$runs{$t_run}++ if $t_run;
#print Dumper(\%runs); use Data::Dumper;
my @runs_in_order = sort {$a <=> $b} keys %runs;
foreach my $run_length (@runs_in_order) {
print "Got a [$run_length] run [$runs{$run_length}] times\n";
}
@msouth
Copy link
Author

msouth commented Jun 9, 2016

[mjsouth@msouth-ns-air ~ ]$ ./flip.pl
I'm going to flip a coin [1000] times...
Got a [1] run [213] times
Got a [2] run [136] times
Got a [3] run [74] times
Got a [4] run [32] times
Got a [5] run [14] times
Got a [6] run [4] times
Got a [7] run [4] times
Got a [8] run [3] times
Got a [9] run [1] times
Got a [10] run [1] times
[mjsouth@msouth-ns-air ~ ]$ ./flip.pl 50
I'm going to flip a coin [50] times...
Got a [1] run [14] times
Got a [2] run [7] times
Got a [3] run [3] times
Got a [4] run [2] times
Got a [5] run [1] times

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment