Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to randomise a list 1

Status
Not open for further replies.

audiopro

Programmer
Apr 1, 2004
3,165
GB
I am randomising the order of numbers 1 - 10.
I have done it by looping through the numbers and re-trying if the chosen number is already included in the random list.
Is there a more efficient way of doing it?


Keith
 
You could use List::Util - here's a quick example:
Code:
use List::Util qw/shuffle/;
print "$_\n" for shuffle(1..10);
 
Thanks Rharsh but I do not have the List::Utill available.

This is what I am using.
Code:
	my $SIDEARTS=$query->param("sidad") || 0;
	$SIDEARTS=$SIDEARTS*2;
	my @POS;
	if($SIDEARTS > 0){
		my $count=0;
		my $ran_num=0;
		my $check;
		while($count < $SIDEARTS){
			$ran_num=int(rand($SIDEARTS))+1;
			$check=0;
			for($x=1; $x<=$count; ++$x){
				if($POS[$x] == $ran_num){
					++$check;
				}
			}
			if($check == 0){
				++$count;
				$POS[$count]=$ran_num;
			}
		}
	}

I works ok but I thought there may be a tidier way.

Keith
 
When your script makes you rich and famous, give credit for this bit to the guy who wrote the List::Util module. Here's the code right out of the module:
Code:
sub shuffle (@) {
  my @a=\(@_);
  my $n;
  my $i=@_;
  map {
    $n = rand($i--);
    (${$a[$n]}, $a[$n] = $a[$i])[0];
  } @_;
}
 
To give credit where it's due I think this ia actually the Fisher-Yates shuffle
Code:
sub fisher_yates_shuffle
  {
  my $deck = shift;  # $deck is a reference to an array
  my $i = @$deck;
  while ($i--)
    {
    my $j = int rand ($i+1);
    @$deck[$i,$j] = @$deck[$j,$i];
    }
  }
Named after the two Medical Statisticians

Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top