Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ljepson
Created December 14, 2012 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljepson/4283524 to your computer and use it in GitHub Desktop.
Save ljepson/4283524 to your computer and use it in GitHub Desktop.
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