dice game 2016


SUBMITTED BY: foxhunters

DATE: Aug. 8, 2016, 12:27 a.m.

FORMAT: Text only

SIZE: 1.6 kB

HITS: 1083

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

comments powered by Disqus