aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJaime <42359730+bracteatus@users.noreply.github.com>2019-07-26 23:51:27 -0600
committerJaime <42359730+bracteatus@users.noreply.github.com>2019-07-26 23:51:27 -0600
commit81caa1238297c1e7aba934168200c314265bd735 (patch)
tree232d27b5f4f2daff29232e36f49c64e473bd521a
parent7ec4eedfe14d441bdf41dce04f271ec9264314b7 (diff)
downloadperlweeklychallenge-club-81caa1238297c1e7aba934168200c314265bd735.tar.gz
perlweeklychallenge-club-81caa1238297c1e7aba934168200c314265bd735.tar.bz2
perlweeklychallenge-club-81caa1238297c1e7aba934168200c314265bd735.zip
Update ch-1.pl
Iterate ordered substrings to find largest common substring.
-rw-r--r--challenge-018/jaime/perl5/ch-1.pl24
1 files changed, 20 insertions, 4 deletions
diff --git a/challenge-018/jaime/perl5/ch-1.pl b/challenge-018/jaime/perl5/ch-1.pl
index b5cd68a3c6..ce9415e8c2 100644
--- a/challenge-018/jaime/perl5/ch-1.pl
+++ b/challenge-018/jaime/perl5/ch-1.pl
@@ -2,7 +2,23 @@
# # Challenge #1
#
# Write a script that takes 2 or more strings as command line parameters
-# and print the longest common substring. For example, the longest
-# common substring of the strings “ABABC”, “BABCA” and “ABCBA” is string
-# “ABC” of length 3. Other common substrings are “A”, “AB”, “B”, “BA”,
-# “BC” and “C”.
+# and print the longest common substring.
+
+sub of_size {
+ my ($n,$s) = @_;
+ my @subs = ();
+ for (my $i = 0; ($i+$n) <= length $s; $i++) {
+ push @subs, substr($s,$i,$n);
+ }
+ return @subs; #substrings of $s of length $n.
+}
+
+my $head = shift;
+for my $n (reverse 1..(length $head)) {
+ for my $s (of_size($n,$head)) {
+ if (@ARGV == grep(/$s/,@ARGV)) {
+ print "$s\n";
+ exit;
+ }
+ }
+}