aboutsummaryrefslogtreecommitdiff
path: root/challenge-018
diff options
context:
space:
mode:
authorKian-Meng, Ang <kianmeng@cpan.org>2019-07-28 18:00:37 +0800
committerKian-Meng, Ang <kianmeng@cpan.org>2019-07-28 18:01:19 +0800
commitd201e39cab0f919b27bcc6408cd376f576e2d4fc (patch)
tree321367982d0527e0da496f6d3408910b9ed8070e /challenge-018
parentd20c0a014b2fb7524c0bb3254ee9cabeea1069be (diff)
downloadperlweeklychallenge-club-d201e39cab0f919b27bcc6408cd376f576e2d4fc.tar.gz
perlweeklychallenge-club-d201e39cab0f919b27bcc6408cd376f576e2d4fc.tar.bz2
perlweeklychallenge-club-d201e39cab0f919b27bcc6408cd376f576e2d4fc.zip
Add task #1 answer for challenge 018
Diffstat (limited to 'challenge-018')
-rw-r--r--challenge-018/kian-meng-ang/perl5/ch-1.pl39
1 files changed, 39 insertions, 0 deletions
diff --git a/challenge-018/kian-meng-ang/perl5/ch-1.pl b/challenge-018/kian-meng-ang/perl5/ch-1.pl
new file mode 100644
index 0000000000..01538d8109
--- /dev/null
+++ b/challenge-018/kian-meng-ang/perl5/ch-1.pl
@@ -0,0 +1,39 @@
+#!/usr/bin/env perl
+# vi:et:sw=4 ts=4 ft=perl
+
+use strict;
+use warnings;
+use utf8;
+use feature qw(say);
+
+# Naive and primitive approach.
+
+die 'Required at least two strings!' if @ARGV < 2;
+
+my %cnt = ();
+foreach my $str (@ARGV) {
+ my $len = length $str;
+ foreach my $l (1 .. $len) {
+ foreach my $o (0 .. $len - $l) {
+ $cnt{substr $str, $o, $l}++;
+ }
+ }
+}
+
+# See https://stackoverflow.com/a/4184957
+# See https://en.wikipedia.org/wiki/Schwartzian_transform
+my $longest = (
+ map { $_->[0] }
+ sort { $b->[1] <=> $a->[1] }
+ map { [ $_, length $_] }
+ grep { $cnt{$_} == scalar @ARGV } keys %cnt
+)[0];
+
+say $longest;
+
+1;
+
+__END__
+
+$ perl ch-1.pl ABABC BABCA ABCBA
+ABC