-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet.cpp
More file actions
74 lines (65 loc) · 1.69 KB
/
Copy pathHashSet.cpp
File metadata and controls
74 lines (65 loc) · 1.69 KB
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
#include "HashSet.h"
#include <algorithm>
HashSet::HashSet(unsigned int totalBuckets)
:totalBuckets{totalBuckets}, table{totalBuckets}, totalElements{0}
{
}
void HashSet::insert(std::int64_t value)
{
const auto hash{calculateHash(value)};
auto it{std::find(table.at(hash).begin(), table.at(hash).end(), value)};
const auto valueNotFound{it == table.at(hash).end()};
if(valueNotFound)
{
table[hash].push_back(value);
totalElements++;
}
}
void HashSet::erase(std::int64_t value)
{
const auto hash{calculateHash(value)};
auto it{std::find(table.at(hash).begin(), table.at(hash).end(), value)};
const auto valueFound{it not_eq table.at(hash).end()};
if(valueFound)
{
table.at(hash).erase(it);
totalElements--;
}
}
bool HashSet::contains(std::int64_t value) const
{
const auto hash{calculateHash(value)};
auto it{std::find(table.at(hash).begin(), table.at(hash).end(), value)};
return it not_eq table.at(hash).end();
}
unsigned int HashSet::size() const
{
return totalElements;
}
unsigned int HashSet::collisionCount() const
{
unsigned int totalCollisions{0};
for(const auto& valueList : table)
{
const auto valueListSize{valueList.size()};
const auto moreThanOneElement{valueListSize > 1};
if(moreThanOneElement)
{
totalCollisions+=(valueListSize-1);
}
}
return totalCollisions;
}
unsigned int HashSet::calculateHash(std::int64_t value) const
{
return value % totalBuckets;
}
bool HashSet::empty() const
{
return size() == 0;
}
void HashSet::clear()
{
table = std::vector<std::list<std::int64_t>>(totalBuckets);
totalElements = 0;
}