简体   繁体   中英

How to generate a new sequence of random numbers every day?

I'm making a daily challenge in a game. Every day should be a new challenge. My procedural generation uses a random number generator . Attempting the daily challenge twice (or two different users attempting it) should have the same results (the same sequence of random numbers).

I want:

  • generate a sequence of random numbers.
  • sequence must be the same every time I start generating in the same day
  • get a different sequence of numbers each day

I think I should create a Random with a DateTime as the seed, but I'm not sure how. DateTime.UtcNow.Ticks is a long and DateTime's seed is an int .

I do not want the hours/minutes/seconds to impact the randomness (aside from the boundary between yesterday and today). The answers I've found are all about passing the current time into Random (or how that's the default no-parameter ctor behaviour).

// UTC ensures all users see the date flip occur at the same
// time. If you want the date flip to be local for the user's
// time zone, use DateTime.Today instead.
var date = DateTime.UtcNow.Date;
// Generate a seed by combining the year and the day of the year.
// DayOfYear is always gregorian (ignores culture) and always in
// [1,366].
var seed = date.Year * 1000 + date.DayOfYear;
return new Random(seed);

It may be better to generate a sequence of random numbers once each day and store them, so that those numbers can be "replayed" to people who play the challenge during that day. This approach may be viable, for instance, if that challenge consists of a randomly generated puzzle game board. This approach also has the advantage that the application won't be tied to a particular RNG's implementation. See also my article on seeded RNGs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM