< Back to IRCAM Forum

Finding the most recurring element of a list

Hello,

this is so simple and stupid I am almost embarrassed to ask. But not enough for not asking in the end. :slight_smile:

I was wondering if there is a way to pick the most frequent element from within a list without getting into omloop/counter/recursion/etc. What I mean is the following:

( a b b c d b b b b e) -> b

(1 2 3 2 4 4 4 4 2 3 4) -> 4

I have been scanning through the libraries, but couldn’t find something working properly. So here I am asking for help… if omloop is the way to go a hint would be appreciated. The issue is that I am planning on using this feature in a batch for getting the most frequent quantized f0s from a series of analyses, which means I do not know how many f0 I will get from each analysis itself. Hope this makes sense!

Thanks,
Gab

Hello Gab,

This Lisp method should do the trick, maybe there is a shorter way to do this but it seems to work.
What it does is removing duplicates, build a list with 0s to count elements, loop on the original list and increment counters.
The value/symbol with the highest counter is returned.

(defmethod! most-common ((self list))
(let* ((clean-list (remove-duplicates self))
(count-list (loop for i in clean-list collect 0)))
(loop for value in list do
(incf (nth (position value clean-list :test 'eq) count-list)))
(nth (position (reduce #'max count-list) count-list :test '=) clean-list)))

I joined it in a lisp file so you can load it into OM and use it in a patch.

Cheers,

Dimitri.

most-common-element.lisp (346 Bytes)

Thank you Dimitri,

under another suggestions, I ended up doing something similar (I believe…) with the OM objects (objects count, remove-dup, and mapcar). I am sharing it just in case it’s useful to anyone for future reference…

Thanks again,

Gab

Screen-Shot-2014-03-17-at-11.30.09-AM.png