4

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
john
  • 41
  • 1
  • 1
  • 2
  • 5
    We don't just give answers. Take your best shot at it, post your code along with any error messages, and we'll help improve it. – Jacob Mattison Jun 15 '11 at 18:23

3 Answers3

4

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.

Ravan Scafi
  • 6,382
  • 2
  • 24
  • 32
1

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

Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
-1

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