Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generated random string isn't random when called more than once [duplicate]

Tags:

c#

asp.net

I'm attempting to create a randomly generated string of words, which works fine unless I call it multiple times in a row. This is on a WebForms page that and the list of words comes from a file.

I suspect I'm not understanding something with out C# or possibly ASP.NET works in this case, can someone explain why this is happening and how to approach a fix?

Here is the method

public string GeneratePhrase()
{
    // get dictionary file
    var data = File.ReadAllLines(HttpContext.Current.Server.MapPath("~/libs/words.txt"));

    Random rand = new Random();
    int r1 = rand.Next(data.Count());
    int r2 = rand.Next(data.Count());
    int r3 = rand.Next(data.Count());

    string p1 = data.ElementAt(r1).ToLower();
    string p2 = data.ElementAt(r2).ToLower();
    string p3 = data.ElementAt(r3).ToLower();

    string ret = string.Format("{0}{1}{2}", p1, p2, p3);
    return ret;
}

If I call this once during a PostBack, it's fine and always creates a random combination of words. However if I use this more than once during a PostBack, it simply repeats the same random string from each call.

string s1 = this.GeneratePhrase();
string s2 = this.GeneratePhrase();
string s3 = this.GeneratePhrase();
Response.Write(s1);
Response.Write(s2);
Response.Write(s3);

output

tirefriendhotdog
tirefriendhotdog
tirefriendhotdog

Any reason on why this may happen?

like image 959
Kirk Avatar asked Dec 28 '25 13:12

Kirk


1 Answers

Random rand = new Random(); uses the current time as a seed value, so calling it multiple times in quick succession will give you the same random sequences. You can:

  • create a single Random object that is used for all requests
  • seed it with a different pseudo-random number like Guid.NewGuid().GetHashCode()
  • Use a different random number generator that is not time-dependent.
like image 191
D Stanley Avatar answered Dec 31 '25 04:12

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!