Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Select a number at random based on the frequency that it randomly showed up.
Array.prototype.frequency = function() {
this.sort();
var i = 0, array, count, item, first = this.slice(0);
while(i < first.length) {
count = 1; item = first[i]; array = i + 1;
while(array < first.length && (array = first.indexOf(item, array)) !== -1) {
count += 1; first.splice(array,1);
}
first[i] += ' : '+ count; i++;
}
return first;
}
var random = [];
for (var i = 0; i < 1000; i++) random.push(Math.round(Math.random() * 10));
var frequency = random.frequency(), largest, largest_count = 0;
for(var n in frequency) {
var current = frequency[n];
if(typeof frequency[n] === 'string') var current_count = current.replace(/.*: /,'');
if(current_count - largest_count > 0) {
largest = current;
largest_count = current_count;
}
}
largest = largest.replace(/(\d*).*/,'$1').trim();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.