|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +namespace DataStructures.Probabilistic |
| 6 | +{ |
| 7 | + public class HyperLogLog<T> where T : notnull |
| 8 | + { |
| 9 | + private const int P = 16; |
| 10 | + private const double Alpha = .673; |
| 11 | + private readonly int[] registers; |
| 12 | + private readonly HashSet<int> setRegisters; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Initializes a new instance of the <see cref="HyperLogLog{T}"/> class. |
| 16 | + /// </summary> |
| 17 | + public HyperLogLog() |
| 18 | + { |
| 19 | + var m = 1 << P; |
| 20 | + registers = new int[m]; |
| 21 | + setRegisters = new HashSet<int>(); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Merge's two HyperLogLog's together to form a union HLL. |
| 26 | + /// </summary> |
| 27 | + /// <param name="first">the first HLL.</param> |
| 28 | + /// <param name="second">The second HLL.</param> |
| 29 | + /// <returns>A HyperLogLog with the combined values of the two sets of registers.</returns> |
| 30 | + public static HyperLogLog<T> Merge(HyperLogLog<T> first, HyperLogLog<T> second) |
| 31 | + { |
| 32 | + var output = new HyperLogLog<T>(); |
| 33 | + for (var i = 0; i < second.registers.Length; i++) |
| 34 | + { |
| 35 | + output.registers[i] = Math.Max(first.registers[i], second.registers[i]); |
| 36 | + } |
| 37 | + |
| 38 | + output.setRegisters.UnionWith(first.setRegisters); |
| 39 | + output.setRegisters.UnionWith(second.setRegisters); |
| 40 | + return output; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Adds an item to the HyperLogLog. |
| 45 | + /// </summary> |
| 46 | + /// <param name="item">The Item to be added.</param> |
| 47 | + public void Add(T item) |
| 48 | + { |
| 49 | + var x = item.GetHashCode(); |
| 50 | + var binString = Convert.ToString(x, 2); // converts hash to binary |
| 51 | + var j = Convert.ToInt32(binString.Substring(0, Math.Min(P, binString.Length)), 2); // convert first b bits to register index |
| 52 | + var w = (int)Math.Log2(x ^ (x & (x - 1))); // find position of the right most 1. |
| 53 | + registers[j] = Math.Max(registers[j], w); // set the appropriate register to the appropriate value. |
| 54 | + setRegisters.Add(j); |
| 55 | + } |
| 56 | + |
| 57 | + /// <summary> |
| 58 | + /// Determines the approximate cardinality of the HyperLogLog. |
| 59 | + /// </summary> |
| 60 | + /// <returns>the approximate cardinality.</returns> |
| 61 | + public int Cardinality() |
| 62 | + { |
| 63 | + // calculate the bottom part of the harmonic mean of the registers |
| 64 | + double z = setRegisters.Sum(index => Math.Pow(2, -1 * registers[index])); |
| 65 | + |
| 66 | + // calculate the harmonic mean of the set registers |
| 67 | + return (int)Math.Ceiling(Alpha * setRegisters.Count * (setRegisters.Count / z)); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments