简体   繁体   中英

How to create a set of unique random numbers?

I've made this code for practicing and I want to make a list that keeps every number that this code wrote before so I don't want to get duplicates.

It's just guessing random numbers and I don't want it to guess the number that it already guessed before.

Just to be clear I want to make it as a list

int password = 432678;
int valt = 999999;

for (int i = 0; i < valt; i++)
{
    int[] test2 = new int[valt];
    Random randNum = new Random();
    for (int j = 0; j < test2.Length; j++)
    {                   
        test2[i] = randNum.Next(1, valt);
        Console.WriteLine("CURRENT: " + test2[i]);                    
        if (test2[i] == password)
        {
            goto Back;
        }
    }
}

Back:
    Console.WriteLine("password: "+ password);
    Console.ReadLine();

You can use Hashtable or Dictionary for this. Generate a number, try to check if that already exists. If not let's use that. If it is a duplicate, go on and generate another number.

You might also look for GUID if that supports your scenario.

There is one more approach that might suit you. Instead of generating random numbers, you could also increment numbers with each turn. So next will always be different from the previous.

Should work:

Random randNum = new Random();

int password = 432678;
int valt = 999999;

//INITIALIZE LIST
List<int> list = new List<int>();
for (int i = 0; i < valt; i++) list.Add(i);


while (list.Count > 0)
{
    int index = randNum.Next(1, list.Count);
    Console.WriteLine("CURRENT: " + list[index] + ", LIST SIZE: " + list.Count);

    //BREAK WHILE
    if (list[index] == password) break;

    //REMOVE INDEX FROM LIST
    list.RemoveAt(index);
}

Console.WriteLine("password: " + password);
Console.ReadLine();

Martin's code: I would set the random to static.

static Random randNum = new Random(); 

int password = 432678;
int valt = 999999;

//INITIALIZE LIST
List<int> list = new List<int>();
for (int i = 0; i < valt; i++) list.Add(i);


while (list.Count > 0)
{
    int index = randNum.Next(1, list.Count);
    Console.WriteLine("CURRENT: " + list[index] + ", LIST SIZE: " + list.Count);

    //BREAK WHILE
    if (list[index] == password) break;

    //REMOVE INDEX FROM LIST
    list.Remove(index);
}

Console.WriteLine("password: " + password);
Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM