-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathHyperLogLog.php
60 lines (48 loc) · 1.25 KB
/
HyperLogLog.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
50
51
52
53
54
55
56
57
58
59
<?php
/**
* code-segment
*
* @author liu hao<liu546hao@163.com>
* @copyright liu hao<liu546hao@163.com>
*/
require_once './Bucket.php';
class HyperLogLog
{
private $bucketMap = [];
private $bucketCount = 16384;
public function __construct($bucketCount = 16384)
{
$this->bucketCount = $bucketCount;
for ($i = 0; $i < $bucketCount; $i++) {
$this->bucketMap[$i] = new Bucket();
}
}
public function add($value)
{
$number = crc32($value);
$bucketOffset = (($number & 0xffff0000) >> 16) % $this->bucketCount;
$this->getBucket($bucketOffset)->random();
}
public function count()
{
$number = 0.0;
$notEmptyCount = 0;
for ($i = 0; $i < $this->bucketCount; $i++) {
$division = floatval($this->getBucket($i)->getMaxTailZeroCount());
if ($division != 0) {
$number += 1.0 / $division;
$notEmptyCount++;
}
}
$avg = floatval($notEmptyCount) / $number;
return round(pow(2, $avg) * $notEmptyCount);
}
/**
* @param $offset
* @return Bucket
*/
private function getBucket($offset)
{
return $this->bucketMap[$offset];
}
}