in reply to How do I pick a random element from an array?

This node falls below the community's minimum standard of quality and will not be displayed.

Replies are listed 'Best First'.
Re: Answer: How do I pick a random element from an array?
by Abigail-II (Bishop) on Aug 21, 2002 at 10:59 UTC
    Wrong.

    That will never pick the last element.

    #!/usr/bin/perl use strict; use warnings 'all'; my @array = qw /first middle last/; my $count = 0; my $sec = 100; $SIG {ALRM} = sub { die "Ran for $sec seconds, trying $count times and failed.\n" }; alarm $sec; my $randomIndex; do { $count ++; $randomIndex = rand $#array; } until $array [$randomIndex] eq "last"; print "Success after $count tries.\n"; __END__ Ran for 100 seconds, trying 29495241 times and failed.
    However, if we change the rand $#array to rand @array, we get:
    Success after 2 tries.
    or some other small number.

    Abigail