javascriptreturnreturn-valuegethashcode

How to find a string with specific letters in gethash javascript function


function getHash( string ) {  
   let h = 7, letters = "acdefhlmnoprstuw";   
   for( var i = 0; i < string.length; i++ ) {  
      h = ( h * 37 + letters.indexOf( string[ i ] ) );  
   }  
   return h;  
}

My task is to write a code which finds the string containing some of following letters: ACDEFHLMNOPRSTUW
Sothat the function getHash(THE SEARCHING STRING) gets the result of 18794359164.


Solution

  • I am not giving you some code, just some hints.

    To get an understanding of the code, you have, and the one, you want to get, is to take a string with you gunction and get a hash value from it.

    For example take 'wonder' and get

    19017519751
    

    as hash value.

    This value contains a start value of seven (h = 7) and for each letter it multiplies h with 37 (this value looks like it is made for 37 different characters) and adds the index value of letters.

    To get the opposite with a numerical value, you need to separate a rest of a division by 37 to get an index of a letter, exact the opposite of using a letter and add a value to the hash.

    For example take the above value 19017519751 and get the rest of the division by 37

    19017519751 % 37 -> 11  r
    

    Now with the last letter (remember encoding goes from start to end of the word, decoding starts with the end), you need get a value without the last letter.

    By encoding, you multiply each last sum by 37 and this works here as well, but in reversed manner and you need an integer value. Just divide by 37 and take the floored value for the next letter.

    The rest looks like this:

      513987020 % 37 ->  3  e
       13891541 % 37 ->  2  d
         375447 % 37 ->  8  n
          10147 % 37 ->  9  o
            274 % 37 -> 15  w
    

    Finially, you need to have a check to stop the iteration ans this value is 7 the first value of encoding.