Re: Count lists elements



On 2006-11-16, Carlo Capelli <carlo.capelli@xxxxxxxx> wrote:
a solution using more idiomatic Prolog:

most_often(L,M) :-
retractall(count(_,_)),
forall(member(X,L),(
(retract(count(X,N)) -> N1 is N+1 ; N1 = 1 ),
assert(count(X,N1))
)
),
findall(K/C, count(K,C), [H|T]),
findmax(H,T,M/_).

findmax(H,[],H).
findmax(K/Nk,[X/Nx|T],R) :-
Nk > Nx ->
findmax(K/Nk,T,R) ;
findmax(X/Nx,T,R).

Retract??? I guess the most simple and efficient approach is to first
sort and than count the same elements, maintaining the one you found
most often. Plain and simple. Sorting without removing duplicates is
provided by msort/2 in some Prolog environments. Check the manual
otherwise.

<Rapolas@xxxxxxxxx> ha scritto nel messaggio
news:1163632144.097642.125230@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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?

It would be more convincing if you showed some of the work.

--- Jan
.