开发者

Generating a Random Sequence from a string

I have a function that uses Randomized numbers to generate its output. I'd like to be able to seed these random numbers with a long string; so long as the string is the same, the random number sequence will be the same. This is mainly for test purposes, but also for repeatability.

I plan on creating a wrapper class that acts like the built-in System.Random class with a constructor sort of like this:

MyRandom mr = new MyRandom(100, "This is a really long string...");

This generates an internal list of numbers so that when mr.Next() is called it just returns the next entry in the list. When it gets to 100, the list just wraps. I'd like to be able to call .NextDouble() too. This isn't meant to be anything high performance, I just want to be able to generate a random list and use it again.开发者_Go百科

How do I convert the long string into a list of randomish number. I've thought about taking the length of the string and diving by the number n (in this case 100). Then subdividing the string and calling a hash on each segment.

Is this a reasonable way to do this or is there another, better method?


You don't really need a long input to initialize Random such that it generates the same sequence of random values (for the same sequence of calls). If you just use integer as an argument, then Random will initialize its internal state (called seed) using the integer and the sequence of randomly generated numbers will be always the same (for the same seed).

  • For more information see the overloaded Random constructor at MSDN

If you want to initialize Random using a string value for some reason, then you can just use new Random(str.GetHashCode()).


Sounds a bit strange. Are you looking for something like this?

Random rnd = new Random("Your string".GetHashCode());
Console.WriteLine(rnd.Next());

This would always generate the same sequence of random number as you're essentially seeding with the string whereas the hash code will always remain the same for the same string.


Here's how I made it deterministic across process restarts:

private static Random GetRNG(string seed) {
    using var algo = SHA1.Create();
    var hash = BitConverter.ToInt32(algo.ComputeHash(Encoding.UTF8.GetBytes(seed)));
    return new Random(hash);
}


Why not just seed the random number generator with the hash code of the string, and use it like normal?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜