-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
HashTable.cs
327 lines (282 loc) · 10 KB
/
HashTable.cs
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
using System;
using System.Collections.Generic;
using System.Linq;
using DataStructures.Hashing.NumberTheory;
namespace DataStructures.Hashing;
/// <summary>
/// Hash table implementation.
/// </summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <typeparam name="TValue">Type of the value.</typeparam>
public class HashTable<TKey, TValue>
{
private const int DefaultCapacity = 16;
private const float DefaultLoadFactor = 0.75f;
private readonly float loadFactor;
private int capacity;
private int size;
private int threshold;
private int version;
private Entry<TKey, TValue>?[] entries;
/// <summary>
/// Gets the number of elements in the hash table.
/// </summary>
public int Count => size;
/// <summary>
/// Gets the capacity of the hash table.
/// </summary>
public int Capacity => capacity;
/// <summary>
/// Gets the load factor of the hash table.
/// </summary>
public float LoadFactor => loadFactor;
/// <summary>
/// Gets the keys in the hash table.
/// </summary>
public IEnumerable<TKey> Keys => entries.Where(e => e != null).Select(e => e!.Key!);
/// <summary>
/// Gets the values in the hash table.
/// </summary>
public IEnumerable<TValue> Values => entries.Where(e => e != null).Select(e => e!.Value!);
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">Key to get or set.</param>
/// <returns>Value associated with the key.</returns>
public TValue this[TKey? key]
{
get
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
var entry = FindEntry(key);
if (entry == null)
{
throw new KeyNotFoundException();
}
return entry.Value!;
}
set
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
var entry = FindEntry(key);
if (entry == null)
{
throw new KeyNotFoundException();
}
entry.Value = value;
version++;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="HashTable{TKey, TValue}"/> class.
/// </summary>
/// <param name="capacity">Initial capacity of the hash table.</param>
/// <param name="loadFactor">Load factor of the hash table.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="capacity"/> is less than or equal to 0.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="loadFactor"/> is less than or equal to 0.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="loadFactor"/> is greater than 1.</exception>
/// <remarks>
/// <paramref name="capacity"/> is rounded to the next prime number.
/// </remarks>
/// <see cref="PrimeNumber.NextPrime(int, int, bool)"/>
/// <see cref="PrimeNumber.IsPrime(int)"/>
public HashTable(int capacity = DefaultCapacity, float loadFactor = DefaultLoadFactor)
{
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be greater than 0");
}
if (loadFactor <= 0)
{
throw new ArgumentOutOfRangeException(nameof(loadFactor), "Load factor must be greater than 0");
}
if (loadFactor > 1)
{
throw new ArgumentOutOfRangeException(nameof(loadFactor), "Load factor must be less than or equal to 1");
}
this.capacity = PrimeNumber.NextPrime(capacity);
this.loadFactor = loadFactor;
threshold = (int)(this.capacity * loadFactor);
entries = new Entry<TKey, TValue>[this.capacity];
}
/// <summary>
/// Adds a key-value pair to the hash table.
/// </summary>
/// <param name="key">Key to add.</param>
/// <param name="value">Value to add.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="key"/> already exists in the hash table.</exception>
/// <remarks>
/// If the number of elements in the hash table is greater than or equal to the threshold, the hash table is resized.
/// </remarks>
public void Add(TKey? key, TValue? value)
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
if (size >= threshold)
{
Resize();
}
var index = GetIndex(key);
if (
entries[index] != null &&
EqualityComparer<TKey>.Default.Equals(entries[index]!.Key!, key))
{
throw new ArgumentException("Key already exists");
}
if (EqualityComparer<TValue>.Default.Equals(value, default(TValue)))
{
throw new ArgumentNullException(nameof(value));
}
entries[index] = new Entry<TKey, TValue>(key!, value!);
size++;
version++;
}
/// <summary>
/// Removes the key-value pair associated with the specified key.
/// </summary>
/// <param name="key">Key to remove.</param>
/// <returns>True if the key-value pair was removed, false otherwise.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
/// <remarks>
/// If the number of elements in the hash table is less than or equal to the threshold divided by 4, the hash table is resized.
/// </remarks>
public bool Remove(TKey? key)
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
var index = GetIndex(key);
if (entries[index] == null)
{
return false;
}
entries[index] = null;
size--;
version++;
if (size <= threshold / 4)
{
Resize();
}
return true;
}
/// <summary>
/// Find the index of the entry associated with the specified key.
/// </summary>
/// <param name="key">Key to find.</param>
/// <returns>Index of the entry associated with the key.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
public int GetIndex(TKey? key)
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
var hash = key!.GetHashCode();
var index = hash % capacity;
if (index < 0)
{
index += capacity;
}
return index;
}
/// <summary>
/// Finds the entry associated with the specified key.
/// </summary>
/// <param name="key">Key to find.</param>
/// <returns>Entry associated with the key.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
/// <remarks>
/// This method uses <see cref="GetIndex(TKey)"/> internally.
/// </remarks>
public Entry<TKey, TValue>? FindEntry(TKey? key)
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
var index = GetIndex(key);
return entries[index];
}
/// <summary>
/// Checks if the hash table contains the specified key.
/// </summary>
/// <param name="key">Key to check.</param>
/// <returns>True if the hash table contains the key, false otherwise.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
/// <remarks>
/// This method uses <see cref="FindEntry(TKey)"/> internally.
/// </remarks>
public bool ContainsKey(TKey? key)
{
if (EqualityComparer<TKey>.Default.Equals(key, default(TKey)))
{
throw new ArgumentNullException(nameof(key));
}
return FindEntry(key) != null;
}
/// <summary>
/// Checks if the hash table contains the specified value.
/// </summary>
/// <param name="value">Value to check.</param>
/// <returns>True if the hash table contains the value, false otherwise.</returns>
public bool ContainsValue(TValue? value)
{
if (EqualityComparer<TValue>.Default.Equals(value, default(TValue)))
{
throw new ArgumentNullException(nameof(value));
}
return entries.Any(e => e != null && e.Value!.Equals(value));
}
/// <summary>
/// Clears the hash table.
/// </summary>
/// <remarks>
/// This method resets the capacity of the hash table to the default capacity.
/// </remarks>
public void Clear()
{
capacity = DefaultCapacity;
threshold = (int)(capacity * loadFactor);
entries = new Entry<TKey, TValue>[capacity];
size = 0;
version++;
}
/// <summary>
/// Resizes the hash table.
/// </summary>
/// <remarks>
/// This method doubles the capacity of the hash table and rehashes all the elements.
/// </remarks>
public void Resize()
{
var newCapacity = capacity * 2;
var newEntries = new Entry<TKey, TValue>[newCapacity];
foreach (var entry in entries)
{
if (entry == null)
{
continue;
}
var index = entry.Key!.GetHashCode() % newCapacity;
if (index < 0)
{
index += newCapacity;
}
newEntries[index] = entry;
}
capacity = newCapacity;
threshold = (int)(capacity * loadFactor);
entries = newEntries;
version++;
}
}