Debian Codegraph @

ex21.sh

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