Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Forked from srph/instruction.md
Created December 12, 2015 16:47
Show Gist options
  • Save onmyway133/2f7bd240fab794cf0e9c to your computer and use it in GitHub Desktop.
Save onmyway133/2f7bd240fab794cf0e9c to your computer and use it in GitHub Desktop.
Find a 9 letter string of characters that contains only letters from [acdegilmnoprstuw] such that the hash(the_string) is 910897038977002; If hash is defined with the given pseudo-code

Find a 9 letter string of characters that contains only letters from

acdegilmnoprstuw

such that the hash(the_string) is

910897038977002

if hash is defined by the following pseudo-code:

Int64 hash (String s) {
    Int64 h = 7
    String letters = "acdegilmnoprstuw"
    for(Int32 i = 0; i < s.length; i++) {
        h = (h * 37 + letters.indexOf(s[i]))
    }
    return h
}

For example, if we were trying to find the 7 letter string where hash(the_string) was 680131659347, the answer would be leepadg.

// Given character set
var set = 'acdegilmnoprstuw';
// Hasging algorithm constants
var CONST_HASH = 7;
var CONST_MULT = 37;
/**
* Hashing algorithm
* @return {int}
*/
var hash = function(string) {
var _hash = CONST_HASH;
for(var i = 0; i < string.length; i++) {
_hash = (_hash * CONST_MULT + set.indexOf(string[i]));
}
return _hash;
}
/**
* Decodes the provided hashing algorithm
* @return {str}
*/
var decode = function(_hash) {
var
decoded = '',
// The position of the portion
// of the decoded hash (letter) in the set
positionsInSet = [],
i;
for(i = 0; _hash > CONST_MULT; i++) {
// With a modulus, we are able to extract
// the exact decoded (letter in the set).
positionsInSet[i] = Math.floor(_hash % CONST_MULT);
// Divide back to go past back the multiplied value
// (constant value of 37)
_hash /= 37;
}
// Translates the value of each index
// to its respective letter in the set.
// We start from the last position
// for we are decoding it with a backwards logic.
for(i = (positionsInSet.length - 1); i >= 0; i--) {
// Concatenate each letter
decoded += set[ positionsInSet[i] ];
}
return decoded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment