let’s say I have number from 1-8, I want to choose a random number between 1-8. That’s easy(done).
Now, let’s say I choose 6, so the rest number left are:
1,2,3,4,5,7,8, If I do random range again, it has chance of choosing 6 again, then I would need to write function recursivly to do random again, until I find a number still inside the current table.
Is there anyway to use random only from a selected table or something?
Sounds like you thought of a similar solution yourself, but was thinking you could keep an array, then just remove entries as you randomly select from it.
I wrote a quick script to test it :
private var candidates = new Array ();
var lowerRange : int = 1;
var upperRange : int = 8;
function Start () {
var i : int;
for (i=lowerRange; i<=upperRange; i++){
candidates.Add(i);
}
}
function FixedUpdate () {
if (candidates.length > 0){
var randomValue = Random.Range(0, candidates.length);
Debug.Log ("randomly chosen : " + candidates[randomValue]);
candidates.RemoveAt(randomValue);
} else {
Debug.Log ("Out of numbers");
}
}
You might want to have a look at this thread, which has a random picking and shuffling library attached. One of its functions, SampleRemove, does the kind of thing you are looking for efficiently.
shouldn’t it return me 3 numbers between 1-8?
After debug.log, I checked that Samples array length is 3, however, when I try to go through a loop and print out 3 numbers, it prints out al 0’s