2010-01-11, 14:26(+00), Stephane CHAZELAS: > 2010-01-9, 06:23(-06), den...@netstrata.com: > [...] >> 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 "${di...@]}" >> 290 582 837 1130 1375 1635 1315 1126 845 574 291 >> >> The total is correct: >> >> $ unset t; for i in ${di...@]}; 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 "${di...@]}" >> 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 ${di...@]}; do ((t+=i)); done; echo $t >> 10047 > [...] > > I've been scratching my head for some time, but can't figure out > what's going on. I get the exact same behavior with ksh93 and > zsh. Again there, replacing RANDOM with $RANDOM fixes the > problem. Strange that all 3 shells would have the exact same > bug. Are we missing the obvious here?
Oh I get it dice[RANDOM%6+1 + RANDOM%6+1]++ is processed as dice[RANDOM%6+1 + RANDOM%6+1] = dice[RANDOM%6+1 + RANDOM%6+1] + 1 with RANDOM expanded to different values 4 times. which explains both the evenness and incorrect sum we get similar problems with: $ bash -c 'x=0; ((a[++x]++)); echo $x' 2 The +=, -=, *=... are also affected. -- Stéphane