'Longest sequence of even numbers in a list with prolog
I want to implement a predicate even_sequence(X,Y,Z) where X is the given list, Y is a counter of the max length of even numbers sequence, and Z is the counter that stores the length of the current even number subsequence. For example for the given list 2,4,6,3,5,2,2 i want to return 3 because 2,4,6 is the longest sequence.
Here is the code that i tried and i don't know how to make it work(i am a total beginner in Prolog).If i run even_sequence([2,2,2,3,3],C,R) i get the error: Arguments are not sufficiently instantiated In: [1] even_sequence([2,2|...],_1730,_1732)
even_sequence([],_,_).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =:= 0,
LocalMax1 is LocalMax+1,
even_sequence(T,GlobalMax,LocalMax1).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =\= 0,
GlobalMax1 is LocalMax,
LocalMax1 is LocalMax-LocalMax,
even_sequence(T,GlobalMax1,LocalMax1).
Solution 1:[1]
longest_even_sequence(Lst, EvenSeqLen) :-
% Keep running total of current sequence, and best-so-far
longest_even_sequence_(Lst, 0, 0, EvenSeqLen).
longest_even_sequence_([], Cur, Best, EvenSeqLen) :-
% Check final sequence, and assign EvenSeqLen
num_num_max(Cur, Best, EvenSeqLen).
longest_even_sequence_([H|T], Cur, Best, EvenSeqLen) :-
0 is H mod 2, !,
% Is even, so sequence gets longer
Cur1 is Cur + 1,
longest_even_sequence_(T, Cur1, Best, EvenSeqLen).
longest_even_sequence_([_H|T], Cur, Best, EvenSeqLen) :-
% Is odd (because not even), so check the finished sequence
num_num_max(Cur, Best, Best1),
% Starting new sequence
longest_even_sequence_(T, 0, Best1, EvenSeqLen).
% Convenient wrapper
num_num_max(X, Y, Max) :-
Max is max(X, Y).
Result in swi-prolog:
?- longest_even_sequence([2,4,6,3,5,2,2], N).
N = 3.
?- longest_even_sequence([1,2,3], N).
N = 1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | brebs |
