I'm a beginner in Prolog and this is my question:
I have a sorted list of integers without duplicates i.e. [1,2,3,11,12,13,14,21,22,23,24,25]
I want to write a predicate that finds the longest contiguous sublist of the elements of the list, that is the longest list where each integer is followed by its subsequent integer (in the set of natural numbers).
In the above example this list would be [21,22,23,24,25]
where length = 5
.
In case there are more than one lists with the same maximum length, I'm interested in just one of them, no matter which.
It should work like this:
maxCont([1,2,3,11,12,13,14,21,22,23,24,25],Lst]).
Lst = [21,22,23,24,25].
First, we define
z_nonsucc_t/3
based on clpfd andbool01_t/2
:To split an integer list into consecutive runs, we use
splitlistIfAdj/3
like this:Next, we define meta-predicate
max_of_by/3
based onif_/3
,(#>)/3
, and(#>=)/3
:To get the longest list(s), we use meta-predicate
max_of_by/3
withlength/2
like so:Note that
max_of_by/3
may succeed more than once in tie cases:Put it all together in predicate
maxCont/2
:Sample queries: