1

Simply put, I want mylist to contain 7 unique numbers and I wrote the code below for that purpose.

However, it does not do the job and I get fewer unique numbers (mostly only 5 and sometimes 7) when deletion becomes necessary after I get a roll violating uniqueness.

Basically, I want a loop that keeps working and rolling random numbers within a specified range until a string of 7 unique numbers is observed. Of course, it should also put that desired string into a list.

class Program
{
    static void Main(string[] args)
    {

        Random number = new Random();

        List<int> mylist = new List<int>();
        int i = mylist.Count;


        while(i<7)
        {
            int selected = number.Next(50);

            if (mylist.Contains(selected))
            { mylist.Remove(selected); }
            else
            {
                mylist.Add(selected);
            }

            i++;
        }

        Console.WriteLine("Amount:"+ mylist.Count);

        foreach (int item in mylist)
        {
            Console.WriteLine(item);
        }

        Console.ReadKey();
Larx
  • 101
  • 7
  • You should be checking the loop with `while (mylist.Count < 7) instead of `i`. – Ron Beyer Apr 04 '18 at 03:31
  • @RonBeyer it actually worked.. But, I do not understand.. i IS mylist.Count ? Clearly, there is something that I still don't see. – Larx Apr 04 '18 at 03:33
  • `i` is only equal to `mylist.Count` the first time you assign it. When you remove an item from the list, you increment `i`. If you want to keep it in sync, you should be subtracting one from it when you remove, and only adding to it when you add to the list. – Ron Beyer Apr 04 '18 at 03:36

2 Answers2

1

There is no need to remove items from the list. Simply don't add duplicate values. Then you can simplify this to something like:

Random number = new Random();
List<int> mylist = new List<int>();

while (mylist.Count < 7)
{
    int selected = number.Next(50);

    if (!mylist.Contains(selected))
    {
        mylist.Add(selected);
    }
}
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • I think "if (!mylist.Contains(selected)" translates into if my list does not contain 'selected'. I did not know I could do that - very new to programming :) Thank you. – Larx Apr 04 '18 at 03:42
  • Yes that's right. If my list does not contain `selected` then add it to the list. In plain english, only add to the list if the value isn't already there. – P.Brian.Mackey Apr 04 '18 at 03:43
0

Here's a trick: Whenever you need uniqueness, you can flip the randomization procedure to generate the unique numbers first, then randomize the order.

For example, this gives you a list of random numbers between 1 and 25 without any repetition:

var number = new Random();
var list = Enumerable.Range(1,25).OrderBy( i => number.NextDouble() );
John Wu
  • 50,556
  • 8
  • 44
  • 80