List containing indexes of equal elements - list

I'm trying to define a predicate that takes 3 lists as parameters and the third list contains the indexes where the elements in the other two lists are the same.
This is my attempt at solving the problem.
sameIndex(List1, List2, List3) :- findIndex(List1,List2,0, List3).
% Helper Function
% Base cases
findIndex([],_,_,[]).
findIndex(_,[],_,[]).
findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
Head1 == Head2, append([Count], List4, FinalList), NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount,FinalList); NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount, List4).
Sample test case:
sameIndex([1,2,3,4], [6,2,4,4], List)
should return
List = [1,3]
My logic is : if the heads of the lists are equal then append Count (keeps track of the index we're at) to our empty List4, increment Count, and recursively call the predicate with the tails of the two lists. Otherwise, increment Count and recursively call the predicate with the tails.
I'm assuming my code has improper use of arithmetic in prolog but I just can't get it to work. Any suggestions/help is appreciated.

Here is your code corrected - and reformatted, using 'standard' indentation
findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
( Head1 == Head2,
append([Count], FinalList, List4),
NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount,FinalList)
; NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount, List4)
).
Your error was to invert the arguments to append/3.
Another problem it's returning multiple solutions - some of them wrong, so you should use the if/then/else construct, and discriminate the 2 base cases:
findIndex([],_,_,[]) :- !.
findIndex(_,[],_,[]).
findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
( Head1 == Head2
->append([Count], FinalList, List4),
NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount,FinalList)
; NewCount is Count+1,
findIndex(Tail1,Tail2,NewCount, List4)
).
But the code can be far simpler, using some library helpers:
sameIndex(List1, List2, List3) :-
findall(P, (nth0(P,List1,E), nth0(P,List2,E)), List3).
Differently from your solution, this one will work for any length lists...

Related

Prolog list within list

I have some trouble when im trying to create a list with multiple sublists. I fail to see why my code is not working as expected.
solves(_, _, 0, _).
solves(Length, List, Stopcond, NList):- length(NL, Length),
append([NL], List, NList),
write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2).
?- solves(3, [], 3, B).
I want B to be a list with three sublists, each with three intern variables.
When I write Nlist, it shows:
1. [[_G3207,_G3210,_G3213]]
2. [[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
3. [[_G3237,_G3240,_G3243],[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
4. B = [[_G3207, _G3210, _G3213]] .
But I don't understand why B becomes only the last element of the list. I want it to be the list on line 3. Can anyone see why and what i'm doing wrong? I'm pretty new to prolog.
I think this is what you intended
solves(_, List, 0, List).
solves(Length, List, Stopcond, NList2):- length(NL, Length),
append([NL], List, NList),
%write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2).
What does your predicate try to do ( Ignoring the 3 element sublists for now )?
It appends a list of length Stopcond to the 2nd argument passed (List).
How do you recursively construct a list of length TL Given a list of length L?
You append a list of Length L with a list of Length 1 and try to construct a list of length TL-1 from our new list of length L+1.
As a base case, You know that to construct a list of length TL from a list of length TL, you just need to return the list as is.
Your predicate returns a bigger-list consisting of Stopcond smaller-lists of length Length each.
Recursively, A bigger-list of length Stopcond is a smaller-list of Length elements appended to a bigger-list of length Stopcond-1.
Base case: A bigger-list of size 0 is simply an empty list.
If we were just to consider 0's instead of the 3 element sublists,
solves(FinalList, 0, FinalList). % The result of appending a list of length 0 to the given list is the given list itself.
solves(List, StopCond, FinalList):- % Appends A list of length StopCond to List
Length1List = [0], % Create a list of length 1
append( Length1List, List, LengthPlus1List),
N is N-1,
solves( LengthPlus1List, N, FinalList).
Since you're new, It might help to write english comments against each line.
% Base case: stopping condition satisfied. List is the final List we need
solves(_, List, 0, List).
% Recursive case: We need to make one more list of length L and append/prepend it to List
solves(Length, List, Stopcond, NList2):-
length(NL, Length), % Create smaller-list of length Length
append([NL], List, NList), % Append it to the list we're building up
%write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2). % Build Stopcond-1 more lists

Trouble with finding length of list in Prolog

I'm having trouble finding the length of a list. I know how to deal with lists such as say [a,b,c,d] or [a,b,[],d] or even [a,[[[]]],c,[]] each of which have a length of 4. The problem I'm having is trying to figure out the length of the list in a case like this [a,[b,c],d]. There are 4 elements, but when I run my code, it'll print 3. It considers the inner list [b,c] as a single element and I'm not sure how to count those separately.
Here's what I have:
% this is the base case
mylen([],0).
% case where element is a single atom like a or []
mylen([_|T],Len) :- atom(_),Len is Len1+1.
% case that *should* deal with sublists [b,c]
mylen([[_|TH]|T],Len) :- mylen(TH,Len1), Len is Len1+1.
% general case
mylen([_|T],Len):- mylen(T,Len1),Len is Len1+1.
I hope my question is clear. Thank you!
Ps. I looked at other posts concerning this, but couldn't find any solutions to this specific problem.
Your problem comes from the fact that you need to treat the head of the list in a special way when it is a non-empty list. So for example:
strangelen([], 0).
strangelen([H|T], Len) :-
( H = [_|_] % head is a non-empty list
-> strangelen(H, LenH)
; LenH = 1
),
strangelen(T, LenT),
Len is LenH + LenT.
And then:
?- strangelen([a,b,c,d], Len).
Len = 4.
?- strangelen([a,b,[],d], Len).
Len = 4.
?- strangelen([a,[[[]]],c,[]], Len).
Len = 4.
?- strangelen([a,[b,c],d], Len).
Len = 4.
?- strangelen([[]], Len).
Len = 1.
?- strangelen([[[b,c]]], Len).
Len = 2.
This solution does not work for a first argument that is not a proper list (try ?- strangelen(List, Len).)
?- atom(_).
false.
Then the second clause it's useless, will always fail. You should not ignore the 'shape' of the list' head, since it could be a list. This problem also appears in the third clause.

Prolog List Predicates

I need some help with three prolog predicates for checking and manipulating lists. I'm new to prolog and any help would be much appreciated.
The three predicates are:
double_up(+List1, -List2) is true when List2 has each element of List1 twice. The query double_up([a,b,c],X) should give X=[a,a,b,b,c,c]. The order of the elements in the output list does not matter.
pivot(+List1, +Pivot, -Smaller, -GreaterEq) is true when Smaller is the list of numbers in List1 smaller than Pivot, and GreaterEq is the list of numbers in List1 bigger than or equal to Pivot.
fancy_replace(+List, +Takeout,+Putin, -NewList, -Count) is true when NewList is the same list as the input List, but where each Takeout element in the list is replaced with the Putin element. Count should be the number of Takeouts that got replaced. For example, the query fancy_replace([9,10,1,9,2],9,0, X, C) should give X = [0,10,1,0,2] and C = 2. The order of the elements in the output list does not matter.
The simpler pattern to process lists in Prolog imposes a recursive predicate with 2 arguments, matching - conventionally - input and output data, and a base case, stopping the recursion, matching the empty list. Then
double_up([X|Xs], [X,X|Ys]) :- double_up(Xs, Ys).
double_up([], []).
This predicate it's a bit more general than what's required, because it works also in mode double_up(-List1, +List2). For instance
?- double_up(L,[1,1,2,2]).
L = [1, 2].
To restrict its mode as required, I think it's necessary to uselessly complicate the code, moving that clean loop in a service predicate, and leaving double_up just to test the arguments:
double_up(I, O) :- is_list(I), var(O), double_up_(I, O).
double_up_([X|Xs], [X,X|Ys]) :- double_up_(Xs, Ys).
double_up_([], []).
pivot/4 could be 'one-liner' in SWI-Prolog:
pivot(List1, Pivot, Smaller, GreaterEq) :-
partition(>(Pivot), List1, Smaller, GreaterEq).
like partition, foldl from library(apply) it's an easy inplementation of the last required predicate:
fancy_replace(List, Takeout, Putin, NewList, Count) :-
foldl(swap_n_count(Takeout, Putin), List, NewList, 0, Count).
swap_n_count(Takeout, Putin, L, N, C0, C) :-
( L == Takeout
-> N = Putin, C is C0 + 1
; N = L, C = C0
).
to be honest, i hate prolog... even though it is fun and easy after you learn it
i think this is a good reference as I was having trouble understanding how prolog works couple weeks ago.
what does the follow prolog codes do?
anyway.. this is the answer for your first problem; Hopefully you could solve the rest yourself :D
double([]).
double([H|[]], [H,H|[]]).
double([H|T],[H,H|T1]):- double(T, T1).
btw, this might not the only solution...but it works

How do I remove supersets in a list of lists?

Let's say I have the following list:
List = [[a],[a,b],[a,c],[b,c],[b,d],[a,b,c],[a,b,d],[b,c,e],[b,d,e,f]]
The goal is to remove every list in the list that is a superset of a list in the list.
The list that contains the lists always has the following properties:
The lists in the list are sorted by length
Each list in the list is sorted
My initial idea was to simply start with the first list in the list and go through all other lists and remove the lists that are a superset. Next I'd look at the second list, et cetera.
After removing all supersets of the list [a] it should look like this:
List = [[a],[b,c],[b,d],[b,c,e],[b,d,e,f]]
Next the supersets of [b,c] should be removed:
List = [[a],[b,c],[b,d],[b,d,e,f]]
Last is the supersets of [b,d]:
List = [[a],[b,c],[b,d]]
And the line above should be the result.
I already made a predicate akin to the member predicate, but instead of taking a single element and comparing it to the list, this takes an entire list and compares it to the list:
memberList([],_).
memberList([X|Xs],Y) :-
member(X,Y),
memberList(Xs,Y).
This only works with lists.
?- memberList(a,[a,b,c]).
false.
?- memberList([a],[a,b,c]).
true .
?- memberList([a,b],[a,b,c]).
true .
But after this I'm a bit lost.
I tried the following which should remove the supersets of a single set, but it did not work:
removeSupersetsList(_,[],[]).
removeSupersetsList(X,[Y|Ys],[Y|Out]) :-
not(memberList(X,Y)),
removeSupersetsList(X,Ys,Out).
removeSupersetsList(X,[Y|Ys],Out) :-
memberList(X,Y),
removeSupersetsList(X,Ys,Out).
So I was wondering if someone could point me in the right direction to remove all supersets from a list or maybe even give the right predicate.
I'm using SWI-Prolog, where I find a crafted libray for ordered sets, and the required test, then using select/3 it's really easy to sanitize the list
rem_super_sets([], []).
rem_super_sets([L|Ls], R) :-
( select(T, Ls, L1), % get any T in Ls
ord_subset(L, T) % is T a superset of L ?
-> rem_super_sets([L|L1], R) % discard T, keep L for further tests
; R = [L|L2],
rem_super_sets(Ls, L2)
).
here a verification and the result
test :-
List = [[a],[a,b],[a,c],[b,c],[b,d],[a,b,c],[a,b,d],[b,c,e],[b,d,e,f]],
rem_super_sets(List, R),
write(R).
?- test.
[[a],[b,c],[b,d]]
true.
memberList([],_).
memberList([X|Xs],Y) :- member(X,Y),
memberList(Xs,Y).
%remove(ToRemove,ListWithSublists,LocRez,FinalRez)
%A list from ListWithSublists is removed,depending on ToRemove
% LocRez is accumulator used to obtain the FinalRez ( at the end )
remove(_,[],LocRez,LocRez) :- !.
remove(ToRemove,ListWithSublists,LocRez,FinalRez) :- ListWithSublists=[Sublist|Rest],
memberList(ToRemove,Sublist),
remove(ToRemove,Rest,LocRez,FinalRez),!.
remove(ToRemove,ListWithSublists,LocRez,FinalRez) :- ListWithSublists=[Sublist|Rest],
not(memberList(ToRemove,Sublist)),
append(LocRez,[Sublist],LocRezNew),
remove(ToRemove,Rest,LocRezNew,FinalRez),!.
> removeSupersetsList(List,Rez) :- removeSupersetsList(List,[],Rez). % call this for testing
%removeSupersetsList(List,LocRez,Final)
%remove the Head from List from the List itself if needed(obtain Rez in the process)
%append the Head into our LocRez(get LocRezNew),
%call this recursively for the Rez
removeSupersetsList(List,LocRez,LocRez) :- List=[] ,!.
removeSupersetsList(List,LocRez,Final) :- ( List=[ToRemove|_] ; List=[ToRemove] ),
remove(ToRemove,List,[],Rez),
append(LocRez,[ToRemove],LocRezNew),
removeSupersetsList(Rez,LocRezNew,Final),!.

managing lists in prolog

Im new to Prolog and was looking for some assistance. What i am trying to do is basically get a list L consisting of elements that repeat at least twice in a given list L'
Example
L'=[1,2,1,3,4,3,2] => L=[1,2,3].
So far I am able to compute the occurrence of every consecutive variables
% pack(L1,L2) :- the list L2 is obtained from the list L1 by packing
% repeated occurrences of elements into separate sublists.
% (list,list) (+,?)
pack([],[]).
pack([X|Xs],[Z|Zs]) :- transfer(X,Xs,Ys,Z), pack(Ys,Zs).
% transfer(X,Xs,Ys,Z) Ys is the list that remains from the list Xs
% when all leading copies of X are removed and transfered to Z
transfer(X,[],[],[X]).
transfer(X,[Y|Ys],[Y|Ys],[X]) :- X \= Y.
transfer(X,[X|Xs],Ys,[X|Zs]) :- transfer(X,Xs,Ys,Zs).
% encode(L1,L2) :- the list L2 is obtained from the list L1 by run-length
% encoding. Consecutive duplicates of elements are encoded as terms [N,E],
% where N is the number of duplicates of the element E.
% (list,list) (+,?)
encode(L1,L2) :- pack(L1,L), transform(L,L2).
transform([],[]).
transform([[X|Xs]|Ys],[[N,X]|Zs]) :- length([X|Xs],N), transform(Ys,Zs).
which will return the following list of touples
?- encode([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
X = [[4,a],[1,b],[2,c],[2,a],[1,d][4,e]]
But there still remains the problem of building a list that will contain distinct elements that repeat at least twice.
If anyone can help me or point me in the general direction that would be great.
Thanks in advance
an element E of list L should:
be a member of list L',
be a member of list L'' where L'' is list L' if we remove element E.
check select/3, member/2, findall/3 and/or setof/3
You could write a procedure:
% E it's the list of are elements from L that repeat at least twice
elements_that_repeat_at_least_twice(L, E) :-
elements_that_repeat_at_least_twice(L, [], E).
elements_that_repeat_at_least_twice([H|Ls], Dupl, E) :-
...
In elements_that_repeat_at_least_twice the added list Dupl will keep each element you verify it's present multiple times. Examine each element of L, using [H|Ls].
Use memberchk/2 to verify if H is in L: then it's at least duplicate. If it's not yet in Dupl, add to it, and recurse. Remember to write the recursion base case (stop at empty list []).
Now I see you have added some code: then I complete suggestion:
elements_that_repeat_at_least_twice([], Dupl, Dupl).
elements_that_repeat_at_least_twice([H|Ls], Dupl, E) :-
( memberchk(H, Ls)
-> ( \+ memberchk(H, Dupl)
-> Dupl1 = [H|Dupl]
; Dupl1 = Dupl
)
; Dupl1 = Dupl
),
elements_that_repeat_at_least_twice(Ls, Dupl1, E).
Remember to reverse the list of duplicates when done.