How to count number of element occurrences in a list in Prolog
i m new in prolog that s why may be the question is easy for you but i couldnt find the answer. Can someone please help me.
I just want
a count function s.t
count([c,c,a,a,b,b,d,a,c,b,d,d,a], O).
it will returns the number of occurences of the list members.
O = [[a, 4], [b, 3], [c, 3], [d, 3]]
Solution 1:
The following is based on my previous answer to "Remove duplicates in list (Prolog)" and on this previous answer to the question "Prolog union for A U B U C".
list_item_subtracted_count0_count/5
is derived from list_item_subtracted/3
.
list_counts/2
is derived from list_setB/2
, which were both defined here.
list_item_subtracted_count0_count([], _, [], N,N). list_item_subtracted_count0_count([A|As], E, Bs1, N0,N) :- if_(A = E, ( Bs1 = Bs , N1 is N0+1 ), ( Bs1 = [A|Bs], N1 = N0 )), list_item_subtracted_count0_count(As, E, Bs, N1,N). list_counts([], []). list_counts([X|Xs], [X-N|Ys]) :- list_item_subtracted_count0_count(Xs, X, Xs0, 1,N), list_counts(Xs0, Ys).
Here's the query the OP gave:
?- list_counts([c,c,a,a,b,b,d,a,c,b,d,d,a], Xss).
Xss = [c-3,a-4,b-3,d-3]. % succeeds deterministically
Note the order of pairs X-N
in Counts
corresponds to the first occurrence of X
in Xs
:
?- list_counts([a,b,c,d], Xss). Xss = [a-1,b-1,c-1,d-1]. ?- list_counts([d,c,b,a], Xss). Xss = [d-1,c-1,b-1,a-1].
Last, let's consider all possible lists Es
—enumerated fairly with ascending lengths:
?- length(Es, N), list_counts(Es, Xss). N = 0, Es = [], Xss = [] ; N = 1, Es = [A], Xss = [A-1] ; N = 2, Es = [A,A], Xss = [A-2] ; N = 2, Es = [A,B], Xss = [A-1,B-1], dif(B,A) ; N = 3, Es = [A,A,A], Xss = [A-3] ; N = 3, Es = [A,A,B], Xss = [A-2,B-1], dif(B,A) ; N = 3, Es = [A,B,A], Xss = [A-2,B-1], dif(B,A) ; N = 3, Es = [B,A,A], Xss = [B-1,A-2], dif(A,B), dif(A,B) ; N = 3, Es = [A,B,C], Xss = [A-1,B-1,C-1], dif(C,A), dif(C,B), dif(B,A) ...