-4

I want to generate 10 'random' numbers, but they have to be unique. I have tried something, but is there someone who can help me out with something better?

My code:

List<int> ran = new List<int>();
Random rnd = new Random();
public static int randomValue;

int tempRandom;
public int randomNum()
{
    if(ran.Count == 0)
    {
        ran.Add(0);
        ran.Add(1);
        ran.Add(2);
        ran.Add(3);
        ran.Add(4);
        ran.Add(5);
        ran.Add(6);
        ran.Add(7);
    }
    tempRandom = rnd.Next(0, ran.Count);
    randomValue = ran[randomValue];
    ran.RemoveAt(tempRandom);

    return randomValue;
}
Natheem Yousuf
  • 143
  • 2
  • 2
  • 8
  • So you require 10 unique integers between 1 and 10? – Chris Pickford Jan 13 '17 at 10:10
  • 2
    This should help you: http://stackoverflow.com/questions/273313/randomize-a-listt – hellogoodnight Jan 13 '17 at 10:11
  • 10 unique integral numbers between 1 and 10... I am thinking of 10 possible numbers... – Camilo Terevinto Jan 13 '17 at 10:15
  • This question isn't about randomness.. –  Jan 13 '17 at 10:19
  • And who better than @RandomStranger to talk about randomness :) – Pikoh Jan 13 '17 at 10:21
  • Doesn't have anything to do about it. He's asking for a list of unique numbers. –  Jan 13 '17 at 10:22
  • @RandomStranger It was just a joke with your nick. Never mind :) – Pikoh Jan 13 '17 at 10:24
  • @RandomStranger if i can Add this 10 number to List or Generate 10 Unique Integers – Natheem Yousuf Jan 13 '17 at 11:05
  • there are plenty of ways. how do you mean better? and what is the purpose? please answer to these questions in your question. – Bizhan Jan 13 '17 at 11:29
  • You say you wish to "generate ten random numbers", but what you actually do is *shuffle the numbers from 0 to 7*. There are far better ways to shuffle a list than what you're doing here, and the question of how to shuffle efficiently has been asked probably dozens of times. I would delete this question and **do some research on efficient shuffle algorithms**. – Eric Lippert Jan 13 '17 at 11:57

2 Answers2

1

Is this what you're trying to say? If not, please specify how you mean further. This code should give you a number between 1-10 that hasn't been already used. This code will only work 10 times.

Random rnd = new Random();
List<int> usedNumbers = new List<int>();


public int RandomNum(){
    int number;
    do {
        number = rnd.Next(1, 10);
    } while(usedNumbers.IndexOf(number) == -1);

    usedNumbers.Add(number);

    return number;
}
Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32
0

Straight answer to your question (not regarding if you actually want what you are asking for):

Random.Range( int.MinValue, int.MaxValue );

This simply produces a random int in the range of all integers. For 10 numbers, the probability of duplicates is so little that every number will be unique.