-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
87 lines (71 loc) · 2.21 KB
/
Program.cs
File metadata and controls
87 lines (71 loc) · 2.21 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
75
76
77
78
79
80
81
82
83
84
85
86
87
// This is a simple implementation of a set using a hash table.
// This implementation isn't complete and it's not efficient.
// It's just a simple example to show how a hash table works.
var hashtable = new Set(5);
hashtable.Add("Leo"); // 76 101 111 = 288 % 5 -> 3
hashtable.Add("Eva"); // 69 118 97 = 284 % 5 -> 4
hashtable.Add("Bob"); // 66 111 98 = 275 % 5 -> 0
hashtable.Add("Sue"); // 83 117 101 = 301 % 5 -> 1
hashtable.Add("Ana"); // 65 110 97 = 272 % 5 -> 2
//hashtable.Add("Lia"); // 76 105 97 = 278 % 5 -> 3
Console.WriteLine(hashtable.Get("Leo")); // Leo
Console.WriteLine(hashtable.Get("Eva")); // Eva
Console.WriteLine(hashtable.Get("Bob")); // Bob
Console.WriteLine(hashtable.Get("Sue")); // Sue
Console.WriteLine(hashtable.Get("Ana")); // Ana
//Console.WriteLine(hashtable.Get("Lia")); // Lia
hashtable.Remove("Leo");
hashtable.Remove("Eva");
hashtable.Remove("Bob");
hashtable.Remove("Sue");
hashtable.Remove("Ana");
//hashtable.Remove("Lia");
class Set
{
private string?[] _items;
public Set(int capacity)
=> _items = new string[capacity];
public void Add(string value)
{
var index = _computeHash(value);
if (_items[index] is not null)
{
throw new InvalidOperationException();
}
_items[index] = value;
}
public string Get(string value)
{
var index = _computeHash(value);
if (_items[index] is not null)
{
if (_items[index] == value)
{
return _items[index];
}
}
throw new KeyNotFoundException();
}
public void Remove(string value)
{
var index = _computeHash(value);
if (_items[index] is null)
{
throw new KeyNotFoundException();
}
if (_items[index] != value)
{
throw new KeyNotFoundException();
}
_items[index] = null;
}
private int _computeHash(string value)
{ // This is an ingenuous way to get a hash code. Never use this in production.
var sum = 0;
foreach(var c in value)
{
sum += c;
}
return sum % _items.Length;
}
}