Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random seed c# - How to generate same sequence of numbers for debug

Tags:

c#

random

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.

like image 693
Rainy267 Avatar asked Dec 01 '22 18:12

Rainy267


2 Answers

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.

like image 135
Rotem Avatar answered Dec 04 '22 08:12

Rotem


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

like image 34
Bathsheba Avatar answered Dec 04 '22 06:12

Bathsheba