# [Chicago-talk] Random first numbers

Lee Aylward lee at laylward.com
Mon May 17 14:49:40 PDT 2010

```Hi,

I typically use List::Util's shuffle function. I can't really say if
it will give you better results, though.

--
Lee

On Mon, 17 May 2010 16:25:10 -0500

> I have a CGI-based study coded in Perl that needs to randomly assign
> participants to conditions.  The code below sucks:
>
>   my @conditions = qw/cond1 cond2 cond3 cond4a/;
>   shuffle(@conditions);
>   \$\$state{'condition'} = \$conditions[0];
>
> I've just run through a dozen tests and cond3 appeared 90% of the
> time and cond2 10% of the time (cond1 and cond4a never appearing).  I
> haven't run the numbers, but I think this is "statistically
> significant". I think my shuffle is a "good" one from the on-line
> Perl lore, but maybe I'm wrong:
>
> #----------------------------------------------------------
> # Durstenfeld's implementation of Fisher and Yates
> #----------------------------------------------------------
> sub shuffle {
>   my \$n = scalar @_;
>   while ( \$n > 0 ) {
>     \$n--;
>     my \$j = int rand \$n;
>     (\$_[\$j], \$_[\$n]) = (\$_[\$n], \$_[\$j]); # swap
>   }
> }
>
> Assuming that shuffle() is not the culprit, I think it's just that
> when I run this code quickly/repeatedly, rand() is getting seeded
> with substantially the same value and is generating essentially the
> same initial value.  If so, my question is whether there is a better
> way to generate random numbers (so that the first values are more
> random).
>
> I was wondering if anyone agreed/disagreed and whether anyone had a
> "lazy" solution... if not, I can enforce better randomness by keeping
> some sort of state in a database.
>
> -Alan
>
```