Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Get random number in range based on current date

Hello everyone and thank you for reading.

I’m trying to get a random number in a given range (in my case 1 – 87) based on the current date (no matter the format… milliseconds, YYYYMMDD, etc) and all this in javascript.

The reason for this is that I want to have a random number in this range that is different from day to day but remains the same during the day.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I first thought of simply generating a random number and then storing it in the cookies or localeStorage but I think that if you empty the browser cache or the localStorage (because yes my project is meant to be used on a browser) it will generate a new number when the page reloads and so this solution won’t work.

Then I tried to use the seedRandom function of Davide Bau (http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html) but I didn’t get the expected result (maybe I didn’t understand how it works which is very likely too)

I would have shared with you a piece of code of my progress but none of the tests I did made sense to me, so I started from zero and I rely on you today.

Hoping to get some help, thanks !

>Solution :

Based on the ARNG algorithm that I found on the link you shared, you can use the current date (in my example, the timestamp format) as a seed for the RNG and always get the same random number from the list (1..87) given the same date.

<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/lib/alea.min.js">
</script>
<script>
const arng = new alea(new Date().getTime());
const rand = Math.ceil( arng.quick() * 87 ); 
console.log( rand ); // <= Gives a random number between 1 and 87, 
// based on the timestamp seed
</script>

Since the randomness is derived based on the date, you do not need to save anything in the localStorage or elsewhere. Your dates are the single point of reference when it comes to the random number generator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading