I’d like something (a “target”) to show up five times in a random order (out of a total of 10 times).
The problem with the code below is I can get it to show up in a random order, but not necessarily five times:
function rand_float(min:Number,max:Number=NaN):Number {
if (isNaN(max)) { max = min; min=0; }
return Math.random()*(max-min)+min;
}
function rand_integer(min:Number,max:Number=NaN):int {
if (isNaN(max)) { max = min; min=0; }
return Math.floor(rand_float(min,max));
}
function rand_boolean(chance:Number=0.5):Boolean {
return (Math.random() < chance);
}
var a_list:Array = ['a','b','d','e'];
var target:String = 'b';
for (var i:int = 0; i < 10; i++) {
if (rand_boolean()) {
trace('random other thing: ' + a_list[rand_integer(0,3)]);
} else {
trace('target! :' + target);
}
}
Because the rand_boolean method is 50-50, it either “shows up” or “does not show” but there’s no guarantee it will always be 5 times out of 10.
I guess I could put in a counter and then limit it after 5 times (if it goes over) or force it to show up more (if say, after 8 times it has only shown up once) but is there perhaps a better way to go about doing this?
One simple solution: create a list of possibilities with the correct amount of the desired target.
Create a copy of it, remove each item as you pick them. Once you’ve pulled all 10, re-copy the list.
Alternatively, you can create this list by seeding it with 5 ‘b’s, selecting at random 5 ‘a’,’c’, or ‘d’, and then you have your list to select from randomly, if you don’t want the non-‘b’ counts to be consistent.
To generate the random item array:
And then in your random selection: