Skip to content

Commit 11901dd

Browse files
authored
Create Hashset.lua
1 parent 0f176dc commit 11901dd

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

DataStructures/Hashset/Hashset.lua

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
local hashset = {}
2+
3+
hashset.__index = hashset
4+
5+
hashset.Node = {}
6+
hashset.Node.__index = hashset.Node
7+
8+
function hashset.Node.create(key)
9+
local s = {}
10+
setmetatable(s, hashset.Node)
11+
12+
s.key = key
13+
s.next = nil
14+
15+
return s
16+
end
17+
18+
function hashset.create(hash)
19+
local s = {}
20+
setmetatable(s, hashset)
21+
22+
if hash == nil then
23+
hash = function(x) return x end
24+
end
25+
26+
s.s = {}
27+
s.N = 0
28+
s.hash = hash
29+
30+
return s
31+
end
32+
33+
function hashset:add(key)
34+
local h = self.hash(key)
35+
local x = self.s[h]
36+
local found = false
37+
while x ~= nil do
38+
if x.key == key then
39+
found = true
40+
break
41+
end
42+
x = x.next
43+
end
44+
45+
if found == false then
46+
local old = self.s[h]
47+
self.s[h] = hashset.Node.create(key)
48+
self.s[h].next = old
49+
self.N = self.N + 1
50+
end
51+
52+
end
53+
54+
function hashset:contains(key)
55+
local h = self.hash(key)
56+
local x = self.s[h]
57+
while x ~= nil do
58+
if x.key == key then
59+
return true
60+
end
61+
x = x.next
62+
end
63+
return false
64+
end
65+
66+
function hashset:size()
67+
return self.N
68+
end
69+
70+
function hashset:isEmpty()
71+
return self.N == 0
72+
end
73+
74+
function hashset:remove(key)
75+
local h = self.hash(key)
76+
local x = self.s[h]
77+
local prev_x = nil
78+
while x ~= nil do
79+
if x.key == key then
80+
if prev_x == nil then
81+
self.s[h] = x.next
82+
else
83+
prev_x.next = x.next
84+
end
85+
self.N = self.N - 1
86+
end
87+
prev_x = x
88+
x = x.next
89+
end
90+
91+
return nil
92+
end
93+
94+
return hashset

0 commit comments

Comments
 (0)