Perl Weekly Challenge 018

back to index

A solution to the first task of the 18th Perl Weekly Challenge.

Challenge 018, Task #1

The Longest Common Substring Problem

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”. Please check this wiki page for details.

My Code

sub substrings($_, \len) {
    gather for 0 .. (.chars - len) -> \offset {
        take .substr(offset, len);
    }
}

sub MAIN(*@strings where .so) {
    for @strings>>.chars.min ... 1 -> \len {
        my @common-substrings = keys [∩] @strings>>.&substrings(len);
        if @common-substrings {
            .perl.put for @common-substrings.sort;
            last;
        }
    }
}
back to index