Dave's Brain

Browse - Programming Tips - How can I shuffle (randomize) an array in perl?

Date: 2009dec27
Language: perl

Q.  How can I shuffle (randomize) an array in perl?

A.  Here's a function that does it:

sub fisher_yates_shuffle($) { my $array = shift; my $i, $j; for ($i = @$array; --$i; ) { $j = int rand($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } sub example_use() { my(@a) = qw(aaa bbb ccc ddd); fisher_yates_shuffle(\@a); }
Source: perl cookbook

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.