Ad

Converting An Arbitrary Seed Into A Float Between 0 And 1

I want to be able to change any string containing any utf-8 into a random number between 0 and 1.

I can convert any seed that is a number with the following:

Math.abs(Math.sin(seed));

From this I'm able to generate a pseudo seeded Math.random()-like number.

So it's converting a string into a number. I looked into using crypto and found that making a digest of the string works but is incredibly slow, and is a bit overkill.

Any ideas on how to accomplish this?

Ad

Answer

Using String.prototype.charCodeAt() you can generate an integer representation:

function stringToSeed(str){
  var values = [];
  for (var i = 0, len = str.length; i < len; i++) {
    values.push(str.charCodeAt(i));
  }
  // concatenatte and coerce to integer 
  return values.join('') + 0;
}

var seed = stringToSeed(string);

You can then pass this seed to sin as you were before.

The thought behind concatenation instead of simply adding the values is to ensure that order is taken into account for randomness, otherwise "AB" and "BA" would produce the same value, for example.

Ad
source: stackoverflow.com
Ad