-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
371 lines (337 loc) · 9.67 KB
/
mod.rs
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
use rand;
use std::cmp::Ordering;
use std::mem;
#[derive(Default, Debug)]
pub struct Treap {
root: Option<Box<Node>>,
}
#[derive(Debug)]
struct Node {
key: i32,
val: i32,
priority: u64,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Treap {
/// Makes a new empty Treap.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::treap::Treap;
///
/// let mut map = Treap::new();
///
/// // entries can now be inserted into the empty map
/// map.insert(1, 1);
/// ```
pub fn new() -> Treap {
Default::default()
}
/// Returns true if the map contains no elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::treap::Treap;
///
/// let mut a = Treap::new();
/// assert!(a.is_empty());
/// a.insert(1, 1);
/// assert!(!a.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.root.is_none()
}
/// Returns the value corresponding to the key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::treap::Treap;
///
/// let mut map = Treap::new();
/// map.insert(1, 1);
/// assert_eq!(map.get(1), Some(1));
/// assert_eq!(map.get(2), None);
/// ```
pub fn get(&self, key: i32) -> Option<i32> {
self.root.get(key)
}
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, `None` is returned.
///
/// If the map did have this key present, the value is updated, and the old
/// value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::treap::Treap;
///
/// let mut map = Treap::new();
/// assert_eq!(map.insert(37, 1), None);
/// assert_eq!(map.is_empty(), false);
///
/// map.insert(37, 2);
/// assert_eq!(map.insert(37, 3), Some(2));
/// ```
pub fn insert(&mut self, key: i32, value: i32) -> Option<i32> {
let prev = self.root.insert(key, value);
self.check();
prev
}
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::treap::Treap;
///
/// let mut map = Treap::new();
/// map.insert(1, 1);
/// assert_eq!(map.remove(1), Some(1));
/// assert_eq!(map.remove(1), None);
/// ```
pub fn remove(&mut self, key: i32) -> Option<i32> {
let prev = self.root.remove(key);
self.check();
prev
}
/// Returns true if the tree satisfies the binary
/// search tree propery of a treap.
fn is_bst(&self) -> bool {
self.root.is_bst(None, None)
}
/// Returns true if the tree satisfies the
/// heap propery of a treap.
fn is_heap(&self) -> bool {
self.root.is_heap()
}
/// Applies all the invariant tests on the
/// binary search tree. Tests are only
/// applied in the debug! context.
fn check(&self) {
debug_assert!(self.is_bst(), "Not a binary search tree");
debug_assert!(self.is_heap(), "Not a heap");
}
}
impl Node {
fn leaf(key: i32, val: i32) -> Node {
Node {
key: key,
val: val,
priority: rand::random(),
left: None,
right: None,
}
}
fn left(&self) -> &Box<Node> {
self.left.as_ref().unwrap()
}
fn right(&self) -> &Box<Node> {
self.right.as_ref().unwrap()
}
fn left_rotate(&mut self) {
let mut child = self.right.take().unwrap();
mem::swap(self, &mut child);
mem::swap(&mut child.right, &mut self.left);
self.left = Some(child);
}
fn right_rotate(&mut self) {
let mut child = self.left.take().unwrap();
mem::swap(self, &mut child);
mem::swap(&mut child.left, &mut self.right);
self.right = Some(child);
}
}
trait OptionBoxNode {
fn get(&self, key: i32) -> Option<i32>;
fn insert(&mut self, key: i32, value: i32) -> Option<i32>;
fn remove(&mut self, key: i32) -> Option<i32>;
fn rotate_to_leaf(&mut self);
fn is_bst(&self, min: Option<i32>, max: Option<i32>) -> bool;
fn is_heap(&self) -> bool;
fn mutate(&mut self) -> &mut Box<Node>;
fn key(&self) -> i32;
fn val(&self) -> i32;
fn left(&mut self) -> &mut Option<Box<Node>>;
fn right(&mut self) -> &mut Option<Box<Node>>;
}
impl OptionBoxNode for Option<Box<Node>> {
fn get(&self, key: i32) -> Option<i32> {
match *self {
None => None,
Some(ref node) => {
match key.cmp(&node.key) {
Ordering::Equal => Some(node.val),
Ordering::Less => node.left.get(key),
Ordering::Greater => node.right.get(key),
}
}
}
}
fn insert(&mut self, key: i32, value: i32) -> Option<i32> {
match *self {
None => {
*self = new_leaf(key, value);
None
}
Some(ref mut node) => {
let priority = node.priority;
match key.cmp(&node.key) {
Ordering::Equal => {
let prev = node.val;
node.val = value;
Some(prev)
}
Ordering::Less => {
let prev = node.left.insert(key, value);
if node.left().priority.lt(&priority) {
node.right_rotate();
}
prev
}
Ordering::Greater => {
let prev = node.right.insert(key, value);
if node.right().priority.lt(&priority) {
node.left_rotate();
}
prev
}
}
}
}
}
fn remove(&mut self, key: i32) -> Option<i32> {
match *self {
None => None,
Some(_) => {
let target = self.key();
let val = self.val();
match key.cmp(&target) {
Ordering::Equal => {
self.rotate_to_leaf();
Some(val)
}
Ordering::Less => self.left().remove(key),
Ordering::Greater => self.right().remove(key),
}
}
}
}
fn rotate_to_leaf(&mut self) {
if self.left().is_none() && self.right().is_none() {
*self = None;
} else if self.left().is_none() {
self.mutate().left_rotate();
self.left().rotate_to_leaf();
} else if self.right().is_none() {
self.mutate().right_rotate();
self.right().rotate_to_leaf();
} else {
let lkey = self.left().key();
let rkey = self.right().key();
if lkey.lt(&rkey) {
self.mutate().right_rotate();
self.right().rotate_to_leaf();
} else {
self.mutate().left_rotate();
self.left().rotate_to_leaf();
}
}
}
fn mutate(&mut self) -> &mut Box<Node> {
self.as_mut().unwrap()
}
fn key(&self) -> i32 {
self.as_ref().unwrap().key
}
fn val(&self) -> i32 {
self.as_ref().unwrap().val
}
fn left(&mut self) -> &mut Option<Box<Node>> {
&mut self.as_mut().unwrap().left
}
fn right(&mut self) -> &mut Option<Box<Node>> {
&mut self.as_mut().unwrap().right
}
fn is_heap(&self) -> bool {
match *self {
None => true,
Some(ref node) => {
let priority = node.priority;
if node.left.is_some() && node.left().priority.lt(&priority) {
return false;
}
if node.right.is_some() && node.right().priority.lt(&priority) {
return false;
}
node.left.is_heap() && node.right.is_heap()
}
}
}
fn is_bst(&self, min: Option<i32>, max: Option<i32>) -> bool {
match *self {
None => true,
Some(ref node) => {
if min.is_some() && node.key.cmp(&min.unwrap()) != Ordering::Greater {
return false;
}
if max.is_some() && node.key.cmp(&max.unwrap()) != Ordering::Less {
return false;
}
node.left.is_bst(min, Some(node.key)) && node.right.is_bst(Some(node.key), max)
}
}
}
}
fn new_leaf(key: i32, val: i32) -> Option<Box<Node>> {
Some(Box::new(Node::leaf(key, val)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_construction() {
let mut tree = Treap::new();
assert_eq!(tree.get(0), None);
assert_eq!(tree.insert(0, 1), None);
assert_eq!(tree.insert(0, 2), Some(1));
assert_eq!(tree.get(0), Some(2));
}
#[test]
fn insert_sequence() {
let mut tree = Treap::new();
for i in 0..256 {
assert_eq!(tree.insert(i, i), None);
}
for i in 0..256 {
assert_eq!(tree.get(i), Some(i));
}
}
#[test]
fn remove() {
let mut tree = Treap::new();
for i in 0..256 {
assert_eq!(tree.insert(i, i), None);
}
for i in 0..256 {
assert_eq!(tree.remove(i), Some(i));
assert_eq!(tree.remove(i), None);
}
}
}