Here is some simple code to show my problem:
void method()
{
for(int i = 0;i<=99)
{
method1();
method2();
}
}
void method1()
{
if(Randombool())
{
bool exists = true;
int n;
while(exists)
{
n=RandNum(100);
exists = list1.Exists(num => num == n);
}
list1.add(n);
}
}
void method2()
{
int n;
bool exists = true;
bool exists2 = true;
while(!(exists && !exists2))
{
n = RandNum(100);
exists = list1.Exists(elem => elem == n);
exists2 = list2.Exists(elem => elem == n);
}
list2.add(n)
}
Well it’s obvious it will be stuck in the while loop from method2 for a long time.
Is there a more gentle method to generate numbers so I can avoid waiting?
It seems like you’re trying to generate a random sequence of N numbers. The approach you’re using here is to get a random number and then discard it if it is one you already have.
What you want to do is Shuffle an Array which can be done reasonably efficiently. Just populate the list with 0, 1, 2, … in order and then shuffle it.
Pseudocode copied from the above link: