Search code examples
answer-set-programmingclingo

How to obtain count of repeated values in predicate?


I am trying to obtain the count of equal scores obtained by some player. For example, if I have score(p1, 1), score(p2, 1), score(p3, 2), I would like to obtain a new predicate occurences(Score, Count) with result(1,2) and result(2,1), since a score of 1 was obtained two times, and score 2 only once.

I have tried counting the number of occurences with the following program:

getScore(S) :- score(P,S).

occurences(S,L) :- L = #count{Sc : score(P,Sc)}, getScore(S).

However, the values obtained are not correct: occurences(1,2), occurences(2,2). Score 2 should only have one count, as mentioned above.


Solution

  • You could think of your question this way: how many players got that score? Then count those players #count{Player : score(Player, S)}:

    occurences(S, L) :- L = #count{P : score(P, S)}, score(_, S).