From 0c05530197191561a9ca62edd8ac164dfea0e119 Mon Sep 17 00:00:00 2001 From: andrezgz Date: Tue, 6 Aug 2019 18:24:11 -0300 Subject: challenge-020 andrezgz solution --- challenge-020/andrezgz/perl5/ch-1.pl | 12 +++++++++++ challenge-020/andrezgz/perl5/ch-1.sh | 5 +++++ challenge-020/andrezgz/perl5/ch-2.pl | 42 ++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 challenge-020/andrezgz/perl5/ch-1.pl create mode 100644 challenge-020/andrezgz/perl5/ch-1.sh create mode 100644 challenge-020/andrezgz/perl5/ch-2.pl diff --git a/challenge-020/andrezgz/perl5/ch-1.pl b/challenge-020/andrezgz/perl5/ch-1.pl new file mode 100644 index 0000000000..ba3c444ef5 --- /dev/null +++ b/challenge-020/andrezgz/perl5/ch-1.pl @@ -0,0 +1,12 @@ +#!/usr/bin/perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-019/ +# Task #1 +# Write a script to accept a string from command line and split it on change of character. +# For example, if the string is "ABBCDEEF", then it should split like "A", "BB", "C", "D", "EE", "F". + +use strict; +use warnings; + +my $s = $ARGV[0] || 'ABBCDEEF'; +while ($s =~ /(([A-Z])\2*)/g) { print "$1\n"; }; diff --git a/challenge-020/andrezgz/perl5/ch-1.sh b/challenge-020/andrezgz/perl5/ch-1.sh new file mode 100644 index 0000000000..b2b22220ec --- /dev/null +++ b/challenge-020/andrezgz/perl5/ch-1.sh @@ -0,0 +1,5 @@ +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-019/ +# Task #1 +# Write a script to accept a string from command line and split it on change of character. +# For example, if the string is "ABBCDEEF", then it should split like "A", "BB", "C", "D", "EE", "F". +perl -e 'while ($ARGV[0] =~ /(([A-Z])\2*)/g) { print "$1\n"; };' $1 diff --git a/challenge-020/andrezgz/perl5/ch-2.pl b/challenge-020/andrezgz/perl5/ch-2.pl new file mode 100644 index 0000000000..8344578299 --- /dev/null +++ b/challenge-020/andrezgz/perl5/ch-2.pl @@ -0,0 +1,42 @@ +#!/usr/bin/perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-019/ +# Task #2 +# Write a script to print the smallest pair of Amicable Numbers. +# For more information, please checkout wikipedia page. +# https://en.wikipedia.org/wiki/Amicable_numbers + +use strict; +use warnings; + +my $n = 0; +until (amicable(++$n)) {}; +print "Smallest pair of Amicable Numbers: ($n,".amicable($n).")\n"; + +{ + my %cache; + sub amicable { + my $n = shift; + + $cache{$n} = sum(factors($n)) unless exists $cache{$n}; + my $m = $cache{$n}; + return if $m == $n; # same number + + $cache{$m} = sum(factors($m)) unless exists $cache{$m}; + return if $cache{$m} != $n; # not amicable + + return $m; + } +} + +sub sum { + my $s = 0; + $s += $_ for @_; + return $s; +} + +sub factors { + my $n = shift; + my $upto = $n == 1 ? 1 : $n/2; + return grep {$n % $_ == 0} (1 .. $upto); +} -- cgit