📄 randomvar.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>$RANDOM: generate random integer</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.57"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Variables Revisited"HREF="variables2.html"><LINKREL="PREVIOUS"TITLE="Indirect References to Variables"HREF="ivr.html"><LINKREL="NEXT"TITLE="The Double Parentheses Construct"HREF="dblparens.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="SECT1"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLEWIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="ivr.html">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 9. Variables Revisited</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="dblparens.html">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="RANDOMVAR">9.6. $RANDOM: generate random integer</A></H1><P><TTCLASS="VARNAME">$RANDOM</TT> is an internal Bash <AHREF="functions.html#FUNCTIONREF">function</A> (not a constant) that returns a <ICLASS="FIRSTTERM">pseudorandom</I> <ANAME="AEN5174"HREF="#FTN.AEN5174">[1]</A> integer in the range 0 - 32767. It should <TTCLASS="REPLACEABLE"><I>not</I></TT> be used to generate an encryption key.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX21"></A><P><B>Example 9-24. Generating random numbers</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 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</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="PICKCARD"></A><P><B>Example 9-25. Picking a random card from a deck</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # pick-card.sh 3 4 # This is an example of choosing random elements of an array. 5 6 7 # Pick a card, any card. 8 9 Suites="Clubs 10 Diamonds 11 Hearts 12 Spades" 13 14 Denominations="2 15 3 16 4 17 5 18 6 19 7 20 8 21 9 22 10 23 Jack 24 Queen 25 King 26 Ace" 27 28 # Note variables spread over multiple lines. 29 30 31 suite=($Suites) # Read into array variable. 32 denomination=($Denominations) 33 34 num_suites=${#suite[*]} # Count how many elements. 35 num_denominations=${#denomination[*]} 36 37 echo -n "${denomination[$((RANDOM%num_denominations))]} of " 38 echo ${suite[$((RANDOM%num_suites))]} 39 40 41 # $bozo sh pick-cards.sh 42 # Jack of Clubs 43 44 45 # Thank you, "jipe," for pointing out this use of $RANDOM. 46 exit 0</PRE></TD></TR></TABLE><HR></DIV><P> <ICLASS="EMPHASIS">Jipe</I> points out a set of techniques for generating random numbers within a range. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 # Generate random number between 6 and 30. 2 rnumber=$((RANDOM%25+6)) 3 4 # Generate random number in the same 6 - 30 range, 5 #+ but the number must be evenly divisible by 3. 6 rnumber=$(((RANDOM%30/3+1)*3)) 7 8 # Note that this will not work all the time. 9 # It fails if $RANDOM returns 0. 10 11 # Frank Wang suggests the following alternative: 12 rnumber=$(( RANDOM%27/3*3+6 ))</PRE></TD></TR></TABLE> </P><P> <ICLASS="EMPHASIS">Bill Gradwohl</I> came up with an improved formula that works for positive numbers. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 rnumber=$(((RANDOM%(max-min+divisibleBy))/divisibleBy*divisibleBy+min))</PRE></TD></TR></TABLE> </P><P>Here Bill presents a versatile function that returns a random number between two specified values.</P><DIVCLASS="EXAMPLE"><HR><ANAME="RANDOMBETWEEN"></A><P><B>Example 9-26. Random between values</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # random-between.sh 3 # Random number between two specified values. 4 # Script by Bill Gradwohl, with minor modifications by the document author. 5 # Used with permission. 6 7 8 randomBetween() { 9 # Generates a positive or negative random number 10 #+ between $min and $max 11 #+ and divisible by $divisibleBy. 12 # Gives a "reasonably random" distribution of return values. 13 # 14 # Bill Gradwohl - Oct 1, 2003 15 16 syntax() { 17 # Function embedded within function. 18 echo 19 echo "Syntax: randomBetween [min] [max] [multiple]" 20 echo 21 echo "Expects up to 3 passed parameters, but all are completely optional." 22 echo "min is the minimum value" 23 echo "max is the maximum value" 24 echo "multiple specifies that the answer must be a multiple of this value." 25 echo " i.e. answer must be evenly divisible by this number." 26 echo 27 echo "If any value is missing, defaults area supplied as: 0 32767 1" 28 echo "Successful completion returns 0, unsuccessful completion returns" 29 echo "function syntax and 1." 30 echo "The answer is returned in the global variable randomBetweenAnswer" 31 echo "Negative values for any passed parameter are handled correctly." 32 } 33 34 local min=${1:-0} 35 local max=${2:-32767} 36 local divisibleBy=${3:-1} 37 # Default values assigned, in case parameters not passed to function. 38 39 local x 40 local spread 41 42 # Let's make sure the divisibleBy value is positive. 43 [ ${divisibleBy} -lt 0 ] && divisibleBy=$((0-divisibleBy)) 44 45 # Sanity check. 46 if [ $# -gt 3 -o ${divisibleBy} -eq 0 -o ${min} -eq ${max} ]; then 47 syntax 48 return 1 49 fi 50 51 # See if the min and max are reversed. 52 if [ ${min} -gt ${max} ]; then 53 # Swap them. 54 x=${min} 55 min=${max} 56 max=${x} 57 fi 58 59 # If min is itself not evenly divisible by $divisibleBy, 60 #+ then fix the min to be within range. 61 if [ $((min/divisibleBy*divisibleBy)) -ne ${min} ]; then 62 if [ ${min} -lt 0 ]; then 63 min=$((min/divisibleBy*divisibleBy)) 64 else 65 min=$((((min/divisibleBy)+1)*divisibleBy)) 66 fi 67 fi 68 69 # If max is itself not evenly divisible by $divisibleBy, 70 #+ then fix the max to be within range. 71 if [ $((max/divisibleBy*divisibleBy)) -ne ${max} ]; then 72 if [ ${max} -lt 0 ]; then 73 max=$((((max/divisibleBy)-1)*divisibleBy)) 74 else 75 max=$((max/divisibleBy*divisibleBy)) 76 fi 77 fi 78 79 # --------------------------------------------------------------------- 80 # Now, to do the real work. 81 82 # Note that to get a proper distribution for the end points, 83 #+ the range of random values has to be allowed to go between 84 #+ 0 and abs(max-min)+divisibleBy, not just abs(max-min)+1. 85 86 # The slight increase will produce the proper distribution for the 87 #+ end points. 88 89 # Changing the formula to use abs(max-min)+1 will still produce 90 #+ correct answers, but the randomness of those answers is faulty in 91 #+ that the number of times the end points ($min and $max) are returned 92 #+ is considerably lower than when the correct formula is used. 93 # --------------------------------------------------------------------- 94 95 spread=$((max-min)) 96 [ ${spread} -lt 0 ] && spread=$((0-spread)) 97 let spread+=divisibleBy 98 randomBetweenAnswer=$(((RANDOM%spread)/divisibleBy*divisibleBy+min)) 99 100 return 0 101 102 # However, Paulo Marcel Coelho Aragao points out that 103 #+ when $max and $min are not divisible by $divisibleBy, 104 #+ the formula fails. 105 # 106 # He suggests instead the following formula: 107 # rnumber = $(((RANDOM%(max-min+1)+min)/divisibleBy*divisibleBy)) 108 109 } 110 111 # Let's test the function. 112 min=-14 113 max=20 114 divisibleBy=3 115 116 117 # Generate an array of expected answers and check to make sure we get 118 #+ at least one of each answer if we loop long enough. 119 120 declare -a answer 121 minimum=${min} 122 maximum=${max} 123 if [ $((minimum/divisibleBy*divisibleBy)) -ne ${minimum} ]; then 124 if [ ${minimum} -lt 0 ]; then 125 minimum=$((minimum/divisibleBy*divisibleBy)) 126 else 127 minimum=$((((minimum/divisibleBy)+1)*divisibleBy)) 128 fi 129 fi 130 131 132 # If max is itself not evenly divisible by $divisibleBy, 133 #+ then fix the max to be within range. 134 135 if [ $((maximum/divisibleBy*divisibleBy)) -ne ${maximum} ]; then 136 if [ ${maximum} -lt 0 ]; then 137 maximum=$((((maximum/divisibleBy)-1)*divisibleBy)) 138 else 139 maximum=$((maximum/divisibleBy*divisibleBy)) 140 fi 141 fi 142 143 144 # We need to generate only positive array subscripts, 145 #+ so we need a displacement that that will guarantee 146 #+ positive results.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -