如何计算Prolog中列表中元素出现次数

时间:2012-05-27 19:50:33

标签: list count prolog

我是prolog的新手,为什么问题对你来说很容易,但我找不到答案。有人可以帮助我。

我只想要

计数功能s.t

count([c,c,a,a,b,b,d,a,c,b,d,d,a], O).

它将返回列表成员的出现次数。

 O = [[a, 4], [b, 3], [c, 3], [d, 3]]

2 个答案:

答案 0 :(得分:2)

以下内容基于我的previous answer至“Remove duplicates in list (Prolog)”和this previous answer上的问题“Prolog union for A U B U C”。

list_item_subtracted_count0_count/5源自list_item_subtracted/3list_counts/2源自list_setB/2defined 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).

以下是OP给出的查询:

?- 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

请注意X-N中对Counts的顺序与XXs的第一次出现相对应:

?- 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].

最后,让我们考虑所有可能的列表Es - 使用递增的长度进行公平枚举:

?- 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)
...

答案 1 :(得分:0)

co(X,L) :- co(X,[],L).

co([],A,A).
co([X|Xs], A, L) :- p(X-Z,A,R), !, Z1 is Z+1, co(Xs, [X-Z1|R], L). 
co([X|Xs], A, L) :- co(Xs, [X-1|A], L). 

p(X-Y,[X-Y|R],R):- !.
p(X,[H|Y], [H|Z]) :- p(X,Y,Z).

我没有故意使用非常有意义的名字。试着理解每个谓词的作用。