How to count the number of items in a list?

I need to write a small Prolog program to count the number of times each item appears in the list.

numberOfRepetition(input, result) 

For instance:

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

X=[a/3,b/2,d/1,c/1] can be executed, because a occurs three times, b occurs 2 times and c and d once.

+4
source share
3 answers

I do not want to give you an answer, so I will help you with this:

 % 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 efforts and feedback, I can help you get an answer.

+4
source

Pay attention to my answer to the corresponding question " How to count the number of entries in a list in Prolog "! In this answer, I present the predicate list_counts/2 , which should suit your needs.

Using an example:

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

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

If possible, switch to a view using (-)/2 for better compatibility with standard library predicates (e.g. keysort/2 ).

+1
source

If you want to find an element with maximum 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)).** 
-1
source

All Articles