Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
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...
commit a8d93fb8b69fd220ea97fbcb4e3b5b7225f7d245 1 parent 7003663
Michael G. Schwern schwern authored
Showing with 24 additions and 1 deletion.
  1. +5 −1 lib/perl5i/2/ARRAY.pm
  2. +19 −0 t/pick.t
6 lib/perl5i/2/ARRAY.pm
View
@@ -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;
}
19 t/pick.t
View
@@ -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;
Please sign in to comment.
Something went wrong with that request. Please try again.