Palindrome.pm (1518B) - raw
1 package Palindrome; 2 3 use strict; 4 use warnings; 5 use List::Util qw(min max); 6 7 sub new { 8 my ( $class, $min_max ) = @_; 9 10 # check whether min_factor key exists; if not, set to 1 11 $min_max->{min_factor} = 1 unless ( exists $min_max->{min_factor} ); 12 13 # %factors is a hash whose values are array references containting 14 # factor pairs for the products (which are represented by the keys) 15 my %factors; 16 foreach my $x ( $min_max->{min_factor} .. $min_max->{max_factor} ) { 17 foreach my $y ( $x .. $min_max->{max_factor} ) { 18 my $product = $x * $y; 19 # add factor pair if product is a palindrome 20 push @{$factors{$product}} => [$x, $y] if (_is_palindrome($product)); 21 } 22 } 23 24 # return an object that represents all palindrome products and their factors 25 bless \%factors, $class 26 } 27 28 29 sub largest { 30 my $self = shift; 31 my $largest_product = max keys %{ $self }; # hash keys are not sorted 32 return ( { 33 value => $largest_product, 34 factors => $self->{ $largest_product }, 35 } 36 ); 37 } 38 39 sub smallest { 40 my $self = shift; 41 my $smallest_product = min keys %{ $self }; # hash keys are not sorted 42 return ( { 43 value => $smallest_product, 44 factors => $self->{ $smallest_product }, 45 } 46 ); 47 } 48 49 sub _init { 50 my ( $self, $arg ) = @_; 51 $self->{min_factor} = 52 defined $arg->{min_factor} ? $arg->{min_factor} : 1; 53 $self->{max_factor} = $arg->{max_factor}; 54 } 55 56 sub _is_palindrome { 57 return $_[0] eq reverse $_[0]; 58 } 59 60 1;