Percentage of Array Calcualtion

I’d like to determine the percentage of times that certain items appear in an array…

I can think of a complex way of doing this, where the Array tests against a Set and counts each element - but I’m wondering if there is a more straightforward way or maybe even a convenience method.


Probably using a Dictionary is an acceptable way to de-duplicate values? This is a pretty simple way to express this with dictionaries and should represent roughly the fastest algorithm for this?

~array = 100.collect { (0..9).choose };
~frequency = (); {
	~frequency[value] = (~frequency[value] ?? 0) + 1;
	|value, count|
	"%: %".format(value, 100 * count / ~array.size).postln 

Bag.countsDo gets things most of the way there.

Depending on how you want the results changes the function somewhat, but this seems to work reliably for me, compiling a 2D array, with [number, percentage of]:

a = 99.collect({ (14..28).choose });

b =; // only need this line if running this block repeatedly with new values each time
a.asBag.countsDo({ |item, count, index|
	b = b ++ [[item, (count / a.size) * 100]].postln;


E.g. with findAll

a = { rand(10) } ! 100;

a.findAll([0]).size / a.size * 100;