aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-020/paulo-custodio/README1
-rw-r--r--challenge-020/paulo-custodio/perl/ch-1.pl22
-rw-r--r--challenge-020/paulo-custodio/perl/ch-2.pl51
-rw-r--r--challenge-020/paulo-custodio/test.pl22
4 files changed, 96 insertions, 0 deletions
diff --git a/challenge-020/paulo-custodio/README b/challenge-020/paulo-custodio/README
new file mode 100644
index 0000000000..87dc0b2fbd
--- /dev/null
+++ b/challenge-020/paulo-custodio/README
@@ -0,0 +1 @@
+Solution by Paulo Custodio
diff --git a/challenge-020/paulo-custodio/perl/ch-1.pl b/challenge-020/paulo-custodio/perl/ch-1.pl
new file mode 100644
index 0000000000..31dc97a57b
--- /dev/null
+++ b/challenge-020/paulo-custodio/perl/ch-1.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/env perl
+
+# Challenge 020
+#
+# 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;
+use 5.030;
+
+my $str = shift;
+
+my @segs;
+while ($str ne '') {
+ $str =~ s/^((.)\2*)//x or die;
+ push @segs, $1;
+}
+
+say join(", ", map {'"'.$_.'"'} @segs), ".";
diff --git a/challenge-020/paulo-custodio/perl/ch-2.pl b/challenge-020/paulo-custodio/perl/ch-2.pl
new file mode 100644
index 0000000000..e770678290
--- /dev/null
+++ b/challenge-020/paulo-custodio/perl/ch-2.pl
@@ -0,0 +1,51 @@
+#!/usr/bin/env perl
+
+# Challenge 020
+#
+# Task #2
+# Write a script to print the smallest pair of Amicable Numbers. For more
+# information, please checkout wikipedia page.
+
+use strict;
+use warnings;
+use 5.030;
+
+sub divisors {
+ my($n) = @_;
+ my(@div_low, @div_high);
+ for (my $i = 1; $i <= sqrt($n); $i++) {
+ if ($n%$i == 0) {
+ push @div_low, $i;
+ unshift @div_high, $n/$i if $n/$i != $i;
+ }
+ }
+ return (@div_low, @div_high);
+}
+
+sub proper_divisors {
+ my($n) = @_;
+ my @div = divisors($n);
+ return @div[0..$#div-1];
+}
+
+sub sum {
+ my $sum = 0;
+ $sum += $_ for @_;
+ return $sum;
+}
+
+sub amicable_pair_iter {
+ my $n = 1;
+ return sub {
+ while (1) {
+ $n++; # start at 2
+ my $sum = sum(proper_divisors($n));
+ if (sum(proper_divisors($sum))==$n && $n < $sum) {
+ return ($n, $sum);
+ }
+ }
+ };
+}
+
+my $iter = amicable_pair_iter();
+say "(", join(",", $iter->()), ")";
diff --git a/challenge-020/paulo-custodio/test.pl b/challenge-020/paulo-custodio/test.pl
new file mode 100644
index 0000000000..063c3b5b83
--- /dev/null
+++ b/challenge-020/paulo-custodio/test.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use 5.030;
+use Test::More;
+
+is capture("perl perl/ch-1.pl ABBCDEEF"), <<END;
+"A", "BB", "C", "D", "EE", "F".
+END
+
+is capture("perl perl/ch-2.pl"), "(220,284)\n";
+
+done_testing;
+
+
+sub capture {
+ my($cmd) = @_;
+ my $out = `$cmd`;
+ $out =~ s/[ \r\t]*\n/\n/g;
+ return $out;
+}