john
john

Reputation: 41

How do I count the number of elements in a list?

I need to write a small Prolog program to count the number of occurrence of each element in a list.

numberOfRepetition(input, result)

For example:

numberOfRepetition([a,b,a,d,c,a,b], X)

can be satisfied with X=[a/3,b/2,d/1,c/1] because a occurs three times, b occurs 2 times and c and d one time.

Upvotes: 4

Views: 15064

Answers (3)

repeat
repeat

Reputation: 18726

Check out my answer to the related question "How to count number of element occurrences in a list in Prolog"! In that answer I present the predicate list_counts/2, which should fot your needs.

Sample use:

:- list_counts([a,b,a,d,c,a,b],Ys).
Ys = [a-3, b-2, d-1, c-1].

Note that that this predicate uses a slightly different representation for key-value pairs expressing multiplicity: principal functor (-)/2 instead of (/)/2.

If possible, switch to the representation using (-)/2 for better interoperability with standard library predicates (like keysort/2).

Upvotes: 1

ViseSystems
ViseSystems

Reputation: 36

If you wish to find element with max occurrences:

occurrences([],_,0).
occurrences([X|Y],X,N):- occurrences(Y,X,W),N is W + 1.
occurrences([X|Y],Z,N):- occurrences(Y,Z,N),X\=Z.

**make_list(Max):-
   findall((Num,Elem),occurrences([d,d,d,a,a,b,c,d,e],Elem,Num),L),
   sort(L,Sorted),
   last(Sorted,(_,Max)).**

Upvotes: -1

Ravan Scafi
Ravan Scafi

Reputation: 6392

I don't want to give you the answer, so I gonna help you with it:

% Find the occurrences of given element in list
%
% occurrences([a,b,c,a],a,X).
% -> X = 2.

occurrences([],_,0).
occurrences([X|Y],X,N):- occurrences(Y,X,W),N is W + 1.
occurrences([X|Y],Z,N):- occurrences(Y,Z,N),X\=Z.

Depending on your effort and feedback, I can help you to get your answer.

Upvotes: 4

Related Questions