0

I want to get 20 random numbers between 1 to 100, but the number should not repeated....

Updated: If I have 20 names in which any 5 to be selected at random one by one but the name came once not to be called again.....

Javed Akram
  • 15,024
  • 26
  • 81
  • 118

2 Answers2

7

Put the numbers in a list, and pick from the list:

List<int> numbers = Enumerable.Range(1, 100).ToList();

Random rnd = new Random();
List<int> picks = Enumerable.Range(1, 20).Select(n => {
  int index = rnd.Next(numbers.Count);
  int pick = numbers[index];
  numbers.RemoveAt(index);
  return pick;
});

This is probably the simplest way to solve it, but it's not the most efficient. Removing items in a list involves moving the following items. With a bit more code you could avoid that move, but for most purposes the code is good enough as it is.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
5

I asked this a year or so ago.

Unique Random Numbers

The selected answer is brilliant, I thought.

Community
  • 1
  • 1
dicroce
  • 45,396
  • 28
  • 101
  • 140