best scrip of the net


SUBMITTED BY: foxhunters

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

FORMAT: Text only

SIZE: 2.5 kB

HITS: 7676

  1. #!/bin/bash
  2. # $RANDOM returns a different random integer at each invocation.
  3. # Nominal range: 0 - 32767 (signed 16-bit integer).
  4. MAXCOUNT=10
  5. count=1
  6. echo
  7. echo "$MAXCOUNT random numbers:"
  8. echo "-----------------"
  9. while [ "$count" -le $MAXCOUNT ] # Generate 10 ($MAXCOUNT) random integers.
  10. do
  11. number=$RANDOM
  12. echo $number
  13. let "count += 1" # Increment count.
  14. done
  15. echo "-----------------"
  16. # If you need a random int within a certain range, use the 'modulo' operator.
  17. # This returns the remainder of a division operation.
  18. RANGE=500
  19. echo
  20. number=$RANDOM
  21. let "number %= $RANGE"
  22. # ^^
  23. echo "Random number less than $RANGE --- $number"
  24. echo
  25. # If you need a random integer greater than a lower bound,
  26. #+ then set up a test to discard all numbers below that.
  27. FLOOR=200
  28. number=0 #initialize
  29. while [ "$number" -le $FLOOR ]
  30. do
  31. number=$RANDOM
  32. done
  33. echo "Random number greater than $FLOOR --- $number"
  34. echo
  35. # Let's examine a simple alternative to the above loop, namely
  36. # let "number = $RANDOM + $FLOOR"
  37. # That would eliminate the while-loop and run faster.
  38. # But, there might be a problem with that. What is it?
  39. # Combine above two techniques to retrieve random number between two limits.
  40. number=0 #initialize
  41. while [ "$number" -le $FLOOR ]
  42. do
  43. number=$RANDOM
  44. let "number %= $RANGE" # Scales $number down within $RANGE.
  45. done
  46. echo "Random number between $FLOOR and $RANGE --- $number"
  47. echo
  48. # Generate binary choice, that is, "true" or "false" value.
  49. BINARY=2
  50. T=1
  51. number=$RANDOM
  52. let "number %= $BINARY"
  53. # Note that let "number >>= 14" gives a better random distribution
  54. #+ (right shifts out everything except last binary digit).
  55. if [ "$number" -eq $T ]
  56. then
  57. echo "TRUE"
  58. else
  59. echo "FALSE"
  60. fi
  61. echo
  62. # Generate a toss of the dice.
  63. SPOTS=6 # Modulo 6 gives range 0 - 5.
  64. # Incrementing by 1 gives desired range of 1 - 6.
  65. # Thanks, Paulo Marcel Coelho Aragao, for the simplification.
  66. die1=0
  67. die2=0
  68. # Would it be better to just set SPOTS=7 and not add 1? Why or why not?
  69. # Tosses each die separately, and so gives correct odds.
  70. let "die1 = $RANDOM % $SPOTS +1" # Roll first one.
  71. let "die2 = $RANDOM % $SPOTS +1" # Roll second one.
  72. # Which arithmetic operation, above, has greater precedence --
  73. let "throw = $die1 + $die2"
  74. echo "Throw of the dice = $throw"
  75. echo
  76. exit 0

comments powered by Disqus