Random Number Selection

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?

I guess I find a way:

  1. random number their indexes
  2. after choosing the index, shorten the array by one, and there will be another value on this index.

so the value inside the array won’t ever be the same.

That’ll work (and pretty much is the best way), just be sure your random number generator uses a new maximum value each time you shorten the array.

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.

What is this, Forum moderators, writing code?!?!???

:lol:

Thanks for the link – that’s a no brainer for the utilities library.

Hi Andee, I checked,
it returns me nothing

int[ ] Samples = RandFuncs.SampleRemove(pointsArray.Length-1, 3);

assuming pointsArray’s length is 8,

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

Thanks.