Benjamin Aguilar
Benjamin Aguilar

Reputation: 3

Javascript Hash Unusual Behavior with Short Strings

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?

Upvotes: 0

Views: 44

Answers (3)

Umashankar Das
Umashankar Das

Reputation: 601

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.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78550

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.

Upvotes: 0

Hodrobond
Hodrobond

Reputation: 1696

((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");

Upvotes: 1

Related Questions