-
Notifications
You must be signed in to change notification settings - Fork 0
/
BloomFilter.php
49 lines (40 loc) · 1.05 KB
/
BloomFilter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
* @author Ivan Pavlov [ivan dot pavlov at gmail dot com]
*/
class BloomFilter {
public $field; //length of the bitfield
public $len;
function hash($key){
return array(
abs(hexdec(hash('crc32','m'.$key.'a'))%$this->len),
abs(hexdec(hash('crc32','p'.$key.'b'))%$this->len),
abs(hexdec(hash('crc32','t'.$key.'c'))%$this->len)
);
}
function __construct($len){
$this->len = $len;
$this->field = bitset_empty($this->len);
}
static function init($field){
$bf = new self(strlen(bitset_to_string($field)));
$bf->field = $field;
return $bf;
}
function add($key){
foreach ($this->hash($key) as $h) bitset_incl($this->field,$h);
}
function has($key){
foreach ($this->hash($key) as $h) if (!bitset_in($this->field,$h)) return false;
return true;
}
/**
* Reports the false positive rate of the current bloom filter
* @param int $numItems number of items inserted in the bloom filter
*/
function falsePositiveRate($numItems){
$k = count($this->hash('1'));
return pow((1-pow((1-1/$this->len),$k*$numItems)),$k);
}
}
?>