Skip to content
This repository
Browse code

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

…an element occurs more than once.
  • Loading branch information...
commit 74a67fe4d905654f5d7990f70ec670b9799c25d2 1 parent cdb1529
Prashan Dharmasena authored November 29, 2011
19  lib/perl5i/2/ARRAY.pm
@@ -55,18 +55,19 @@ method pick ( $num ){
55 55
         my @result = List::Util::shuffle(@$self);
56 56
         return wantarray ? @result : \@result;
57 57
     }
58  
-    my $nPicked = 0;
59  
-    my $nLeft = @$self;
60  
-    my $rand = 0;
61  
-    my @result = (1..$num);
62  
-    for(my $i =0; $num > 0; $i++){
63  
-        $rand = int(rand($nLeft));
  58
+    my $num_picked = 0;
  59
+    my $num_left = @$self;
  60
+    my @result;
  61
+    my $i=0;
  62
+    while($num > 0){
  63
+        my $rand = int(rand($num_left));
64 64
         if($rand < $num){
65  
-            $result[$nPicked] = @$self[$i];
66  
-            $nPicked++;
  65
+            $result[$num_picked] = @$self[$i];
  66
+            $num_picked++;
67 67
             $num--;
68 68
         }
69  
-        $nLeft--;
  69
+        $num_left--;
  70
+        $i++;
70 71
     }
71 72
     return wantarray ? @result : \@result;
72 73
 }
13  t/pick.t
@@ -8,7 +8,16 @@ note 'pick method'; {
8 8
 
9 9
     my @rand = @array->pick(5);
10 10
     is @rand, 5;
11  
-
  11
+    my %rand_hash = @array->as_hash;
  12
+    my %expected_hash;
  13
+    foreach (@array){
  14
+        if(exists $rand_hash{$_}){
  15
+            $rand_hash{$_} -= 1;
  16
+            $expected_hash{$_} = 0;
  17
+        }
  18
+    }
  19
+    is_deeply \%rand_hash, \%expected_hash;
  20
+   
12 21
     @rand = @array->pick(100);
13 22
     is @rand, 9;
14 23
 
@@ -16,4 +25,4 @@ note 'pick method'; {
16 25
     is @rand, 0;
17 26
 }
18 27
  
19  
-done_testing(3);
  28
+done_testing(4);

0 notes on commit 74a67fe

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