-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRobinHoodHashTable.cpp
137 lines (125 loc) · 5.03 KB
/
RobinHoodHashTable.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
template <class T>
class RobinHoodHashTable
{
private:
vector<Hash<T>> table;
size_t size;
int collisions;
int find_count;
int insert_count;
int delete_count;
public:
RobinHoodHashTable(size_t size) : size(size), collisions(0), find_count(0), insert_count(0), delete_count(0)
{
if (size == 0)
throw runtime_error("Wrong size");
table.vector<Hash<T> >::resize(size);
for (auto it : table)
it = Hash<T>();
}
// Метод для поиска значения в хеш-таблице
size_t find(Hash<T> val)
{
size_t key = Hash<T>{}(val);
find_count++; // Увеличиваем счетчик операций поиска
size_t index = key % size; // �'ычисляем индекс ячейки
size_t distance = 0; // Расстояние до искомого значения
while (table[index] != Hash<T>() && Hash<T>{}(table[index]) != key && distance <= size)
{
// Продолжаем искать, пока не найдем ячейку с искомым значением или пустую ячейку
index = (index + 1) % size; // Переходим к следующей ячейке
distance++;
}
if (distance > size)
return -1;
return (Hash<T>{}(table[index]) == key) ? index : -1;
}
// Метод для вставки значения в хеш-таблицу
void insert(Hash<T> val)
{
size_t key = Hash<T>{}(val);
insert_count++; // Увеличиваем счетчик операций вставки
size_t index = key % size; // �'ычисляем индекс ячейки
size_t distance = 0; // Расстояние до текущей ячейки
while (table[index] != Hash<T>() && Hash<T>{}(table[index]) != key)
{
if (distance > Hash<T>{}(table[index]) - index)
{
// Robin Hood: обменять текущее значение с новым, если новое значение имеет меньшее расстояние
swap(table[index], val);
distance = Hash<T>{}(table[index]) - index;
}
index = (index + 1) % size; // Переходим к следующей ячейке
distance++;
collisions++; // Увеличиваем счетчик коллизий
}
// Вставляем новое значение в пустую ячейку
swap(table[index], val);
}
// Метод для удаления значения из хеш-таблицы
void remove(Hash<T> val)
{
size_t index = find(val); // Находим индекс ячейки с искомым ключом
delete_count += index != size_t(-1) ? 1 : 0; // Увеличиваем счетчик операций удаления
table[index * (index != size_t(-1))] = (index != size_t(-1)) ? Hash<T>() : table[index * (index != size_t(-1))];
}
// Метод для вычисления коэффициента заполнения таблицы
double loadFactor() const
{
size_t count = 0;
for (auto it : table)
count += int(it != Hash<T>());
return static_cast<double>(count) / (size - count);
}
int getCollisions() const
{
return collisions;
}
int getFindCount() const
{
return find_count;
}
int getInsertCount() const
{
return insert_count;
}
int getDeleteCount() const
{
return delete_count;
}
size_t getSize() const
{
return size;
}
// Метод для сохранения статистики в файл
void save(const string& filename) const
{
ofstream file(filename);
if (!file)
{
cerr << "Error opening file: " << filename << endl;
return;
}
file << "Find operations: " << getFindCount() << endl;
file << "Insert operations: " << getInsertCount() << endl;
file << "Delete operations: " << getDeleteCount() << endl;
file << "Collisions: " << getCollisions() << endl;
file << "Load factor: " << loadFactor() << endl;
file.close();
cout << "Statistics saved to file: " << filename << endl;
}
void save(const string& filename, char mode = 'a') const
{
if (mode == 'a') {
ofstream file(filename, ios_base::app); // Open the file in append mode
if (!file)
{
cerr << "Error opening file: " << filename << endl;
return;
}
//file << "Collisions: " << getCollisions() << ',' << getSize() << ',' << endl;
file << getCollisions() << ',' << loadFactor() << endl;
file.close();
}
}
};