Skip to content
This repository
Browse code

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 authored

Showing 2 changed files with 24 additions and 1 deletion. Show diff stats Hide diff stats

  1. +5 1 lib/perl5i/2/ARRAY.pm
  2. +19 0 t/pick.t
6 lib/perl5i/2/ARRAY.pm
@@ -77,7 +77,11 @@ method pick ( $num ){
77 77 $num_left--;
78 78 $i++;
79 79 }
80   -
  80 +
  81 + # Don't return the picks in the same order as the original array
  82 + # Simulates what would happen if you shuffled first
  83 + @result = @result->shuffle;
  84 +
81 85 return wantarray ? @result : \@result;
82 86 }
83 87
19 t/pick.t
@@ -96,5 +96,24 @@ note "pick_one method";{
96 96
97 97 pick_one_ok([undef, undef, undef, undef]);
98 98 }
  99 +
  100 +note "pick shuffles the result"; {
  101 + my $not_in_order = 0;
  102 + my @array = (1..10);
  103 +
  104 + # Since @array is in ascending order, we should, eventually,
  105 + # get two picks where the first is larger than the second.
  106 + # There's a 50/50 chance for each pick, and with 1000 tries
  107 + # the odds of this failing are something like 1 in 1^300.
  108 + for(1..1000) {
  109 + my @picks = @array->pick(2);
  110 + next if $picks[0] < $picks[1];
  111 +
  112 + $not_in_order = 1;
  113 + last;
  114 + }
  115 +
  116 + ok $not_in_order;
  117 +}
99 118
100 119 done_testing;

0 comments on commit a8d93fb

Please sign in to comment.
Something went wrong with that request. Please try again.