I've been given the following question:
Any list of integers can (uniquely) be broken into "parity runs" where each run is a (maximal) sequence of consecutive even or odd numbers within the original list. For example, the list
List = [8,0,4,3,7,2,-1,9,9]
can be broken into [8, 0, 4]
, [3, 7]
, [2]
and [-1, 9, 9]
Write a predicate paruns(List, RunList)
that converts a list of numbers into the corresponding list of parity runs. For example:
?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]
Here was the code which I tried and it seems to work with the above sample case, thanks to one suggestion, but I've got an issue where when I run paruns([8,0,4], RunList).
it prints RunList = [[8,0,4],[]]
. Any suggestions would be appreciated :)
paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
even([Head | Tail], E, Last),
odd(Last, O, Last1),
paruns(Last1, S).
even([Head | Tail], [], [Head | Tail]) :-
Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
Head mod 2 =:= 0,
even(Tail, L, Last).
even([],[],[]).
odd([Head | Tail], [], [Head, Tail]) :-
Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
Head mod 2 =:= 1,
odd(Tail, L, Last).
odd([],[],[]).