tags:

views:

60

answers:

3

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.

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?

+1  A: 

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).

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

Tomas Petricek
A: 

Java programmer here..

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

Mike Daniels
+3  A: 

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.

steinar