-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderedset.lua
378 lines (313 loc) · 10.4 KB
/
orderedset.lua
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
local VERBOSE = false
local function log(...)
if VERBOSE then print('[INFO]',...) end
end
--[[
This is an implementation of a set that maintains an <= ordering between its items
by way of a self-balancing binary search (AVL) tree.
It's important to keep in mind the invariants of an AVL tree when reasoning
about the behavior:
- Each node has at most two subtrees
- Each node is valued greater than all nodes in its "left" subtree, and lesser
than all nodes in its "right" subtree
- Trees are traversed from "left" to "right" and thus in ascending order of value
- Each node is ranked according to its height in the tree
- Subtrees never rank higher than the root
- Subtrees with the same immediate root never differ in rank by more than 1
]]
local tree = {}
--[[
The height of a node is the length of the longest path downward from that node
to a leaf. Thus, the height of the root node is the height of the tree, and the
height of a leaf is zero.
Conventionally, an empty tree has a height of -1.
]]
local BASE_HEIGHT = -1
local function _leaf(item)
log('(_leaf)', item)
return setmetatable(
{
value = item,
__height = BASE_HEIGHT + 1,
__left = nil,
__right = nil,
},
{ __index = tree })
end
local function _get_height_safely(node)
return node and node.__height or BASE_HEIGHT
end
-- The proper height of a node is 1 greater than the height of its largest subtree.
local function _compute_proper_height(node)
return 1 +
math.max(
_get_height_safely(node.__left),
_get_height_safely(node.__right)
)
end
-- The balance factor will be in {-1, 0, 1} when the tree is balanced.
-- Otherwise, it will be negative when the left side is too tall, and positive
-- when the right side is too tall.
local function _balance_factor(node)
local left_height = _get_height_safely(node.__left)
local right_height = _get_height_safely(node.__right)
return (right_height - left_height)
end
--[[ NOTE(dabrady)
Balancing a binary tree changes the structure without interfering with the
ordering of its nodes.
We use this behavior in particular to ensure our tree is compact in terms of
height. Without this property, our set would technically still be ordered, but
manipulating it would grow less performant in direct proportion to its size.
]]
local function _balance(root_node)
log('(_balance)', root_node)
if not root_node then
print('\t(early return: nil)')
return nil
end
--[[
A single tree rotation is a constant-time operation that essentially
brings one node 'up' and pushes one node 'down'.
Excellent resources on tree rotation algorithms:
@see https://en.wikipedia.org/wiki/Tree_rotation
@see https://www.cs.swarthmore.edu/~brody/cs35/f14/Labs/extras/08/avl_pseudo.pdf
]]
local function __rotate(root_node, rotation_side, opposite_side)
log('\t(__rotate)', rotation_side)
--[[
Rotation is an operation that takes a node and its two subnodes, and
changes their relationship such that the original node becomes a subnode of
one of the others, and the other becomes a 'supernode' to the original.
(One of the sub-subtrees becomes orphaned in this process, and is reassigned
to maintain the tree invariants.)
The subnode in the direction of the rotation is the node that is 'lowered',
and thus its opposite is the node that gets 'promoted'.
(d)
/ \
(b) (e) (b)
/ \ right / \
(a) (c) rotate (a) (d)
-----> / \
(c) (e)
]]
local pivot_node = root_node[opposite_side]
root_node[opposite_side] = pivot_node[rotation_side]
pivot_node[rotation_side] = root_node
root_node.__height = _compute_proper_height(root_node)
pivot_node.__height = _compute_proper_height(pivot_node)
return pivot_node
end
local function __rotate_left(node)
return __rotate(node, "__left", "__right")
end
local function __rotate_right(node)
return __rotate(node, "__right", "__left")
end
root_node.__height = _compute_proper_height(root_node)
-- NOTE(dabrady) If the balance factor of the root is in violation, the tree is
-- unbalanced and needs restructuring.
local balance_factor = _balance_factor(root_node)
if balance_factor < -1 then
-- The left side is too tall, so lower it.
log('\tleft side too tall')
-- When the "inside edge" of a subtree is longer than the "outside edge", we
-- actually need to make a double-rotation to properly rebalance.
local left_balance = _balance_factor(root_node.__left)
if left_balance > 0 then
log('\tinside edge too tall')
root_node.__left = __rotate_left(root_node.__left)
end
return __rotate_right(root_node)
elseif balance_factor > 1 then
log('\tright side too tall')
-- The right side is too tall, so lower it.
local right_balance = _balance_factor(root_node.__right)
if right_balance < 0 then
log('\tinside edge too tall')
root_node.__right = __rotate_right(root_node.__right)
end
return __rotate_left(root_node)
end
-- We've determined the tree is balanced, so give it back.
log('(_balance) balanced root:', root_node)
return root_node
end
function tree:add(item)
log('(tree.add)', item)
if not self or not self.value then
-- Our base case: we've reached the end of a branch, and must grow a new leaf.
log('\tgrowing new leaf for '..item)
return _leaf(item)
end
if item < self.value then
log('\tgoing left from '..self.value)
-- Go left.
self.__left = tree.add(self.__left, item)
elseif item > self.value then
log('\tgoing right from '..self.value)
-- Go right.
self.__right = tree.add(self.__right, item)
else
-- Do nothing, item already represented by the this node.
end
-- Rebalance and return this node.
return _balance(self)
end
function tree:remove(item)
if not self then
return nil
end
-- Found it, time to do some switchery.
if item == self.value then
--[[
If it only has one subtree, just straight up replace it with that subtree;
no need to do anything fancy in this case. E.g.
(b) (b)
/ \ remove (d) / \
(a) (d) ---------> (a) (c)
/
(c)
]]
if not ( self.__left and self.__right ) then
return self.__left or self.__right
end
--[[
If this node is load-bearing (i.e. has both subtrees), we need to do some
more complex transplanting to maintain our order invariant.
What should happen here?
(b)
/ \ remove (b) ????
(a) (d) --------->
/ \
(c) (e)
One approach, which I will use here, is to simply replace the node-to-remove
with the "next" node in the tree (relative to the order invariant).
(b) (c)
/ \ remove (b) / \
(a) (d) ---------> (a) (d)
/ \ \
(c) (e) (e)
Such an action is a bit tricky when the "next" node has a subtree (it will
have either zero or one, by definition of "next") because we have to decide
where to put that subtree. But this is solved by considering a "node
replacement" to be a copy-remove-rebalance action, in which case we have a
simple case of recursion.
(c) (d)
/ \ remove (c) / \
(b) (f) ---------> (b) (f)
/ / \ / / \
(a) (d) (g) (a) (e) (g)
\
(e)
]]
-- The "next" node is always the bottom-left node of the right side of the tree.
local next_node = self.__right
while next_node do
next_node = next_node.__left
end
-- Change the world.
local new_self = tree.remove(self, next_node.value)
-- Forget the old one.
new_self.value = next_node.value
return new_self
end
-- Walk the tree until we find the item, then remove it or die trying.
if item < self.value then
self.__left = tree.remove(self.__left, item)
elseif item > self.value then
self.__right = tree.remove(self.__right, item)
end
-- Rebalance and return this node.
return _balance(self)
end
-----
local orderedset = {}
local function _make_set()
log('(_make_set)')
return setmetatable(
{},
{
root = nil,
size = 0, -- the number of items in our ordered set
__len = function(t) return getmetatable(t).size end,
}
)
end
function orderedset.from(list)
log('(orderedset.from)', list)
local set = _make_set()
if list then
assert(type(list) == "table")
for _,item in ipairs(list) do
log('\tadding', item)
orderedset.add(set, item)
end
end
return set
end
function orderedset.add(set, item)
log('(orderedset.add)', item)
if not set then
error('need a set to add to')
end
if not item then
-- Don't allow nodes without value.
return nil
end
local meta = getmetatable(set)
if not meta.root then
-- The tree is empty, so return a new root.
log('\t(empty tree)')
meta.root = _leaf(item)
else
log('\t(non-empty tree)')
meta.root = meta.root:add(item)
end
-- Keep a table indexed by the items for performant lookups
if not set[item] then
set[item] = true
meta.size = meta.size + 1
end
return item
end
function orderedset.remove(set, item)
log('(orderedset.remove)', item)
if not set then
error('need a set to remove from')
end
if not item then
return nil
end
local meta = getmetatable(set)
meta.root = meta.root and meta.root:remove(item)
-- Keep a table indexed by the items for performant lookups
if set[item] then
set[item] = nil
meta.size = meta.size - 1
end
return nil
end
function orderedset.iterate(set)
log('(orderedset.iterate)')
if not set then
error('need a set to iterate over')
end
local function __traverse(node)
if not node then
return nil
end
__traverse(node.__left)
coroutine.yield(node.value)
__traverse(node.__right)
end
return coroutine.wrap(function()
__traverse(getmetatable(set).root)
end)
end
return setmetatable(
orderedset,
{
__call = function(_, ...) return orderedset.from(...) end
}
)