Reputation: 61
I am writing a cards game, and need to draw random cards from pile. I am using Random and Random.Next(..) for that. Now I want to debug my application, and want to be able to reproduce certain scenarios by using the same Random sequence. Can anyone help...? I couldn't find an answer over several searches. Thanks.
Upvotes: 4
Views: 4371
Reputation: 21927
Use the overload of the Random
constructor which accepts a seed value
static Random r = new Random(0);
This will produce the same sequence of pseudorandom numbers across every execution.
Upvotes: 11
Reputation: 3663
Possibly a bit of overkill for this case (using a seed will give you repeatability) but a good shape for dealing with dependencies over which you do not have full control is to wrap the dependency and access it through an interface. This will allow you to swap in a version that gives specified behaviour for unit testing/ debugging.
e.g.
public interface IRandom {
int Get();
}
public class DefaultRandom : IRandom {
private readonly Random random;
public DefaultRandom() {
random = new Random();
}
public int Get() {
return random.Next();
}
}
public class TestRandom : IRandom {
private readonly List<int> numbers;
private int top;
public TestRandom() {
numbers = new List<int> {1, 1, 2, 3, 5, 8, 13, 21};
top = 0;
}
public int Get() {
return (top >= numbers.Count)
? 0
: numbers[top++];
}
}
One of the nice aspects of this method is that you can use specific values (say, to test edge cases) which might be hard to generate using a fixed seed value.
Upvotes: 1
Reputation: 234715
You will need to seed your random number generator. Assuming you're using System.Random
, use
Random r = new Random(<some integer>);
which starts the sequence at <some integer>
.
But an important note here: you will need to research your random number generator carefully. Else it will be possible to decipher your sequence which will make playing your game unintentionally profitable for an astute user. I doubt you'll be using Random
once you pass to production. (Technically it's possible to decipher a linear congruential sequence - which is what C# uses - in a little over three drawings.)
Upvotes: 4
Reputation: 771
Use the same seed in Random constructor. That guarantee you that Next() will give the same results. For example
Random randomGen1 = new Random(5);
Random randomGen2 = new Random(5);
int r1 = randomGen1.Next();
int r2 = ramdomGen2.Next();
if(r1 == r2)
{
Console.WriteLine("Great success!!");
}
Upvotes: 1
Reputation: 265241
Create a System.Random
instance with the same seed:
Random random = new System.Random(1337);
Upvotes: 1