bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Problems when RANDOM without $ is used as an array index


From: dennis
Subject: Problems when RANDOM without $ is used as an array index
Date: Sat, 9 Jan 2010 06:23:33 -0600

Configuration Information [Automatically generated, do not change]:
Machine: i486
OS: linux-gnu
Compiler: gcc
Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='i486' 
-DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='i486-pc-linux-gnu' 
-DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL 
-DHAVE_CONFIG_H   -I.  -I../bash -I../bash/include -I../bash/lib   -g -O2 -Wall
uname output: Linux emperor 2.6.31-14-generic #48-Ubuntu SMP Fri Oct 16 
14:04:26 UTC 2009 i686 GNU/Linux
Machine Type: i486-pc-linux-gnu

Bash Version: 4.0
Patch Level: 33
Release Status: release

Description:

When RANDOM is used as an array index, the behavior is different depending on 
whether $RANDOM or RANDOM is used.

Also reproduced on Bash 3.2.49(23)-release under cygwin

Repeat-By:

This produces the correct distribution of dice values for two six-sided dice:

 $ unset dice; for i in {1..10000}; do ((dice[$RANDOM%6+1 + $RANDOM%6+1]++)); 
done; echo "${dice[@]}"
 290 582 837 1130 1375 1635 1315 1126 845 574 291

The total is correct:

 $ unset t; for i in ${dice[@]}; do ((t+=i)); done; echo $t
 10000
 
This creates an even distribution which is incorrect:
 
 $ unset dice; for i in {1..10000}; do ((dice[RANDOM%6+1 + RANDOM%6+1]++)); 
done; echo "${dice[@]}"
 886 884 887 882 885 879 886 887 881 879 883

And the total is incorrect (may be larger or smaller):

 $ unset t; for i in ${dice[@]}; do ((t+=i)); done; echo $t
 10047
 
The even distribution is the same as is produced by:

 $ unset dice; for i in {1..10000}; do ((dice[RANDOM%11+2]++)); done; echo 
"${dice[@]}"

The total here, by the way, is incorrect, too, if there's no $ on RANDOM, but 
correct when there is.

The indices are the same in all cases:

 $ echo ${!dice[@]}
 2 3 4 5 6 7 8 9 10 11 12

Using a variable instead of RANDOM works correctly with or without a $:

 $ unset dice t; var=0; for i in {1..10000}; do ((dice[var%11+2]++)); 
((var+=1)); done; echo "${dice[@]}"; echo ${!dice[@]}; for i in ${dice[@]}; do 
((t+=i)); done; echo $t
 9091 9091 9091 9091 9091 9091 9091 9091 9090 9091 9091
 2 3 4 5 6 7 8 9 10 11 12
 100000

Fix:





reply via email to

[Prev in Thread] Current Thread [Next in Thread]