blib/lib/Data/Lotter.pm untested

filter: Statementstmt 0.0% 0 / 60 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 5 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 90 SCAR 40.3
CC
7
Cov
0%
pickup
56.0
new
2.0
left_items
2.0
CRAP 56.0
1 package Data::Lotter;
2  
3 use base qw( Class::Accessor::Fast );
4 use strict;
5 use 5.8.1;
6 our $VERSION = '0.00001_01';
7 use Data::Dumper;
8 use constant DEBUG => $ENV{DATA_LOTTER_DEBUG};
9  
10 __PACKAGE__->mk_accessors qw( lists available );
11  
12 sub new {
13 my $class = shift;
14 my %lists = @_;
15  
16 my $cumulative = 0;
17 foreach my $weight ( values %lists ) {
18 $weight = int($weight);
19 $cumulative += $weight;
20 }
21  
22 return $class->SUPER::new( { available => $cumulative, lists => \%lists } );
23 }
24  
25 sub pickup {
26 my $self = shift;
27 my $num = shift;
28 my $remove = shift || '';
29 my @ret;
30  
31 my $lists = $self->lists;
32 OUTER:
33 while ( $num-- ) {
34 Dumper $lists; # 本当はいらないけど、これがないとtestでこける?
35 my $n = int( rand( $self->available ) ) + 1;
36 if (DEBUG) {
37 print "NUM:$num\n";
38 print "-" x 10, "\n", "Random number: $n\n";
39 print Dumper $lists;
40 }
41 while ( my ( $item, $weight ) = each %$lists ) {
42 print "\tn = $n\n" if DEBUG;
43 if ( $weight > 0 && $weight >= $n ) {
44 push @ret, $item;
45 print "\tHIT!\t$item was pushed\n" if DEBUG;
46 if ($remove) {
47 delete $lists->{$item};
48 $self->available( $self->available - $weight );
49 }
50 else {
51 $lists->{$item} = $weight - 1;
52 $self->available( $self->available - 1 );
53 }
54 next OUTER;
55 }
56 $n -= $weight;
57 }
58 }
59 print join( "\,", @ret ), "\n" if DEBUG;
60 return @ret;
61 }
62  
63 sub left_items {
64 my $self = shift;
65 my @items = keys %{ $self->lists };
66 return @items;
67 }
68  
69 sub left_item_waits {
70 my $self = shift;
71 my $item = shift;
72 return $self->lists->{$item};
73 }
74  
75 1;
76  
77 __END__