0

I have this problem. I'd like to make random a choice from array [1,2,3,4] based on arbitrary 6 letter string in such way that this choice is always same if string is same.

So if i have string 'dogdog' function would return always '3' for example, but '4' for 'bigcat' etc.

I think the solution might be first hashing the string. How could one convert hash string into choice from array?

2 Answers 2

1

You can calculate a hash from a string and take the array item at [hash % array.length]. An example with the DJB hashfunc (see http://www.cse.yorku.ca/~oz/hash.html for more):

function djbHash(s) {
    let hash = 5381;

    for (let c of s) {
        hash = hash * 33 + c.charCodeAt(0);
    }
    return hash;
}

function mapToValues(s, values) {
    return values[djbHash(s) % values.length];
}

console.log(mapToValues('dogdog', [1, 2, 3, 4]));
console.log(mapToValues('bigcat', [1, 2, 3, 4]));

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good solution because the hashing function have a good distribution. Better hashing functions give better results!
0

A really simple hash function:

  • Change each letter of your word by a number (a is 1, b is 2, etc.). Let's call w the whole word changed in a number.
  • Calculate i = w mod 4. i will be a number between 0 and 3. Add 1 to it.
  • Congrats, you can now associate any word to a "random" number between 1 and 4. You can of course replace 4 by any other number to associate each world to a random number in any range.

1 Comment

Your random number algorithm gives an exceptionally poor distribution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.