mika-el
1/14/2019 - 6:06 PM

hash JS

hash JS

/* Find a  8 -letter  string containing only letters from: 'acdegilmnoprstuw',
 * such that the hash(this_string) is 24682779393128 With hash defined by the following pseudo-code.
 * For example, if we try to find the 5-letter string where hash( this_string ) is  485617381 , the answer will be 'agile'.
 */

var letters = 'acdegilmnoprstuw';

function hash(word) {
  let hash = 7;

  for(let i = 0; i < word.length; i++) {
    hash = (hash * 37 + letters.indexOf(word[i]));
  }

  return hash;
}

function unHash(hash) {
  let result = '',
      mod;

  while (hash > 7) {
    mod = hash % 37;
    hash = (hash - mod) / 37;
    result = letters[mod] + result;
  }

  if (hash != 7) {
    throw "Oops, invlid hash!";
  }

  return result;
}

console.log(unHash(24682779393128));