Re: Count lists elements



This seems like quite an ugly solution, but I think it would work.
(its also bad code, with useless variable names etc.. sorry).


most_often(L,K):-
%add a list where the frequency of the elements can be
%stored (in the form [(elem,count),...] ).
most_often(L,[],K).


%base case - find the maximum of the counts
most_often([],Counts,Max):-
maxOcc(Counts,Max).

%update the count
most_often([L|Rest],O,K):-
member((L,C),O),!,
remove((L,C),O,NO),
NC is C + 1,
most_often(Rest,[(L,NC)|NO],K);

%or start a new one
most_often(Rest,[(L,1)|O],K).


%utility preds
member(X,[X|_]).

member(X,[_|Rest]):-member(X,Rest).

remove(_,[],[]).

remove(I,[I|L],R):-!,
remove(I,L,R).

remove(I,[Keep|L],[Keep|R]):-
remove(I,L,R).


%find the element with the highest count
maxOcc([],_):-!,fail. %empty list has no max

maxOcc(Occ,Max):-
% add max so far
maxOcc(Occ,(_,0),Max).

%base case - the soFar will be max
maxOcc([],(Var,_),Var).

%new max found
maxOcc([(Var,Count)|Rest],(_,Count1),Max):-
Count > Count1,!,
maxOcc(Rest,(Var,Count),Max).

%keep on looking
maxOcc([_|Rest],MaxSoFar,Max):-
maxOcc(Rest,MaxSoFar,Max).




I'm sure there will be a better way to do this.. Hope you find it.

Ben.


On Nov 15, 11:09 pm, Rapo...@xxxxxxxxx wrote:
Hi all,
I have a problem, I need to write a program, which finds the element in
a list which repeats most often time. Lets say, I have such query:
?- most_often([a,b,c,a,v,s,a,b,t,a], K).
K = a.

I tried several ways, but no luck... Can anybody help me?

.