Permalink
Browse files

Fixed style problems in pick method. Also updated pick.t to check if …

…an element occurs more than once.
  • Loading branch information...
qrazhan committed Nov 30, 2011
1 parent cdb1529 commit 74a67fe4d905654f5d7990f70ec670b9799c25d2
Showing with 21 additions and 11 deletions.
  1. +10 −9 lib/perl5i/2/ARRAY.pm
  2. +11 −2 t/pick.t
View
@@ -55,18 +55,19 @@ method pick ( $num ){
my @result = List::Util::shuffle(@$self);
return wantarray ? @result : \@result;
}
- my $nPicked = 0;
- my $nLeft = @$self;
- my $rand = 0;
- my @result = (1..$num);
- for(my $i =0; $num > 0; $i++){
- $rand = int(rand($nLeft));
+ my $num_picked = 0;
+ my $num_left = @$self;
+ my @result;
+ my $i=0;
+ while($num > 0){
+ my $rand = int(rand($num_left));
if($rand < $num){
- $result[$nPicked] = @$self[$i];
- $nPicked++;
+ $result[$num_picked] = @$self[$i];
+ $num_picked++;
$num--;
}
- $nLeft--;
+ $num_left--;
+ $i++;
}
return wantarray ? @result : \@result;
}
View
@@ -8,12 +8,21 @@ note 'pick method'; {
my @rand = @array->pick(5);
is @rand, 5;
-
+ my %rand_hash = @array->as_hash;
+ my %expected_hash;
+ foreach (@array){
+ if(exists $rand_hash{$_}){
+ $rand_hash{$_} -= 1;
+ $expected_hash{$_} = 0;
+ }
+ }
+ is_deeply \%rand_hash, \%expected_hash;
+
@rand = @array->pick(100);
is @rand, 9;
@rand = @array->pick(0);
is @rand, 0;
}
-done_testing(3);
+done_testing(4);

0 comments on commit 74a67fe

Please sign in to comment.