How to resolve the algorithm Longest common substring step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Longest common substring step by step in the Raku programming language

Table of Contents

Problem Statement

Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Longest common substring step by step in the Raku programming language

Source code in the raku programming language

sub createSubstrings( Str $word --> Array ) {
   my $length = $word.chars ;
   my @substrings ;
   for (0..$length - 1) -> $start {
      for (1..$length - $start) -> $howmany {
	 @substrings.push( $word.substr( $start , $howmany ) ) ;
      }
   }
   return @substrings ;
}

sub findLongestCommon( Str $first , Str $second --> Str ) {
   my @substringsFirst  = createSubstrings( $first ) ;
   my @substringsSecond = createSubstrings( $second ) ;
   my $firstset  = set( @substringsFirst ) ;
   my $secondset = set( @substringsSecond ) ;
   my $common = $firstset (&) $secondset ;
   return $common.keys.sort({$^b.chars <=> $^a.chars})[0] ; # or: sort(-*.chars)[0]
}

sub MAIN( Str $first , Str $second ) {
   say "The longest common substring of $first and $second is " ~
   "{findLongestCommon( $first , $second ) } !" ;
}


sub substrings ($s)       { (flat (0..$_ X 1..$_).grep:{$_ ≥ [+] @_}).map: { $s.substr($^a, $^b) } given $s.chars }
sub infix:($s1, $s2) { ([∩] ($s1, $s2)».&substrings).keys.sort(*.chars).tail }

my $first  = 'thisisatest';
my $second = 'testing123testing';
say "The longest common substring between '$first' and '$second' is '{$first LCS $second}'.";


  

You may also check:How to resolve the algorithm FizzBuzz step by step in the Ioke programming language
You may also check:How to resolve the algorithm Singly-linked list/Element definition step by step in the JavaScript programming language
You may also check:How to resolve the algorithm A+B step by step in the Genie programming language
You may also check:How to resolve the algorithm Factors of an integer step by step in the PILOT programming language
You may also check:How to resolve the algorithm Convert decimal number to rational step by step in the Fortran programming language