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.

Thanks!

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 = ();
~array.do {
	|value|
	~frequency[value] = (~frequency[value] ?? 0) + 1;
};
~frequency.keysValuesDo({ 
	|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 = Array.new; // 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;
});
)

b.postln

E.g. with findAll

a = { rand(10) } ! 100;

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