aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Köhler <jean-luc@picard.franken.de>2022-12-12 22:12:31 +0100
committerThomas Köhler <jean-luc@picard.franken.de>2022-12-12 22:12:31 +0100
commitffc4d8685185f4c0a80863f6337ac5ccbf9ef535 (patch)
tree3143b54ca14230262e54ba277ec315bcfc4f4521
parent9801381b85125dbcb7a501a85337af1d9eee7f03 (diff)
downloadperlweeklychallenge-club-ffc4d8685185f4c0a80863f6337ac5ccbf9ef535.tar.gz
perlweeklychallenge-club-ffc4d8685185f4c0a80863f6337ac5ccbf9ef535.tar.bz2
perlweeklychallenge-club-ffc4d8685185f4c0a80863f6337ac5ccbf9ef535.zip
Add jeanluc2020's solution to challenge 195.
Signed-off-by: Thomas Köhler <jean-luc@picard.franken.de>
-rwxr-xr-xchallenge-195/jeanluc2020/perl/ch-1.pl31
-rwxr-xr-xchallenge-195/jeanluc2020/perl/ch-2.pl30
2 files changed, 61 insertions, 0 deletions
diff --git a/challenge-195/jeanluc2020/perl/ch-1.pl b/challenge-195/jeanluc2020/perl/ch-1.pl
new file mode 100755
index 0000000000..79573aa3fc
--- /dev/null
+++ b/challenge-195/jeanluc2020/perl/ch-1.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+
+foreach my $input (1..40) {
+ print "Input $input, output " . count_specials($input) . "\n";
+}
+
+sub count_specials {
+ my $number = shift;
+ my $specials = 0;
+ foreach my $i (1..$number) {
+ $specials += is_special($i);
+ }
+ return $specials;
+}
+
+sub is_special {
+ my $number = shift;
+ my $map;
+ # count all digits by adding 1 to the corresponding key in %$map for each digit
+ # the count is the value
+ map { $map->{$_}++ } split //, $number;
+ # sort values descending
+ my @values = reverse sort { $a <=> $b } values %$map;
+ # if the first element is 1, the number is special
+ if($values[0] == 1) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/challenge-195/jeanluc2020/perl/ch-2.pl b/challenge-195/jeanluc2020/perl/ch-2.pl
new file mode 100755
index 0000000000..ec92ca072b
--- /dev/null
+++ b/challenge-195/jeanluc2020/perl/ch-2.pl
@@ -0,0 +1,30 @@
+#!/usr/bin/perl
+
+my @list = (1,1,2,6,2);
+print "(" . join(",", @list) . ") => " . smallest_even_integer(@list) . "\n";
+@list = (1,3,5,7);
+print "(" . join(",", @list) . ") => " . smallest_even_integer(@list) . "\n";
+@list = (6,4,4,6,1);
+print "(" . join(",", @list) . ") => " . smallest_even_integer(@list) . "\n";
+
+sub smallest_even_integer {
+ # we need only even numbers
+ my @list = only_even(@_);
+ return -1 unless @list; # no even numbers found
+ my $map;
+ # count each number in %$map, key is the number, value its count
+ map { $map->{$_}++ } @list;
+ # sort @list by the count for each number descending
+ # if that's equal sort by the number ascending
+ my @sorted = sort { $map->{$b} <=> $map->{$a} || $a <=> $b } @list;
+ # solution is in the first element of the sorted array
+ return $sorted[0];
+}
+
+sub only_even {
+ my @result = ();
+ foreach my $elem (@_) {
+ push @result,$elem unless $elem % 2;
+ }
+ return @result;
+}