-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicatesDictionary.cs
More file actions
60 lines (49 loc) · 1.66 KB
/
DuplicatesDictionary.cs
File metadata and controls
60 lines (49 loc) · 1.66 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
using System;
using System.Collections.Generic;
namespace BalloonProblem
{
/// <summary>
/// A dictionary that allows duplicates, quite surprised this doesn't already exist in BCL
/// </summary>
public class DuplicatesDictionary<K, V>
{
private DuplicatesDictionaryEntryList<K, V>[] _table;
public DuplicatesDictionary()
{
_table = new DuplicatesDictionaryEntryList<K, V>[1000];
for(int i = 0; i < 1000; i++)
{
_table[i] = new DuplicatesDictionaryEntryList<K, V>();
}
}
public void Add(K key, V value)
{
var entry = new DuplicatesDictionaryEntry<K, V> { Key = key, Value = value };
var hash = Hash(entry);
_table[hash].Entries.Add(entry);
}
public void Remove(K key)
{
var entry = new DuplicatesDictionaryEntry<K, V> { Key = key};
var hash = Hash(entry);
var entries = _table[hash].Entries;
if (entries.Count != 0)
{
entries.RemoveAt(0);
}
}
private int Hash(DuplicatesDictionaryEntry<K, V> entry)
{
return Math.Abs(entry.Key.GetHashCode()) % _table.Length;
}
private class DuplicatesDictionaryEntryList<K, V>
{
public List<DuplicatesDictionaryEntry<K, V>> Entries { get; set; } = new List<DuplicatesDictionaryEntry<K, V>>();
}
private class DuplicatesDictionaryEntry<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
}
}