Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- my $min = 1; # Min die value.
- my $max = 6; # Max die value
- my $numdice = 4;
- my $dice; # ref to the table with dice.
- my $num; # number of combinations.
- my $hist; # histogram
- sub High_one;
- prepare_dice();
- # print "@{$dice}" . "\n";
- # for (my $i=1; $i<216; $i++)
- # { forward_dice();
- # }
- do
- {
- # print "@{$dice}" . "\n";
- $$hist{High_two()} += 1;
- } while (forward_dice());
- # print "@{$dice} Num: $num\n";
- print_hist();
- # Init $dice to $numdice dice with value $min.
- sub prepare_dice
- { $dice = undef;
- $num = 1;
- for (my $i=0; $i<$numdice; $i++)
- { push (@{$dice}, $min);
- }
- }
- # Forwards dice by 1 and takes care of overflows.
- # Returns 0 when there are no more combinations, 1 otherwise.
- sub forward_dice
- { my $ind = $numdice -1;
- my $ovf = 0; # Overflow
- do
- { $ovf = 0;
- $$dice[$ind] += 1;
- if ($$dice[$ind] > $max)
- { $$dice[$ind] = $min;
- $ind--;
- $ovf = 1;
- }
- } while ($ovf and ($ind >= 0));
- if ($ind >= 0)
- { $num++;
- return 1;
- }
- return 0;
- }
- # Return the highest die.
- sub High_one
- { my @sorted = sort { $b <=> $a} @$dice;
- return $sorted[0];
- }
- # Return the sum of two highest dice.
- sub High_two
- { my @sorted = sort { $b <=> $a} @$dice;
- return $sorted[0] + $sorted[1];
- }
- # Print histohram.
- sub print_hist
- { my %upto = (); # Number of this or lower.
- foreach my $i (sort { $a <=> $b} keys %$hist)
- { $upto[$i] = $$hist{$i};
- $upto[$i] += $upto[$i-1] if (defined $upto[$i-1]);
- }
- my %gteq = (); # Number of this or higher
- foreach my $i (sort { $b <=> $a} keys %$hist)
- { $gteq[$i] = $$hist{$i};
- $gteq[$i] += $gteq[$i+1] if (defined $gteq[$i+1]);
- }
- my $avg = 0; # Compute average and standard deviation.
- my $stdev = 0;
- foreach my $i (keys %$hist)
- { $avg += $i * $$hist{$i};
- }
- $avg /= $num;
- $avg = sprintf '%2.4f', $avg;
- foreach my $i (keys %$hist)
- { $stdev += ($avg - $i) * ($avg - $i);
- }
- $stdev /= keys (%$hist);
- $stdev = sprintf '%2.4f', sqrt($stdev);
- print "Dice: Highest 2 of $numdice, combinations: $num, Average: $avg, Stdev: $stdev \n";
- print "Outcome, Probability, LowerOrEqual, HigherOrEqual \n";
- foreach my $i (sort { $a <=> $b} keys %$hist)
- { my $ind = sprintf "%2d", $i;
- my $prob = sprintf '%.6f', $$hist{$i}/$num;
- my $lowEq = sprintf '%.6f', $upto[$i]/$num;
- my $gtEq = sprintf '%.6f', $gteq[$i]/$num;
- print "$ind, $prob, $lowEq, $gtEq \n";
- }
- #print "@{$hist} \n";
- }
- # Sortowanie takie jak potrzebuję, z zachowaniem tablicy źródłowej i od największej liczby do najmniejszej:
- # my @sorted = sort { $b <=> $a} @$aref;
- # Wystarczy wtedy wziąść pewną część liczb od początku.
- # Ewentualnie obciąć:
- # my @third = splice(@sorted, 0, 2); // Pierwsze 2.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement