0

I have been searching for an answers to my problem but I can't find any solutions. I writing a program where the user enter name, last name, and social number for five students. When that's done a random number will get handed to each of the five students the user has typed in. But the problem is that two students can not have the same random number. I know with 1-10000 the chances is low, but this is my task.

This is my code where I have tried to fix the problem but I can't get it to work.

while (antal != ggr)
{
    string name = Interaction.InputBox("Write name: ");
    string lastname = Interaction.InputBox("Write last name: ");
    string socialnr = Interaction.InputBox("Write social number: ");
    while (a != false)
    {
        foreach (int item in uniqNum)
        {
            if (item == _rnd)
            {
                a = true;
            }
            else
            {
                _rnd = rnd.Next(1, 10000);
                uniqNum.Add(_rnd);
                a = false;
            }
        }

    }

    ggr++;
    _Studens.Add(new student(name, lastname, socialnr, _rnd));
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
user3356636
  • 115
  • 1
  • 11

3 Answers3

2

Generate a list containing all the random numbers you wish to pick from. Then, choose an index randomly from that list, add the resultant number to a separate list, and remove the indexed element from the list of all numbers.

This will work for smaller ranges of numbers. If you wanted a unique random number in larger ranges, this method is probably not appropriate. In that case, consider generating GUIDs and converting them to their 128-bit numeric representation.

var allNumbers = Enumerable.Range(1, 10000).ToList();
var randomNumbers = new List<int>();
var random = new Random();
const int studentCount = 5;

for (int i = 0; i < studentCount; i++)
{
    int randomIndex = random.Next(0, allNumbers.Count);

    randomNumbers.Add(allNumbers[randomIndex]);
    allNumbers.RemoveAt(randomIndex);
}
NathanAldenSr
  • 7,841
  • 4
  • 40
  • 51
1

What about if you generate the number first, then use the Contains() method to check if the number already exists? If it does, generate the number again. Something like this:

int number = 0;
List<int> numberArray = new List<int>();
while (true)
{
    Random r = new Random();
    number = r.Next(1, 1000);
    if (!numberArray.Contains(number))
    {
        break;
    }
}
David Fenko
  • 131
  • 2
  • 8
0
Random r = new Random();
Enumerable.Range(1,10000).OrderBy(n => r.Next()).Take(5);
Lorentz Vedeler
  • 5,101
  • 2
  • 29
  • 40
  • Ingenious! The one issue with this is it requires an ordering of the entire list of numbers and generation of a random number for each number in the list. That's a lot more work than is necessary. I didn't downvote you, BTW. :) – NathanAldenSr Mar 27 '14 at 18:08