bug-bash
[Top][All Lists]
Advanced

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

Re: Problems when RANDOM without $ is used as an array index


From: Stephane CHAZELAS
Subject: Re: Problems when RANDOM without $ is used as an array index
Date: Mon, 11 Jan 2010 20:54:13 +0000 (UTC)
User-agent: slrn/pre1.0.0-16 (Linux)

2010-01-11, 14:26(+00), Stephane CHAZELAS:
> 2010-01-9, 06:23(-06), address@hidden:
> [...]
>> 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 "address@hidden"
>>  290 582 837 1130 1375 1635 1315 1126 845 574 291
>>
>> The total is correct:
>>
>>  $ unset t; for i in address@hidden; 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 "address@hidden"
>>  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 address@hidden; 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


reply via email to

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