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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Longest common substring step by step in the Prolog 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 Prolog programming language

Source code in the prolog programming language

common_sublist(A, B, M) :-
	append(_, Ma, A), 
	append(M, _, Ma),
	append(_, Mb, B),
	append(M, _, Mb).	

longest_list([], L, _, L).
longest_list([L|Ls], LongestList, LongestLength, Result) :-	
	length(L, Len),
	Len >= LongestLength -> longest_list(Ls, L, Len, Result)
	; longest_list(Ls, LongestList, LongestLength, Result).
	
longest_substring(A, B, Result) :-
	string_chars(A, AChars),
	string_chars(B, BChars),
	findall(SubString, (
		dif(SubString, []), common_sublist(AChars, BChars, SubString)
	), AllSubstrings),
	longest_list(AllSubstrings, [], 0, LongestSubString),
	string_chars(Result, LongestSubString).


  

You may also check:How to resolve the algorithm Averages/Pythagorean means step by step in the Amazing Hopper programming language
You may also check:How to resolve the algorithm ABC problem step by step in the Racket programming language
You may also check:How to resolve the algorithm N-queens problem step by step in the D programming language
You may also check:How to resolve the algorithm Compile-time calculation step by step in the Rust programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the PHP programming language