Permalink
Browse files

Make pick() not always return in the same order as the @array.

This simulates what would happen with a normal shuffle & pick algorithm.
  • Loading branch information...
1 parent 7003663 commit a8d93fb8b69fd220ea97fbcb4e3b5b7225f7d245 @schwern schwern committed Jan 24, 2012
Showing with 24 additions and 1 deletion.
  1. +5 −1 lib/perl5i/2/ARRAY.pm
  2. +19 −0 t/pick.t
View
6 lib/perl5i/2/ARRAY.pm
@@ -77,7 +77,11 @@ method pick ( $num ){
$num_left--;
$i++;
}
-
+
+ # Don't return the picks in the same order as the original array
+ # Simulates what would happen if you shuffled first
+ @result = @result->shuffle;
+
return wantarray ? @result : \@result;
}
View
19 t/pick.t
@@ -96,5 +96,24 @@ note "pick_one method";{
pick_one_ok([undef, undef, undef, undef]);
}
+
+note "pick shuffles the result"; {
+ my $not_in_order = 0;
+ my @array = (1..10);
+
+ # Since @array is in ascending order, we should, eventually,
+ # get two picks where the first is larger than the second.
+ # There's a 50/50 chance for each pick, and with 1000 tries
+ # the odds of this failing are something like 1 in 1^300.
+ for(1..1000) {
+ my @picks = @array->pick(2);
+ next if $picks[0] < $picks[1];
+
+ $not_in_order = 1;
+ last;
+ }
+
+ ok $not_in_order;
+}
done_testing;

0 comments on commit a8d93fb

Please sign in to comment.