1

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!

1
  • Apply the same principles to selecting from an array of numbers, but use the index rather than the value. Commented Feb 12, 2013 at 0:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Clever answer. I chose the other because I'm just needing to weight one element. Thank you though, this will likely come in handy in other applications.
Thanks, as you can tell it is rather platform agnostic and can weight arbitrarily and dynamically. Its not a bad algorithm to keep around.
1

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.

1 Comment

Sweet. I love red about 0.5 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.