0

I tried to create a hash function in Javascript, and I noticed that one version of it had strange behavior with two-letter strings.

    function hash(seed) {
            var genseed = 0;
            for(i=0;i<seed.length;++i) {
                    genseed += seed.charCodeAt(i)**((seed.length-1)-i);
            }
            console.log(genseed)
    }

When you call hash on two-letter strings like hash("AB") and hash("AX"), you get the exact same result. Yes I know about hash collision, but here it seems that so long as the first letter is the same, the second letter changes nothing, so is it just being ignored? Why exactly does this happen?

3
  • What is (seed.length-1)-i? Commented May 24, 2017 at 20:27
  • 1
    Why don't you just use **i instead of the more complicated formula? Commented May 24, 2017 at 20:36
  • @OliverCharlesworth seed.length is the number of characters in the input string. i is the number of times the for loop has already run (in this scenario anyway) Commented May 25, 2017 at 14:17

3 Answers 3

1

((seed.length-1)-i) is 0 when the length is 1 and i=1, or rather: every time the last character is reached. I'd advise removing the -1, otherwise you're just ignoring the last character.

function hash(seed) {
  var genseed = 0;
  for (i = 0; i < seed.length; ++i) {
    genseed += seed.charCodeAt(i) ** ((seed.length) - i);
  }
  console.log(genseed)
}

hash("AB");
hash("AX");

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I ended up doing, I just wanted to know why it was ignoring the last letter. Thanks
0

The problem is this part: ** ((seed.length-1)-i). For the last character, that evaluates to ** 0. Any number to the power of 0 equals 1. Therefor, the last character is always evaluated as 1. Change it to ** (seed.length-i) and it shouldn't have that issue.

Comments

0

In case of 2 letter strings. since, ur total iteration is 2 seed.length becomes equal to 2.

so,in the second iteration (seed.length-1)-i = 2 - 1 -1 = 0. Therefore what you're getting is basically the first genseed which is equal to 66 from the 1st iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.