15,942,847 members
See more:
Hello
I have a problem with random array. I need to have many randomize numbers but they have to be all dissimilar. If program generates 12, it must generate another number next time (not 12)!!!

I wrote this code:

C#
```List<int> rn = new List<int>();
Random r = new Random();
bool br = true;

for (int p = 0; p < 10; p++)
{
int i=0;
while (true)
{
i = r.Next(1, 11);
foreach (int a in rn)
{
if (a == i)
br = false;
}
if (br == true)
break;
}
}```

but after 4 or 5 numbers it is prolonging very bad.
Posted

## Solution 1

Hi,
I've written a tip and I think it can help.

How to generate many random various numbers?[^]

briefly:

C#
```//C#
public static int RandomNumber(ref List<int> numbers, Random random)
{
int count = numbers.Count;
int randomIndex = random.Next(0, count);
int returnedNumber = numbers[randomIndex];
numbers.RemoveAt(randomIndex);
return returnedNumber;
}```

It's requisite for using the method, to have a random variable and a list of numbers, for example:

```//C#
Random random = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i <= 1000; i++)
{
}
//Ok, For each using the method, there is a new and defferent random number:
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));

And I think you'll see a good performance.

JosephineBarry 13-Feb-11 5:06am
Thank you shahin
I did it and it works better than mine
thank you
Sandeep Mewara 13-Feb-11 5:58am
Shahin Khorshidnia 13-Feb-11 7:18am
Thank you guys

## Solution 2

You should set
`br=true;`
before the
`foreach (int a in rn)`
loop

Try this :

```for (int p = 0; p < 10; p++)
{
int i=0;
while (true)
{
i = r.Next(1, 11);
if (!rn.Contains(i))
{
break;
}
}
}```

Cheers

v2
JosephineBarry 13-Feb-11 5:02am
Yes. I did it and it became much better thank you. but it is still prolonging with big numbers. example 10000

List<int> rn = new List<int>();Random r = new Random();bool br = true;

for (int p = 0; p < 10000; p++){ int i=0; while (true) {

i = r.Next(1, 10001); br = true;foreach (int a in rn)

{ if (a == i) br = false; }

if (br == true) break; } rn.Add(i);}but thank you.
Estys 13-Feb-11 5:07am
If you mean by "prolongs" "it takes a long time", see my updated answer.
JosephineBarry 13-Feb-11 5:16am
thanks
but it still takes a long time with big numbers.
sorry. :rose:
Shahin Khorshidnia 13-Feb-11 8:19am
Vote 5
(perspicacity)