1

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.

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116

2 Answers2

1

What you need is a JavaScript random function that also accepts a seed. Then, you can make a numeric version of the username (or use their ID #), and pass it as the seed to your new function.

There is a method for doing this posted here: Seedable JavaScript random number generator

Once you have done that, you will get the same random number generated each time. From there, you can choose that random number to select an index from an array of images.

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
0

Simple Map a String to a an Integer Function

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 randomish option from a string.

function getMappedCode(string, max_number_desired)
{
  var char_code_total = 0;  
  for(var i = 0; i < string.length; i++) {
    char_code_total += string.charCodeAt(i);  
  }  
  return char_code_total % max_number_desired;
}

var mapped_code = getMappedCode("tom finney", 10);

alert(mapped_code);
Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116