I would like to show a random image for each user on my system. However, a specific user must always receive same random image every time, so I must be able to generate the image id if required.
I am thinking of using an MD5 of the users name to generate a number. My system is using JavaScript and I am using the jQuery library.
For example, if there are 4 variations of the random image, I’d like to pass in the name as so and receive an integer.
$image_id = getImage(name);
Note: There is no need for the probabilities to be accurate. I.e. it does not concern me if one of the images is more popular than others.
Simple function to map a string to an integer
Ok, I wrote my own little function. Hope it is useful to someone.
The function sums the char codes for each of the chars in the string, then uses modulus to reduce the number to within the specified maximum. Seems to be quite effective.
N.b. It is not mathematically random, but it is pretty good for picking repeatable random-ish option from a string.