How to resolve the algorithm Non-continuous subsequences step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Non-continuous subsequences step by step in the Prolog programming language

Table of Contents

Problem Statement

Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.

Task: Find all non-continuous subsequences for a given sequence.

For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:

There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Non-continuous subsequences step by step in the Prolog programming language

Source code in the prolog programming language

% fetch all the subsequences
ncsubs(L, LNCSL) :-
	setof(NCSL, one_ncsubs(L, NCSL), LNCSL).

% how to build one subsequence
one_ncsubs(L, NCSL) :-
	extract_elem(L, NCSL);
	(   sublist(L, L1),
	    one_ncsubs(L1, NCSL)).

% extract one element of the list
% this element is neither the first nor the last.
extract_elem(L, NCSL) :-
	length(L, Len),
	Len1 is Len - 2,
	between(1, Len1, I),
	nth0(I, L, Elem),
	select(Elem, L, NCS1),
	(   NCSL = NCS1; extract_elem(NCS1, NCSL)).

% extract the first or the last element of the list
sublist(L, SL) :-
	(L = [_|SL];
	reverse(L, [_|SL1]),
	reverse(SL1, SL)).


?- ncsubs([a,e,i,o,u], L).
L = [[a,e,i,u],[a,e,o],[a,e,o,u],[a,e,u],[a,i],[a,i,o],[a,i,o,u],[a,i,u],[a,o],[a,o,u],[a,u],[e,i,u],[e,o],[e,o,u],[e,u],[i,u]]


  

You may also check:How to resolve the algorithm File input/output step by step in the Erlang programming language
You may also check:How to resolve the algorithm String comparison step by step in the Fortran programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the Nim programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Read a file line by line step by step in the Vedit macro language programming language