0

Say I have a regular Javascript array of around 500 words ie var words = ['apple', 'banana', cherry'... and a Keccak256 (SHA-3) hash that is generated then stored. I need to use the hash to select a value in the array. Every time the same hash is given, the same value must be selected again. It does not matter which word is initially selected, but all words must have a roughly equal chance of being selected.

The hash is made up of numbers 0-9 and letters a-f, example:

5f16f4c7f149ac4f9510d9cf8cf384038ad348b3bcdc01915f95de12df9d1b02

I would like to use the first 3 characters of the hash to do this, ie 5f1, but if more characters are needed, that's okay.

Tried a few things here, but it hasn't worked out too well, and I end up picking some words more than others. What would be a good way to go about doing this?

Thanks in advance!

Chris
  • 68
  • 8
  • `Tried a few things here` - like what? so far all you've done is ask a question with no code :p – Jaromanda X Jan 19 '18 at 01:14
  • @jaromanda-x Ohh, what I tried was shamefully bad, and it's long gone now! I think I need pointing in the right direction, then I can write the code myself, and post it on here for anyone else that may need it! – Chris Jan 19 '18 at 01:22
  • 1
    so something like `words[(parseInt(hash.substr(0,3), 16) % words.length)]` – Jaromanda X Jan 19 '18 at 01:23
  • @jaromanda-x Completely forgot about modulus, thank you very much, that would be it! – Chris Jan 19 '18 at 01:45
  • 1
    If you want an equal distribution, this is a bit tricky due to the limited numeric precision. While very small hashes such as `0...01` and `0..02` will map to distinct integers, this is not the case for numerically large hashes such as `f...fe` and `f...ff` which will map to the same integer. A solution could be to divide the digit sum by the max digit sum and multiply with the word list length. – le_m Jan 19 '18 at 01:46

0 Answers0