commit cc87233946533fe478bcf1dd05b0dfe5513ea5a9
parent 8d5a702385178e91a19be9325f1edb6f82b9e90a
Author: Samir Parikh <noreply@samirparikh.com>
Date: Sun, 23 Jan 2022 16:18:14 +0000
get all tests to pass for palindrome-products
Diffstat:
1 file changed, 31 insertions(+), 28 deletions(-)
diff --git a/palindrome-products/Palindrome.pm b/palindrome-products/Palindrome.pm
@@ -2,45 +2,48 @@ package Palindrome;
use strict;
use warnings;
-use Math::Prime::Util 'factor';
+use List::Util qw(min max);
sub new {
my ( $class, $min_max ) = @_;
- my $self = bless ( {}, $class );
- $self->_init( $min_max );
- #print "min_factor is ", $self->{min_factor}, " and max_factor is ", $self->{max_factor}, "\n";
- return $self;
+
+ # check whether min_factor key exists; if not, set to 1
+ $min_max->{min_factor} = 1 unless ( exists $min_max->{min_factor} );
+
+ # %factors is a hash whose values are array references containting
+ # factor pairs for the products (which are represented by the keys)
+ my %factors;
+ foreach my $x ( $min_max->{min_factor} .. $min_max->{max_factor} ) {
+ foreach my $y ( $x .. $min_max->{max_factor} ) {
+ my $product = $x * $y;
+ # add factor pair if product is a palindrome
+ push @{$factors{$product}} => [$x, $y] if (_is_palindrome($product));
+ }
+ }
+
+ # return an object that represents all palindrome products and their factors
+ bless \%factors, $class
}
-#sub _init {
-# my ( $self, $arg ) = @_;
-# my $min_factor = $arg->{min_factor};
-# unless (defined $min_factor ) {
-# $self->{min_factor} = 1;
-# }
-# $self->{min_factor} = defined $arg->{min_factor} ?
-# $arg->{min_factor} :
-# 1;
-# $self->{max_factor} = $arg->{max_factor};
-#}
sub largest {
my $self = shift;
- print "my min factor is ", $self->{min_factor}, "\n";
- print "my max factor is ", $self->{max_factor}, "\n";
- #my @factors = factor(9);
- #print "my factors are @factors\n";
- my %answer = (
- value => 9,
- factors => [ [1, 9], [3, 3] ],
- );
- return \%answer;
+ my $largest_product = max keys %{ $self }; # hash keys are not sorted
+ return ( {
+ value => $largest_product,
+ factors => $self->{ $largest_product },
+ }
+ );
}
sub smallest {
my $self = shift;
-
- return undef;
+ my $smallest_product = min keys %{ $self }; # hash keys are not sorted
+ return ( {
+ value => $smallest_product,
+ factors => $self->{ $smallest_product },
+ }
+ );
}
sub _init {
@@ -50,7 +53,7 @@ sub _init {
$self->{max_factor} = $arg->{max_factor};
}
-sub is_palindrome {
+sub _is_palindrome {
return $_[0] eq reverse $_[0];
}