forked from RUSH-LAB/Flash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FrequentItems.cpp
83 lines (75 loc) · 1.87 KB
/
FrequentItems.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#pragma once
#include "FrequentItems.h"
using namespace std;
/* Constructor. */
FrequentItems::FrequentItems(int k)
{
_k = k;
_values = new int[_k](); // An array holding _k values.
_size = 0;
for (int i = 0; i < _k; i++)
{
_emptyLocations.push(i); // FIFO, first out will be the smallest number i = 0.
}
}
void FrequentItems::increment(int item)
{
// If item is not found in _keyToValLocMapping.
if (_keyToValLocMapping.find(item) == _keyToValLocMapping.end())
{
// If the lossy counter is saturated. Loss the counts.
if (_size == _k)
{ //clean
for (int i = 0; i < _k; i++)
{
_values[i]--;
if (_values[i] == -1)
{
_emptyLocations.push(i);
_size--;
int key = _valLocToKeyMapping[i];
_keyToValLocMapping.erase(key);
_valLocToKeyMapping.erase(i);
}
}
}
// If still space in the counter.
if (_size < _k)
{
int loc = _emptyLocations.front();
_emptyLocations.pop();
_values[loc] = 1;
_keyToValLocMapping[item] = loc;
_valLocToKeyMapping[loc] = item;
_size++;
}
}
else { // If item found in the mapping. Increase the counts.
_values[_keyToValLocMapping[item]]++;
}
}
unsigned int* FrequentItems::getTopk()
{
unsigned int * heavyhitters = new unsigned int[_keyToValLocMapping.size() + 2];
heavyhitters[0] = _keyToValLocMapping.size(); //1 reserved for id, 0 for size.
int count = 2;
for (unordered_map<int, int>::const_iterator it = _keyToValLocMapping.begin(); it != _keyToValLocMapping.end(); ++it) {
int val = it->first;
heavyhitters[count] = val;
count++;
}
return heavyhitters;
}
void FrequentItems::getTopk(unsigned int * outputs)
{
int count = 0;
for (unordered_map<int, int>::const_iterator it = _keyToValLocMapping.begin(); it != _keyToValLocMapping.end(); ++it) {
int val = it->first;
outputs[count] = val;
count++;
}
}
FrequentItems::~FrequentItems()
{
delete[] _values;
}