I need to find the first sublist having all numbers from 1 to K and return it and its length.
Sorry in advance for the bad editing
So I check if 1 to K is in sublist if not then I delete the element (Hd) from
NumList ,append it to our result(SubList) and recursively call the function
with the tail as our new List to check.
findFirstSubListHavingAllColors( NumList, [Hd|Tl] ,SubList, X):-
( oneToKinSub(SubList,NumList)
-> length(SubList,X)
; delete(NumList,Hd,NumList1),
append(SubList,[Hd],SubList1),
findFirstSubListHavingAllColors(NumList1,Tl,SubList1,_)
).
oneToKinSub(_,[]).
oneToKinSub(SubString,[Hd|Tl]) :-
member(Hd,SubString),
oneToKinSub(SubString,Tl).
For instance if
NumList =[1,2,3]
[Hd|Tl] =[1,3,1,3,1,3,3,2,2,1]
the expected result should be SubList=[1,3,1,3,1,3,3,2] and X= 8
You may use
append/3
andsubtract/3
to obtain the first sublist that contains all items:once/1
here is to avoid getting other (wrong) solutions on backtracking.Here is another solution using aggegate_all/3