Nikonah Nikonah - 2 months ago 26
C# Question

a bit weird random number generator c#

I am trying to make a code of random number generator, and it must have these specifications:


  • the code must have 2 letters followed by 6 digits

  • the letters are constant and same for each code

  • digits shouldn't EVER be duplicated.



I will generate 1000 of codes this way. I know how to generate such code but if I make 1000 of them and I don't want them to be duplicated plus the letters... honestly having some bad time here.

private void btnGenerate_Click(object sender, EventArgs e)
{
Random rnd = new Random();

string newLine = Environment.NewLine;
int nums = rnd.Next(100000, 999999);
txtNumbers.Text = nums.ToString();
for (int i = 1; i <= 1001; i++)
{
nums = rnd.Next(100000, 999999);
txtNumbers.Text = txtNumbers.Text +newLine + nums.ToString();
}
}

Answer

Try using a dictionary or a list to check for duplicates while you generate.

private void btnGenerate_Click(object sender, EventArgs e)
{
HashSet<int> dupTest = new HashSet<int>();
Random rnd = new Random();

string newLine = Environment.NewLine;
int nums = rnd.Next(100000, 999999);
txtNumbers.Text = nums.ToString();
while(dupTest.Count<1000)
{
    nums = rnd.Next(100000, 999999);
    if(!dupTest.Add(nums))
       continue;
    txtNumbers.Text =  txtNumbers.Text +newLine + nums.ToString();
}
}

check out Scott's answer below and use a Hashnet