- Home /
How do Ensure that a series of int's are never the same?
///7 random int values///
var r1 : int;
var r2 : int;
var r3 : int;
var r4 : int;
var r5 : int;
var r6 : int;
var r7 : int;
//randomize the numbers//
function Start(){
r1 = Random.Range(0, 51);
r2 = Random.Range(0, 51);
r3 = Random.Range(0, 51);
r4 = Random.Range(0, 51);
r5 = Random.Range(0, 51);
r6 = Random.Range(0, 51);
r7 = Random.Range(0, 51);
//It has to be 7 entirely different numbers between 0 and 51//
//PLEASE HALP ME//
}
none of these ints can ever be the same.. that would cause major breakage in the game.. please halp.
Answer by Kiwasi · Jul 12, 2014 at 12:43 AM
Two ways to do this.
For the simple case like yours you can simply check against each value to see it is unique. If it is not unique then randomize it until a unique value is returned.
The complex case is used with more numbers, or where checking the uniqueness is difficult or time consuming, or if you need to randomise the entire range. Typically you create the entire range of possibilities in a list. Then remove that item from the list once it is created, meaning it can never be selected again.
How do I check against it with an if statement in update? Or is there a special thing for this?
If you could psuedo do a short psuedo of option one. that would be spectaculous.. and I'll accept it then.
function Update(){
if(r1 == r2 || r1 == r3 || r1 == r4 || r1 == r5 || r1 == r6 || r1 == r7 || r2 == r3 || r2 == r4 || r2 == r5 || r2 == r6 || r2 == r7 || r3 == r4 || r3 == r5 || r3 == r6 || r3 == r7 || r4 == r5 || r4 == r6 || r4 == r7 || r5 == r6 || r5 == r7 || r6 == r7){
randomize again..
}
}
like this? lol
Psuedo code (c#)
// Arrays will make this far easier to do
int[] randomNumbers = new int [7]
void Start (){
for (int i = 0; i < randomNumbers.length; i++){
randomNumbers[i] = Random.Range(0, 51);
while (IsNotUnique(randomNumbers[i],i)){
randomNumbers[i] = Random.Range(0, 51);
}
}
}
private bool IsNotUnique (int number, int index){
for (int i = 0; i < randomNumbers.length; i++){
if (i != index){
if (number == randomNumbers[i]){
return true;
}
}
}
return false;
}
There are probably more efficient ways to code IsNotUnique, but you should get the picture.
Lol, just read your method. It will work. Until tomorrow night when you decide you need 8 ints ins$$anonymous$$d of 7. Arrays are the way to go here.
I agree thanks much your answer is just what I was looking for! The reason I was using var r1 so forth is because Im actually plugging those numbers into another array.. But I got something similar working now, and it's wondiferous.. ty again!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How can I Instantiate and do it in a random spot in a random spot? 2 Answers
Two different random numbers 2 Answers
Missing a Method? Random.Range? 1 Answer