Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I generate a random number between 1 and x (where x is quite small) based on a seed? [JavaScript]

I am currently trying to create a basic (locally hosted) webpage which displays a random image from a folder, with the image changing each day.

To do this, I have put all of the images into a folder and have given them the names 0001, 0002, 0003, ..., . I am now trying to create a random number generator which will generate the same number on a particular day, but on the next day will generate a totally different number. This random number will be used to select the image.

I have tried doing this using the following JavaScript:

var d = new Date();
var seed = Math.floor(d.getTime()/(1000*60*60*24));
var randID = Math.abs(Math.floor(Math.sin(Math.log(seed))*8));

However, incrementing the value of the seed does not have much of an effect on the variable randID, so this is not a possible solution.

Can anyone help me to understand how this might be done?

Note that it is important that the random numbers generated are uniformly distributed (or at least close).

1 Answer

Steven Parker
Steven Parker
243,318 Points

Random numbers don't "remember" what they have been, so anything truly random will have a chance of repeating the same image two days in a row.

So instead, just issue the messages sequentially:

var randID = Math.floor(new Date().getTime() / 8640000) % NUMBER_OF_IMAGES;

You could also shuffle the image names, but there's probably no need for that. Unless someone knows the numbering order of images in advance, they won't be able to distinguish sequential from random selection.