Reputation: 6585
I've read a few posts that deal with higher probabilities and bell curves for selecting elements from an array of numbers, however I have an array of strings I want to choose from. I have a bunch of DIVs on my site that I want to randomly color from a set of 6 colors:
var colors = new Array('red', 'orange', 'yellow', 'green', 'blue', 'purple');
Let's say I really love the color red. How can I tweak the following code to grab a "random" element, but have 'red' be favored over the others? i.e., I want it to return 'red' most of the time.
$('.box').each(function() {
// Get a "random" color
var randomColor = colors[Math.floor(Math.random()*colors.length)];
$(this).css('background-color', randomColor);
});
I realize I could add 'red' a bunch of times to the array, but I'm trying to avoid this. Or is there a different approach altogether? Thanks!
Upvotes: 1
Views: 217
Reputation: 2216
You could create another array that is as long as the array full of colors and assign probabilities to them (i.e. the entire array has to add up to 1). From here generate a number between 1 and 0 and as you iterate over the array of probabilities subtract from it. Once it hits 0 then take that index and return the color that corresponds. I am not good with JavaScript but I will try.
var colors = new Array('red', 'orange', 'yellow', 'green', 'blue', 'purple');
var probabilities = new Array(0.5 , 0.1, 0.1, 0.1, 0.2);
var prob = Math.random()
var i=0;
for (i=0;i<probabilities.length && prob > 0;i++)
{
prob = prob - probabilities[i];
}
var color = colors[i];
I believe that should work.
Upvotes: 2
Reputation: 145388
Besides it is hard to say how much you love red, but here is one possible way:
var randomColor = colors[Math.random() > 0.5
? Math.floor(Math.random() * colors.length) : 0];
In this case red will be selected with the probability 0.5 over the other colours.
Upvotes: 1