-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.d
132 lines (113 loc) · 2.65 KB
/
hashtable.d
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
struct Hashtable
{
this(size_t initialLength)
{
hashtable.length = initialLength;
}
size_t idx(string word)
{
return hashtable.length ? word.hashOf() % hashtable.length : 0;
}
void add(string word, size_t occ = 1)
{
int i = find(word);
if (i == -1)
{
hashtable[idx(word)] ~= Pair(word, occ);
}
else
{
hashtable[idx(word)][i].occ += occ;
}
}
int find(string word)
{
size_t idx = idx(word);
if (!hashtable.length || (hashtable[idx].length == 0)) return -1;
foreach (i, ref elem; hashtable[idx])
{
if (elem.key == word)
{
return cast(int) i;
}
}
return -1;
}
void remove(string word)
{
size_t idx = idx(word);
int i = find(word);
if (i == -1) return;
//import std.stdio;
foreach(j; i .. hashtable[idx].length - 1)
{
//writefln("Word %s i %s len %s", word, i, hashtable[idx].length);
hashtable[idx][j] = hashtable[idx][(j + 1)];
}
//hashtable[idx][i .. ($ - 1)] = hashtable[idx][(i + 1) .. $];
--hashtable[idx].length;
}
size_t get(string word, size_t defaultValue = 0)
{
size_t idx = idx(word);
int i = find(word);
if (i == -1) return defaultValue;
return hashtable[idx][i].occ;
}
void clear()
{
hashtable.length = 0;
}
void resize(size_t newSize)
{
auto h = new Hashtable(newSize);
foreach (ref bucket; hashtable)
{
foreach (ref elem; bucket)
{
h.add(elem.key, elem.occ);
}
}
hashtable = h.hashtable;
}
void resizeDouble()
{
resize(hashtable.length * 2);
}
void resizeHalve()
{
resize(hashtable.length / 2);
}
string bucketToString(size_t indexBucket)
{
import std.conv;
if (hashtable[indexBucket].length == 0) return "";
string res;
foreach(ref elem; hashtable[indexBucket])
{
res ~= "<" ~ elem.key ~ ", " ~ to!string(elem.occ) ~ "> ";
}
return res;
}
string toString()
{
string res;
foreach(i; 0 .. hashtable.length)
{
res ~= bucketToString(i);
res ~= "\n";
}
return res;
}
static struct Pair
{
string key;
size_t occ;
}
size_t length()
{
return hashtable.length;
}
alias Bucket = Pair[];
private Bucket[] hashtable;
}