0

I'm having trouble randomizing X-amounts of strings and adding them to my listbox. it keeps adding the same string over and over. i want it to add 1 line per string. if i say that amount is 11, it just makes one string and adds it 11 times to listbox. what am i doing wrong?

here is my code:

for (int i = 0; i < amount; i++)
        {

            Random adomRng = new Random();
            string rndString = string.Empty;
            char c;

            for (int t = 0; t < 8; t++)
            {
                while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
                rndString += c;
            }

            listBox1.Items.Add(rndString);
        }
Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • You make a new Random object every loop with default seed? They should generate the same thing everytime. – Johnyy Dec 23 '15 at 04:22
  • i want to generate X-amount of strings, with the length of 8. and every string it creates, should be added to listbox. isnt it what my code is telling it to do? im so confused. idk why its not working @Johnny – Tibia Player Dec 23 '15 at 04:24
  • Put your Random adomRng = new Random(); out side of the for loop. – Johnyy Dec 23 '15 at 04:32
  • 1
    Possible duplicate of [Random number generator only generating one random number](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Preston Guillot Dec 23 '15 at 04:39

2 Answers2

2
Random adomRng = new Random();
for (int i = 0; i < amount; i++)
{
    string rndString = string.Empty;
    char c;
    for (int t = 0; t < 8; t++)
    {
        while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
        rndString += c;
    }
    listBox1.Items.Add(rndString);
}

Put the random init code outside of the loop, it will get you the correct result

Explanation: creating multiple new random objects in the short period of time (let's say inside a for loop) will always give you the same output because it will use the current timestamp as random seed.

Kien Chu
  • 4,735
  • 1
  • 17
  • 31
0

You are almost there,just make two simple changes in your code to achieve the target:

for (int t = 0; t < 8; t++)
 {
   rndString =""; //Change 1
   while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
   rndString += c;
   listBox1.Items.Add(rndString);// change  2
 }
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88