I want to generate random unique number. These are codes:
public int NewNumber(int r) {
int[] numbers = new int[r];
int a = Random.Range (0, r);
if(numbers.Contains(a)) {
a = Random.Range (0, r);
}
return a;
}
When the NewNumber(5) works ten times, I get result as like: 5,4,3,4,1,2,4,2,5,3
But what I want: 5,3,4,2,1
Where is wrong?
You are resetting your holder every time you call NewNumber method, you need to put your holder outside your method.
int[] numbers = new int[r];
public int NewNumber(int r) {
int a = Random.Range (0, r);
if(!numbers.Contains(a)) {
a = Random.Range (0, r);
}
return a;
}
It will be better if you use a list instead of array;
List<int> numbers = new List<int>();
public int NewNumber(int r) {
int a = Random.Range (0, r);
if(!numbers.Contains(a)) {
numbers.Add(a);
}
return a;
}
If there's only one number within the range that you don't want to be returned, the solution needs no array. Instead simply repeat creating a new random number if the random number happens to be the one you don't want.
public int RandomNumberInRangeExcluding(int range, int excludedNumber)
{
int r = excludedNumber;
while (r == excludedNumber)
{
r = Random.Range(0, range);
}
return r;
}
nexx is right but you're still going to get duplicates unless you wrap this in a loop, something like...
List<int> numbers = new List<int>();
public int NewNumber(int r) {
int a = 0;
while(a==0){
a = Random.Range (0, r);
if(!numbers.Contains(a)) {
numbers.Add(a);
}else{
a=0;
}
}
return a;
}
I think it's because you only random once when numbers
contains a
. Try changing if
to while
so the random continues until numbers
doesn't contain a
int[] numbers = new int[r];
public int NewNumber(int r) {
int a = Random.Range (0, r);
while(numbers.Contains(a)) { // change this to while
a = Random.Range (0, r);
}
return a;
}
this achieves the same result, without waiting for Random
to hopefully spit out whichever numbers are needed
static void Main(string[] args)
{
List<int> rands = GetRandoms(10);
}
static IEnumerable<int> GetRandoms(int size)
{
List<int> rands = new List<int>();
for (int i = 1; i <= size; i++)
{
rands.Add(i);
}
return rands.OrderBy(i => Guid.NewGuid());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.