How to use the result from a hash function to get the index of an array?

I am involved in the study of flowering filters, and I look at various hash functions in JavaScript.

For example, I found this in another stack overflow answer:

Found here qaru.site/questions/19682 / ... )

String.prototype.hashCode = function() {
  var hash = 0, i, chr, len;
  if (this.length == 0) return hash;
  for (i = 0, len = this.length; i < len; i++) {
    chr   = this.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
};

If I run:

String.prototype.call(null, "hello") 

I get a numerical value: 99162322 (two other hash functions got me: 1335831723 and 120092131).

Now, if I create a hypothetical flowering filter with three hash functions and 18 indices (k = 3, m = 18), How are these large values ​​indexed in an array with indices from 0-17?

+4
source share
1 answer

/ %, .

18 ( 0 17), 99162322 % 18 (16).

- , . , 0 4, 0 2, 0 (0 % 3, 3 % 3) 1 ( 1 % 3 4 % 3) 2 ( 2 % 3). , - , . , -, , . - :

function hashIndex(string, length, hashValueCount) {
  var minBiasedIndex = hashValueCount - (hashValueCount % length);
  for (var i = 0; ; i++) {
    var hashInput = string + ":" + String(i);
    var hashResult = hash(hashInput);
    if (hashResult < minBiasedIndex) {
      return hashResult % length;
    }
  }
}
+1

Source: https://habr.com/ru/post/1617806/


All Articles