10

I am writing a function that needs to return a 'random' number from a given string, starting from:

function hashNumberBetween(str, start, end){
  ....
  return num;
}

// same string and same length return same number
hashNumberBetween('getjnigejgr', 0, 10); // 4
hashNumberBetween('getjnigejgr', 0, 10); // 4

// but, same string and different length return different number
hashNumberBetween('getjnigejgr', 0, 32); // 15

hashNumberBetween('jukojmnktgo', 0, 10); // 6

what is the right way to achieve the same combination given the same string? I reckon it is some sort of hash function. Any online resource I can look at? Might sound a really easy question but I don't know how to search for it.

user3060636
  • 262
  • 4
  • 15
  • Yes you could do this by creating a hash function for the string (see [Generate a Hash from string in Javascript/jQuery](http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery)). Then you can use the resulting hash value to extract the appropriate values. – p.s.w.g Mar 28 '14 at 13:48
  • Does anyone solved this problem? Thanks – Jovem Mar 14 '18 at 16:00

2 Answers2

0

From your question I guess you can already return a random combination of colors and animals.

To achieve the desired behaviour you need a hash function to convert string into integer.

So just pick one of these Javascript hash functions or search for others on google (there is no need to reinvent the wheel).

Hope this helps, have a nice day,

Alberto

Alberto
  • 1,853
  • 1
  • 18
  • 22
-1

Is it something like password in database?

You pass some password string myPassword123 => convert it to crc32/md5 etc. => search in database for generated string => return user name by password.

Justinas
  • 41,402
  • 5
  • 66
  • 96