Shlomi Fish avatar Shlomi Fish committed 00993e4

Add the shuffle method to MicrosoftRand.

Comments (0)

Files changed (3)

abc-path/Games-ABC_Path-Generator/Changes

 
     - Improved lib/Games/ABC_Path/Generator.pm with acknowldgements, a 
     "SEE ALSO" section and a "DESCRIPTION" section.
+    - Add the shuffle method to lib/Games/ABC_Path/MicrosoftRand.pm .
     
 0.0.1       Thu Jul 21 19:02:11 IDT 2011
     - First version, released on an unsuspecting world.

abc-path/Games-ABC_Path-Generator/lib/Games/ABC_Path/MicrosoftRand.pm

     return ($self->rand() % $max);
 }
 
+sub shuffle {
+    my ($self, $deck) = @_;
+    return unless @$deck; # must not be empty!
+
+    my $i = @$deck;
+    while (--$i) {
+        my $j = $self->max_rand($i+1);
+        @$deck[$i,$j] = @$deck[$j,$i];
+    }
+
+    return;
+}
+
 =head1 SUBROUTINES/METHODS
 
 =head2 new
 
 Can be used to re-assign the seed of the randomizer (though not recommended).
 
+=head2 my $array_ref = $randomizer->shuffle(\@array)
+
+Shuffles the array reference of the first argument, B<destroys it> and returns
+it. This is using the fisher-yates shuffle.
+
 =cut
 
 =head1 AUTHOR

abc-path/Games-ABC_Path-Generator/t/ms-rand.t

 use strict;
 use warnings;
 
-use Test::More tests => 3;
+use Test::More tests => 4;
+
+use Test::Differences;
 
 use Games::ABC_Path::MicrosoftRand;
 
     # TEST
     is ($r->rand(), 6_334, "3rd result for seed 1 is 6,334.");
 }
+
+{
+    my $r = Games::ABC_Path::MicrosoftRand->new(seed => 24);
+
+    my @array = (0 .. 9);
+
+    $r->shuffle(\@array);
+    # TEST
+    eq_or_diff(
+        \@array,
+        [1,7,9,8,4,5,3,2,0,6],
+        'Array was shuffled.',
+    );
+}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.