
metadata
I have 6 varibiles
`
x1:int
x2:int
x3:int
x4:int
x5:int
x6:int
`
They can be set to any number really but for the sake of this example Ill give them some random ones.
`
x1:int = 4
x2:int = 2
x3:int = 3
x4:int = 6
x5:int = 5
x6:int = 3
`
These numbers represent chances of colours getting picked.
Red corresponds with x1
Orange corresponds with x2
Yellow corresponds with x3
Green corresponds with x4
Blue corresponds with x5
Purple corresponds with x6
So out of all the colours red for instance has a 4 in 23 chance of getting picked. (Because red is represented by x1 (4) and x1+x2+x3+x4+x5+x6 = 23, aka 4 in 23)
I’m going to create 6 new variables to represent these chances as a visual (this may not be necessary in your solution)
`
y1:int = 4/23
y2:int = 2/23
y3:int = 3/23
y4:int = 6/23
y5:int = 5/23
y6:int = 3/23
`
What I need is a way to randomly pick and output red,orange,yellow,green,blue, or purple based on their chances of getting picked (the x values.)
Any ideas?


metadata
iterate over the array,
sum the elements up,
if the sum is bigger than the random Number, pick the current element.
Yes, normalizing to make the sum 1 is a good idea, because that’s what probabilities are like.


metadata
Don’t use six variables, use an array or object:
`var probabilities:Object = { red:4, blue:5, ... };`
Then normalise it, call random(), and pick the element that matches, as 953 says.


metadata
What do you guys mean by “normalise?”
Also I don’t really understand what NineFiveThree is saying with
“if the sum is bigger than the random Number, pick the current element.”


metadata
Normalise is make sure it adds up to one, i.e. divide by the sum.


metadata
> *Originally posted by **[evan999333](/forums/4/topics/335572?page=1#posts7024981):***
>
> Also I don’t really understand what NineFiveThree is saying with
>
> “if the sum is bigger than the random Number, pick the current element.”He probably means that you'll want to make a loop that checks for something like this: [0] \> randomNumber, [0]+[1] \> randomNumber, [0]+[1]+[2] \> randomNumber, ...etc. Make a variable that keeps track of the sum of the previous array elements as you iterate through the loop, and check that sum against the random number, thus: if (sum \> randomNumber) break out of loop and return the current array index, because it corresponds with the selected color.


metadata
Ah that makes sense thank you everyone.
