问题
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
回答1:
You may use append/3 and subtract/3 to obtain the first sublist that contains all items:
findFirstSubListHavingAllColors( NumList, List ,SubList, Len):-
once((
append(SubList, _, List), % get SubList
subtract(NumList, SubList, []), % test whether NumList is contained in SubList
length(SubList, Len)
)).
once/1 here is to avoid getting other (wrong) solutions on backtracking.
回答2:
Here is another solution using aggegate_all/3
firstSubList(NumList, In, Out) :-
aggregate_all(max(E),(member(X, NumList), once(nth1(E, In, X))), Len),
length(Out, Len),
append(Out, _, In).
Once/1 is used because numbers may appears many times in the list !
来源:https://stackoverflow.com/questions/56116344/find-first-sublist-that-has-all-numbers-from-1-to-k