- Home /
control over the possibility of a Random.Range function from an array's elements
(I'm really sorry if the title is a mess, I can't put it simply in a few words)
I have a built-in Array, "myArray". Right now, I use this:
randomArrayElement = Random.Range (0,myArray.length);
to pick a random element from myArray. What I want is to increase the possibility of certain elements to be picked by this function.
Till now I've been doing it by inserting them more than once from within the editor (so the array has one instance of each element and say 5 instances of a certain element that I want to have randomly picked more frequently).
Is there a code-based way to do this? Thanks :)
Do you need a common curve such as bell curve or is it more arbitrary?
No not a bell/gaussian curve. It will have to be totally arbitrary, eg I have 10 elements in myArray and I want e.g. the 1st to be 50% possible to be "randomly" picked and all the others will equally share the rest 50%
Not exactly what you want, actually very close to what you are already doing: http://processing.org/discourse/yabb2/YaBB.pl?num=1260461297
Thanks a lot Peter, this was really helpful, could you put this in an answer so that I can accept it?
Answer by Meltdown · Feb 13, 2011 at 08:08 PM
Hi schwertfish,
You can do something like this in C#
Basically create a for loop, that runs 5 times, in each iteration, if the first element is returned, you break out of the for loop, if not the loop will try another 4 times to try and return the first element, else it will return another element. You can adjust the values of course to determine how often, and which element you would prefer to get out.
for(int i = 0; i < 5; i++) { randomArrayElement = Random.Range(0,5);
// If the first element (which is the preferred element is chosen), exit the loop if(randomArrayElement == 0) break; }
Or if you want multiple elements to be favoured, such as the 2nd and 4th element..
for(int i = 0; i < 5; i++) { randomArrayElement = Random.Range(0,5);
// If the preferred 2nd or 4th elements are chosen, exit the loop if(randomArrayElement == 1 || randomArrayElement == 3) break; }
Thanks $$anonymous$$eltdown, but I wasn't looking for something like this. I am using a built-in Array, which I can redefine anytime I want (I could for example redefine it through code and make it contain only the desired elements - 1 & 3 as you say), but I was wondering if there is a more "mathematical" way of making the Random.Range a bit biased.