I have a list of hundreds of Sector types with ID values that range from 1..999. The user wants to see a different random Sector displayed on the web site every day.
One way to solve this is to store the randomly selected Sector's ID for the day, and use that, and then update that field with a new Sector Id the next day. But that's a bit messy, because it means I need to store an arbitrary value somewhere in the database... (or alternatively the Application state or something)
I was also thinking that I could take the list of 1..999 and use some Random algorythm to select a random number based on the date, so as long as the date is the same as the last time the random number was selected, the same number will come out.
But I'm not sure how to implement this, so I'm looking for suggestions?
Also, given the size of the range (999), and the number of available days in a year (365), would this mean that the algorythm would always miss certain Sectors because their ID doesn't map to however the Random number selection process selects the Sector ID? Is there any way around this?
You can use the date as seed for the Random
class:
int day = (DateTime.Today - new DateTime(2000,1,1)).TotalDays;
Random rnd = new Random(day);
int id = rnd.Next(1, 1000);
Note that the day is calculated from a fixed start date instead of DateTime.DayOfYear
, so it will not restart each year and only use 365 of the values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With