| 1 | #!/bin/bash |
| 2 | # How random is RANDOM? |
| 3 | |
| 4 | RANDOM=$$ # Reseed the random number generator using script process ID. |
| 5 | |
| 6 | PIPS=6 # A die has 6 pips. |
| 7 | MAXTHROWS=600 # Increase this if you have nothing better to do with your time. |
| 8 | throw=0 # Number of times the dice have been cast. |
| 9 | |
| 10 | ones=0 # Must initialize counts to zero, |
| 11 | twos=0 #+ since an uninitialized variable is null, NOT zero. |
| 12 | threes=0 |
| 13 | fours=0 |
| 14 | fives=0 |
| 15 | sixes=0 |
| 16 | |
| 17 | print_result () |
| 18 | { |
| 19 | echo |
| 20 | echo "ones = $ones" |
| 21 | echo "twos = $twos" |
| 22 | echo "threes = $threes" |
| 23 | echo "fours = $fours" |
| 24 | echo "fives = $fives" |
| 25 | echo "sixes = $sixes" |
| 26 | echo |
| 27 | } |
| 28 | |
| 29 | update_count() |
| 30 | { |
| 31 | case "$1" in |
| 32 | 0) ((ones++));; # Since a die has no "zero", this corresponds to 1. |
| 33 | 1) ((twos++));; # And this to 2. |
| 34 | 2) ((threes++));; # And so forth. |
| 35 | 3) ((fours++));; |
| 36 | 4) ((fives++));; |
| 37 | 5) ((sixes++));; |
| 38 | esac |
| 39 | } |
| 40 | |
| 41 | echo |
| 42 | |
| 43 | |
| 44 | while [ "$throw" -lt "$MAXTHROWS" ] |
| 45 | do |
| 46 | let "die1 = RANDOM % $PIPS" |
| 47 | update_count $die1 |
| 48 | let "throw += 1" |
| 49 | done |
| 50 | |
| 51 | print_result |
| 52 | |
| 53 | exit $? |
| 54 | |
| 55 | # The scores should distribute evenly, assuming RANDOM is random. |
| 56 | # With $MAXTHROWS at 600, all should cluster around 100, |
| 57 | #+ plus-or-minus 20 or so. |
| 58 | # |
| 59 | # Keep in mind that RANDOM is a ***pseudorandom*** generator, |
| 60 | #+ and not a spectacularly good one at that. |
| 61 | |
| 62 | # Randomness is a deep and complex subject. |
| 63 | # Sufficiently long "random" sequences may exhibit |
| 64 | #+ chaotic and other "non-random" behavior. |
| 65 | |
| 66 | # Exercise (easy): |
| 67 | # --------------- |
| 68 | # Rewrite this script to flip a coin 1000 times. |
| 69 | # Choices are "HEADS" and "TAILS." |