commit 0c230b77b5bf4b6371906f38ee72e66cb7cad63a
parent 17b55567772f3d1eb7997509381b8eafec005154
Author: Samir Parikh <noreply@samirparikh.com>
Date: Thu, 12 May 2022 14:12:19 +0000
get all tests to pass
Diffstat:
1 file changed, 17 insertions(+), 13 deletions(-)
diff --git a/anagram/Anagram.pm b/anagram/Anagram.pm
@@ -6,28 +6,32 @@ our @EXPORT_OK = qw<match_anagrams>;
sub is_anagram {
my ( $subject, $candidate ) = @_;
-# print "subject = $subject\n";
-# print "candidate = $candidate\n";
- my %subject_hash = map { $_ => 1 } split //, $subject;
- my %candidate_hash = map { $_ => 1 } split //, $candidate;
+
return 0 if ( $subject eq $candidate );
return 0 if ( length( $subject ) != length( $candidate ) );
- return 1 unless grep (!$candidate_hash{ $_ }, keys %subject_hash);
- return 0;
+
+ my %subject_hash;
+ my %candidate_hash;
+
+ $subject_hash{ $_ } += 1 foreach ( split //, $subject );
+ $candidate_hash{ $_ } += 1 foreach ( split //, $candidate );
+
+ return 1 unless grep( $subject_hash{ $_ } != $candidate_hash{ $_ },
+ keys %subject_hash );
+
+return 0;
}
sub match_anagrams {
my ($input) = @_;
my @output;
- #print "$input->{subject}\n";
-# print "@{ $input->{candidates} }\n";
-# print "$input->{candidates}->[0]\n";
- foreach ( @{ $input->{candidates} } ) {
- #is_anagram( $input->{subject}, $_ );
+
+foreach ( @{ $input->{candidates} } ) {
push @output => $_ if is_anagram( lc $input->{subject}, lc $_ );
}
- #return undef;
- return \@output;
+
+return \@output;
+
}
1;