├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── stree.rs ├── rustfmt.toml └── src ├── bag.rs ├── deque.rs ├── graph ├── directed.rs ├── mod.rs └── undirected.rs ├── hashst.rs ├── kdtree.rs ├── lib.rs ├── misc.rs ├── prelude.rs ├── primitive.rs ├── priority_queue ├── binary_heaps.rs ├── index_pq.rs └── mod.rs ├── queue.rs ├── rbtree.rs ├── rope └── mod.rs ├── skip_list.rs ├── splay_tree.rs ├── stack.rs ├── suffix_tree.rs ├── tries.rs └── union_find.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | priv/ 4 | trash/ 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adivon" 3 | version = "0.2.6" 4 | authors = ["Shuyu Wang "] 5 | description = "Data Structures of daily use: Graph, HashTable, PriorityQueue, Trie, SuffixTree, Rope, SplayTree, SkipList, RedBlackTree." 6 | documentation = "https://docs.rs/adivon/" 7 | homepage = "https://github.com/andelf/rust-adivon" 8 | repository = "https://github.com/andelf/rust-adivon.git" 9 | keywords = ["algorithm", "book"] 10 | license = "MIT OR Apache-2.0" 11 | edition = "2018" 12 | 13 | [features] 14 | default = [] 15 | dev = ["clippy"] 16 | 17 | [dependencies] 18 | rand = "0.7" 19 | vec_map = "0.8" 20 | # clippy = "*" 21 | clippy = { version = "0.0", optional = true } 22 | 23 | [dev-dependencies] 24 | quickcheck = "0.9" 25 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The rust-adivon Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rust-adivon 2 | 3 | 阿迪王 —— 一切皆可改变! 4 | 5 | ## What's this? 6 | 7 | Rust 实现的各种数据结构。 8 | 9 | [Document](https://docs.rs/adivon/) 10 | 11 | - Bag 12 | - Stack 13 | - Queue 14 | - Deque 15 | - PriorityQueue 16 | - HashSearchTable 17 | - Tries 18 | - SuffixTree 19 | - SplayTree 20 | - Rope 21 | - SkipList 22 | - RedBlackTree 23 | - KdTree 24 | - UnionFind 25 | 26 | ## License 27 | 28 | Licensed under either of 29 | 30 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 31 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 32 | 33 | at your option. 34 | 35 | ### Contribution 36 | 37 | Unless you explicitly state otherwise, any contribution intentionally 38 | submitted for inclusion in the work by you, as defined in the Apache-2.0 39 | license, shall be dual licensed as above, without any additional terms or 40 | conditions. 41 | -------------------------------------------------------------------------------- /examples/stree.rs: -------------------------------------------------------------------------------- 1 | extern crate adivon; 2 | 3 | use adivon::suffix_tree::SuffixTree; 4 | 5 | fn main() { 6 | let s = "apple".chars().collect::>(); 7 | let s2 = "apple_tree".chars().collect::>(); 8 | let mut st = SuffixTree::new(&s); 9 | st.add(&s2); 10 | println!("{}", st.to_dot()); 11 | } 12 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | comment_width=120 3 | fn_call_width=100 4 | reorder_imports = true 5 | binop_separator = "Back" 6 | edition = "2018" 7 | newline_style = "Unix" 8 | normalize_comments = false 9 | # trailing_comma = "Never" 10 | tab_spaces = 4 11 | -------------------------------------------------------------------------------- /src/bag.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | pub struct Node { 4 | val: T, 5 | next: Option>>, 6 | } 7 | 8 | impl Clone for Node { 9 | fn clone(&self) -> Self { 10 | Node { 11 | val: self.val.clone(), 12 | next: self.next.clone(), 13 | } 14 | } 15 | } 16 | 17 | /// A collection of objects. 18 | pub struct Bag { 19 | s: Option>>, 20 | n: usize, 21 | } 22 | 23 | impl Clone for Bag { 24 | fn clone(&self) -> Self { 25 | Bag { 26 | s: self.s.clone(), 27 | n: self.n, 28 | } 29 | } 30 | } 31 | 32 | fn write_node_to_formatter(f: &mut fmt::Formatter, x: Option<&Box>>) -> fmt::Result { 33 | if let Some(node) = x { 34 | write!(f, "{:?}, ", node.val)?; 35 | write_node_to_formatter(f, node.next.as_ref()) 36 | } else { 37 | Ok(()) 38 | } 39 | } 40 | 41 | impl fmt::Debug for Bag { 42 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 43 | write!(f, "[")?; 44 | write_node_to_formatter(f, self.s.as_ref())?; 45 | write!(f, "]") 46 | } 47 | } 48 | 49 | impl Bag { 50 | pub fn new() -> Bag { 51 | Bag { s: None, n: 0 } 52 | } 53 | 54 | pub fn add(&mut self, val: T) { 55 | let next = self.s.take(); 56 | self.s = Some(Box::new(Node { val: val, next: next })); 57 | self.n += 1; 58 | } 59 | 60 | pub fn len(&self) -> usize { 61 | self.n 62 | } 63 | 64 | pub fn is_empty(&self) -> bool { 65 | self.len() == 0 66 | } 67 | } 68 | 69 | pub struct Iter<'a, T> 70 | where 71 | T: 'a, 72 | { 73 | node: Option<&'a Box>>, 74 | nitem: usize, 75 | } 76 | 77 | impl<'a, T> Iterator for Iter<'a, T> { 78 | type Item = &'a T; 79 | 80 | fn next(&mut self) -> Option<&'a T> { 81 | if self.nitem == 0 { 82 | None 83 | } else { 84 | let ret = self.node.map(|n| &n.val); 85 | self.node = self.node.map_or(None, |n| n.next.as_ref()); 86 | self.nitem -= 1; 87 | ret 88 | } 89 | } 90 | 91 | // Bad 92 | fn size_hint(&self) -> (usize, Option) { 93 | (self.nitem, Some(self.nitem)) 94 | } 95 | } 96 | 97 | impl<'a, T> ExactSizeIterator for Iter<'a, T> { 98 | fn len(&self) -> usize { 99 | self.nitem 100 | } 101 | } 102 | 103 | impl Bag { 104 | pub fn iter(&self) -> Iter { 105 | Iter { 106 | node: self.s.as_ref(), 107 | nitem: self.n, 108 | } 109 | } 110 | } 111 | 112 | #[test] 113 | fn test_bag() { 114 | let mut s = Bag::new(); 115 | assert_eq!(s.len(), 0); 116 | s.add(1000); 117 | assert_eq!(s.len(), 1); 118 | s.add(2000); 119 | assert_eq!(s.len(), 2); 120 | 121 | s.add(250); 122 | } 123 | 124 | #[test] 125 | fn test_bag_iter() { 126 | let mut s = Bag::new(); 127 | s.add(100); 128 | s.add(200); 129 | s.add(300); 130 | 131 | let mut result = vec![300, 200, 100].into_iter(); 132 | for i in s.iter() { 133 | assert_eq!(*i, result.next().unwrap()); 134 | } 135 | 136 | assert_eq!(s.len(), 3); 137 | } 138 | 139 | #[test] 140 | fn test_bag_clone() { 141 | let mut s = Bag::new(); 142 | s.add(100); 143 | s.add(200); 144 | s.add(300); 145 | 146 | let t = s.clone(); 147 | 148 | assert_eq!(t.len(), 3); 149 | } 150 | -------------------------------------------------------------------------------- /src/deque.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::mem; 3 | use std::ptr; 4 | 5 | struct Rawlink { 6 | p: *mut T, 7 | } 8 | 9 | impl Rawlink { 10 | fn none() -> Rawlink { 11 | Rawlink { p: ptr::null_mut() } 12 | } 13 | 14 | fn some(n: &mut T) -> Rawlink { 15 | Rawlink { p: n } 16 | } 17 | 18 | fn take(&mut self) -> Rawlink { 19 | mem::replace(self, Rawlink::none()) 20 | } 21 | } 22 | 23 | struct Node { 24 | item: T, 25 | next: Option>>, 26 | prev: Rawlink>, 27 | } 28 | 29 | impl Node { 30 | fn size(&self) -> usize { 31 | let mut p = self.next.as_ref(); 32 | let mut sz = 1; 33 | while p.is_some() { 34 | p = p.unwrap().next.as_ref(); 35 | sz += 1; 36 | } 37 | sz 38 | } 39 | } 40 | 41 | /// linked double queue 42 | pub struct Deque { 43 | first: Option>>, 44 | last: Rawlink>, 45 | } 46 | 47 | impl Deque { 48 | pub fn new() -> Deque { 49 | Deque { 50 | first: None, 51 | last: Rawlink::none(), 52 | } 53 | } 54 | 55 | pub fn is_empty(&self) -> bool { 56 | self.first.is_none() 57 | } 58 | 59 | pub fn len(&self) -> usize { 60 | self.first.as_ref().map_or(0, |n| n.size()) 61 | } 62 | 63 | pub fn add_first(&mut self, item: T) { 64 | let mut old_first = self.first.take(); 65 | let mut first = Box::new(Node { 66 | item: item, 67 | next: None, 68 | prev: Rawlink::none(), 69 | }); 70 | 71 | if old_first.is_some() { 72 | old_first.as_mut().unwrap().prev = Rawlink::some(&mut first); 73 | first.next = old_first; 74 | } else { 75 | self.last = Rawlink::some(&mut first); 76 | } 77 | 78 | self.first = Some(first) 79 | } 80 | 81 | pub fn add_last(&mut self, item: T) { 82 | if self.first.is_some() { 83 | let old_last = self.last.take(); 84 | let mut last = Box::new(Node { 85 | item: item, 86 | next: None, 87 | prev: Rawlink::none(), 88 | }); 89 | self.last = Rawlink::some(&mut last); 90 | unsafe { 91 | (*old_last.p).next = Some(last); 92 | } 93 | } else { 94 | self.add_first(item) 95 | } 96 | } 97 | 98 | pub fn remove_first(&mut self) -> Option { 99 | let old_first = self.first.take(); 100 | if old_first.is_some() { 101 | let Node { 102 | item, next: mut first, .. 103 | } = *old_first.unwrap(); 104 | // update new first's prev field 105 | first.as_mut().map(|v| v.prev = Rawlink::none()); 106 | self.first = first; 107 | Some(item) 108 | } else { 109 | None 110 | } 111 | } 112 | 113 | pub fn remove_last(&mut self) -> Option { 114 | let old_last = self.last.take(); 115 | if old_last.p.is_null() { 116 | return None; 117 | } 118 | let last_ref_mut = unsafe { &mut *old_last.p }; 119 | 120 | let last: Node = mem::replace(last_ref_mut, unsafe { mem::zeroed() }); 121 | 122 | if last.prev.p.is_null() { 123 | self.first = None; 124 | } else { 125 | unsafe { 126 | (*last.prev.p).next = None; 127 | } 128 | } 129 | self.last = last.prev; 130 | 131 | Some(last.item) 132 | } 133 | 134 | pub fn peek_first(&self) -> Option<&T> { 135 | self.first.as_ref().map(|n| &n.item) 136 | } 137 | 138 | pub fn peek_last(&self) -> Option<&T> { 139 | if self.last.p.is_null() { 140 | None 141 | } else { 142 | let last_ref = unsafe { &mut *self.last.p }; 143 | Some(&last_ref.item) 144 | } 145 | } 146 | } 147 | 148 | impl Deque { 149 | pub fn iter(&self) -> Iter { 150 | Iter { 151 | current: self.first.as_ref(), 152 | nelem: self.len(), 153 | } 154 | } 155 | } 156 | 157 | impl fmt::Display for Deque { 158 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 159 | match self.first { 160 | None => { 161 | write!(f, "")?; 162 | } 163 | Some(ref l) => { 164 | write!(f, "(")?; 165 | let mut p = Some(l); 166 | while p.is_some() { 167 | write!(f, "{},", p.unwrap().item)?; 168 | p = p.unwrap().next.as_ref(); 169 | } 170 | write!(f, ")")?; 171 | } 172 | } 173 | Ok(()) 174 | } 175 | } 176 | 177 | pub struct IntoIter { 178 | q: Deque, 179 | } 180 | 181 | impl Iterator for IntoIter { 182 | type Item = T; 183 | 184 | fn next(&mut self) -> Option { 185 | self.q.remove_first() 186 | } 187 | 188 | fn size_hint(&self) -> (usize, Option) { 189 | let len = self.q.len(); 190 | (len, Some(len)) 191 | } 192 | } 193 | 194 | impl ExactSizeIterator for IntoIter { 195 | fn len(&self) -> usize { 196 | self.q.len() 197 | } 198 | } 199 | 200 | impl DoubleEndedIterator for IntoIter { 201 | fn next_back(&mut self) -> Option { 202 | self.q.remove_last() 203 | } 204 | } 205 | 206 | impl IntoIterator for Deque { 207 | type Item = T; 208 | type IntoIter = IntoIter; 209 | 210 | fn into_iter(self) -> Self::IntoIter { 211 | IntoIter { q: self } 212 | } 213 | } 214 | 215 | // TODO impl DoubleEndedIterator 216 | pub struct Iter<'a, T: 'a> { 217 | current: Option<&'a Box>>, 218 | nelem: usize, 219 | } 220 | 221 | impl<'a, T> Iterator for Iter<'a, T> { 222 | type Item = &'a T; 223 | 224 | fn next(&mut self) -> Option<&'a T> { 225 | if self.nelem == 0 { 226 | return None; 227 | } 228 | let old_current = self.current.take(); 229 | 230 | self.current = (**old_current.unwrap()).next.as_ref(); 231 | self.nelem -= 1; 232 | Some(&old_current.as_ref().unwrap().item) 233 | } 234 | 235 | fn size_hint(&self) -> (usize, Option) { 236 | (self.nelem, Some(self.nelem)) 237 | } 238 | } 239 | 240 | impl<'a, T> ExactSizeIterator for Iter<'a, T> { 241 | fn len(&self) -> usize { 242 | self.nelem 243 | } 244 | } 245 | 246 | #[test] 247 | fn test_linked_deque_add_remove() { 248 | let mut deque: Deque = Deque::new(); 249 | 250 | assert!(deque.is_empty()); 251 | assert_eq!(deque.remove_first(), None); 252 | assert_eq!(deque.remove_last(), None); 253 | 254 | let result = vec![4, 0, 5, 2, 3]; 255 | let mut rit = result.iter(); 256 | // -1 remove last 257 | // -2 remove first 258 | // extra 2 more -1 -2 will result None 259 | for s in vec![4, 2, 3, 0, -1, -2, 5, -2, -1, -1, -2] { 260 | if s == -2 { 261 | assert_eq!(deque.remove_first(), rit.next().map(|&v| v)); 262 | } else if s == -1 { 263 | assert_eq!(deque.remove_last(), rit.next().map(|&v| v)); 264 | } else { 265 | deque.add_first(s); 266 | } 267 | } 268 | 269 | assert!(deque.is_empty()); 270 | } 271 | 272 | #[test] 273 | fn test_linked_deque_size() { 274 | let mut deque: Deque = Deque::new(); 275 | 276 | assert!(deque.is_empty()); 277 | 278 | let result = vec![0, 1, 2, 3, 4, 3, 2, 3, 2, 1, 0, 0]; 279 | let mut rit = result.iter(); 280 | // -1 remove last 281 | // -2 remove first 282 | for s in vec![4, 2, 3, 0, -1, -2, 5, -1, -1, -2] { 283 | if s == -2 { 284 | assert_eq!(deque.len(), *rit.next().unwrap()); 285 | deque.remove_first(); 286 | } else if s == -1 { 287 | assert_eq!(deque.len(), *rit.next().unwrap()); 288 | deque.remove_last(); 289 | } else { 290 | assert_eq!(deque.len(), *rit.next().unwrap()); 291 | deque.add_first(s); 292 | } 293 | } 294 | 295 | assert!(deque.is_empty()); 296 | } 297 | 298 | #[test] 299 | fn test_linked_deque_iter() { 300 | let mut deque: Deque = Deque::new(); 301 | 302 | assert!(deque.is_empty()); 303 | for i in 0..10 { 304 | if i % 2 == 0 { 305 | deque.add_first(i); 306 | } else { 307 | deque.add_last(i); 308 | } 309 | } 310 | 311 | let mut n = 0i32; 312 | let it = deque.iter(); 313 | assert_eq!(it.len(), 10); 314 | 315 | for _ in it { 316 | n += 1; 317 | } 318 | assert_eq!(n, 10); 319 | } 320 | 321 | #[test] 322 | fn test_deque_into_iter() { 323 | let mut deque: Deque = Deque::new(); 324 | deque.add_last(12); 325 | deque.add_last(11); 326 | deque.add_last(10); 327 | deque.add_first(0); 328 | deque.add_first(5); 329 | deque.add_first(7); 330 | 331 | let mut rit = vec![7, 5, 0, 12, 11, 10].into_iter(); 332 | for i in deque { 333 | assert_eq!(i, rit.next().unwrap()) 334 | } 335 | } 336 | 337 | #[test] 338 | fn test_deque_peek() { 339 | let mut deque: Deque = Deque::new(); 340 | deque.add_last(12); 341 | deque.add_last(10); 342 | 343 | assert_eq!(deque.peek_last(), Some(&10)); 344 | assert_eq!(deque.peek_first(), Some(&12)); 345 | deque.add_last(11); 346 | deque.add_first(34); 347 | assert_eq!(deque.peek_last(), Some(&11)); 348 | assert_eq!(deque.peek_first(), Some(&34)); 349 | } 350 | -------------------------------------------------------------------------------- /src/graph/directed.rs: -------------------------------------------------------------------------------- 1 | use super::super::bag::Bag; 2 | use super::super::queue::Queue; 3 | use super::super::stack; 4 | use super::super::stack::Stack; 5 | use std::iter; 6 | 7 | #[derive(Clone, Debug)] 8 | pub struct Digraph { 9 | v: usize, 10 | e: usize, 11 | adj: Vec>, 12 | } 13 | 14 | impl Digraph { 15 | pub fn new(v: usize) -> Digraph { 16 | Digraph { 17 | v: v, 18 | e: 0, 19 | adj: iter::repeat(Bag::::new()).take(v).collect(), 20 | } 21 | } 22 | 23 | fn validate_vertex(&self, v: usize) { 24 | assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) 25 | } 26 | 27 | pub fn v(&self) -> usize { 28 | self.v 29 | } 30 | 31 | pub fn e(&self) -> usize { 32 | self.e 33 | } 34 | 35 | pub fn add_edge(&mut self, v: usize, w: usize) { 36 | self.validate_vertex(v); 37 | self.validate_vertex(w); 38 | 39 | self.e += 1; 40 | self.adj[v].add(w); 41 | } 42 | 43 | pub fn outdegree(&self, v: usize) -> usize { 44 | self.validate_vertex(v); 45 | self.adj[v].len() 46 | } 47 | 48 | pub fn number_of_self_loops(&self) -> usize { 49 | let mut count = 0; 50 | for v in 0..self.v() { 51 | for w in self.adj(v) { 52 | if v == w { 53 | count += 1; 54 | } 55 | } 56 | } 57 | count / 2 58 | } 59 | 60 | pub fn to_dot(&self) -> String { 61 | let mut dot = String::new(); 62 | 63 | dot.push_str("digraph G {\n"); 64 | for i in 0..self.v { 65 | dot.push_str(&format!(" {};\n", i)); 66 | } 67 | 68 | for (v, adj) in self.adj.iter().enumerate() { 69 | for w in adj.iter() { 70 | dot.push_str(&format!(" {} -> {};\n", v, w)); 71 | } 72 | } 73 | dot.push_str("}\n"); 74 | dot 75 | } 76 | 77 | pub fn adj(&self, v: usize) -> Vec { 78 | self.adj[v].iter().cloned().collect() 79 | } 80 | 81 | pub fn reverse(&self) -> Digraph { 82 | let v = self.v; 83 | let mut adj = iter::repeat(Bag::new()).take(v).collect::>>(); 84 | for s in 0..v { 85 | for e in self.adj(s) { 86 | adj[e].add(s); 87 | } 88 | } 89 | Digraph { 90 | v: v, 91 | e: self.e, 92 | adj: adj, 93 | } 94 | } 95 | 96 | pub fn dfs(&self, s: usize) -> SearchPaths { 97 | let mut path = SearchPaths::new(self, SearchSource::Single(s)); 98 | path.dfs(); 99 | path 100 | } 101 | 102 | pub fn dfs_multi_source>(&self, s: T) -> SearchPaths { 103 | let mut path = SearchPaths::new(self, SearchSource::Multi(s.into_iter().collect())); 104 | path.dfs(); 105 | path 106 | } 107 | 108 | pub fn bfs(&self, s: usize) -> SearchPaths { 109 | let mut path = SearchPaths::new(self, SearchSource::Single(s)); 110 | path.bfs(); 111 | path 112 | } 113 | 114 | pub fn reverse_dfs_postorder(&self) -> stack::IntoIter { 115 | let mut dfo = DepthFirstOrder::new(self); 116 | dfo.init(); 117 | dfo.reverse_post.into_iter() 118 | } 119 | 120 | pub fn kosaraju_sharir_scc(&self) -> KosarajuSharirSCC { 121 | KosarajuSharirSCC::new(self) 122 | } 123 | } 124 | 125 | pub enum SearchSource { 126 | Single(usize), 127 | Multi(Vec), 128 | } 129 | 130 | impl SearchSource { 131 | fn iter(&self) -> ::std::vec::IntoIter { 132 | match *self { 133 | SearchSource::Single(ref i) => vec![*i].into_iter(), 134 | SearchSource::Multi(ref vs) => vs.clone().into_iter(), 135 | } 136 | } 137 | 138 | fn contains(&self, v: usize) -> bool { 139 | match *self { 140 | SearchSource::Single(ref i) => *i == v, 141 | SearchSource::Multi(ref vs) => vs.contains(&v), 142 | } 143 | } 144 | } 145 | 146 | pub struct SearchPaths<'a> { 147 | graph: &'a Digraph, 148 | marked: Vec, 149 | edge_to: Vec>, 150 | source: SearchSource, 151 | } 152 | 153 | impl<'a> SearchPaths<'a> { 154 | fn new(graph: &Digraph, source: SearchSource) -> SearchPaths { 155 | let mut marked = iter::repeat(false).take(graph.v()).collect::>(); 156 | let edge_to = iter::repeat(None).take(graph.v()).collect(); 157 | for s in source.iter() { 158 | marked[s] = true; 159 | } 160 | 161 | SearchPaths { 162 | graph: graph, 163 | marked: marked, 164 | edge_to: edge_to, 165 | source: source, 166 | } 167 | } 168 | 169 | fn dfs_from(&mut self, v: usize) { 170 | self.marked[v] = true; 171 | for w in self.graph.adj(v) { 172 | if !self.marked[w] { 173 | self.dfs_from(w); 174 | self.edge_to[w] = Some(v); 175 | } 176 | } 177 | } 178 | 179 | fn dfs(&mut self) { 180 | for v in self.source.iter() { 181 | self.dfs_from(v); 182 | } 183 | } 184 | 185 | fn bfs(&mut self) { 186 | let mut q = Queue::new(); 187 | for s in self.source.iter() { 188 | q.enqueue(s); 189 | } 190 | while !q.is_empty() { 191 | let v = q.dequeue().unwrap(); 192 | for w in self.graph.adj(v) { 193 | if !self.marked[w] { 194 | self.edge_to[w] = Some(v); 195 | q.enqueue(w); 196 | self.marked[w] = true; 197 | } 198 | } 199 | } 200 | } 201 | 202 | pub fn has_path_to(&self, v: usize) -> bool { 203 | self.marked[v] 204 | } 205 | 206 | pub fn path_to(&self, v: usize) -> Option> { 207 | if self.has_path_to(v) { 208 | let mut path = Stack::new(); 209 | let mut x = v; 210 | while !self.source.contains(x) { 211 | path.push(x); 212 | x = self.edge_to[x].unwrap(); 213 | } 214 | path.push(x); 215 | Some(path.into_iter().collect()) 216 | } else { 217 | None 218 | } 219 | } 220 | } 221 | 222 | pub struct DepthFirstOrder<'a> { 223 | graph: &'a Digraph, 224 | marked: Vec, 225 | reverse_post: Stack, 226 | } 227 | 228 | impl<'a> DepthFirstOrder<'a> { 229 | fn new(graph: &Digraph) -> DepthFirstOrder { 230 | let marked = iter::repeat(false).take(graph.v()).collect(); 231 | DepthFirstOrder { 232 | graph: graph, 233 | marked: marked, 234 | reverse_post: Stack::new(), 235 | } 236 | } 237 | 238 | fn init(&mut self) { 239 | for v in 0..self.graph.v() { 240 | if !self.marked[v] { 241 | self.dfs(v) 242 | } 243 | } 244 | } 245 | 246 | fn dfs(&mut self, v: usize) { 247 | self.marked[v] = true; 248 | for w in self.graph.adj(v) { 249 | if !self.marked[w] { 250 | self.dfs(w); 251 | } 252 | } 253 | self.reverse_post.push(v); 254 | } 255 | } 256 | 257 | /// Compute the strongly-connected components of a digraph using the 258 | /// Kosaraju-Sharir algorithm. 259 | pub struct KosarajuSharirSCC<'a> { 260 | graph: &'a Digraph, 261 | marked: Vec, 262 | id: Vec>, 263 | count: usize, 264 | } 265 | 266 | impl<'a> KosarajuSharirSCC<'a> { 267 | fn new(graph: &Digraph) -> KosarajuSharirSCC { 268 | let n = graph.v(); 269 | let mut cc = KosarajuSharirSCC { 270 | graph: graph, 271 | marked: iter::repeat(false).take(n).collect(), 272 | id: iter::repeat(None).take(n).collect(), 273 | count: 0, 274 | }; 275 | cc.init(); 276 | cc 277 | } 278 | 279 | fn init(&mut self) { 280 | for v in self.graph.reverse().reverse_dfs_postorder() { 281 | if !self.marked[v] { 282 | self.dfs(v); 283 | self.count += 1; 284 | } 285 | } 286 | } 287 | 288 | pub fn count(&self) -> usize { 289 | self.count 290 | } 291 | 292 | pub fn id(&self, v: usize) -> usize { 293 | self.id[v].unwrap() 294 | } 295 | 296 | pub fn connected(&self, v: usize, w: usize) -> bool { 297 | self.id[v] == self.id[w] 298 | } 299 | 300 | fn dfs(&mut self, v: usize) { 301 | self.marked[v] = true; 302 | self.id[v] = Some(self.count); 303 | for w in self.graph.adj(v) { 304 | if !self.marked[w] { 305 | self.dfs(w) 306 | } 307 | } 308 | } 309 | } 310 | 311 | #[test] 312 | fn test_digraph_visit() { 313 | let mut g = Digraph::new(13); 314 | g.add_edge(0, 1); 315 | g.add_edge(2, 0); 316 | g.add_edge(6, 0); 317 | g.add_edge(0, 5); 318 | 319 | g.add_edge(3, 5); 320 | g.add_edge(5, 4); 321 | 322 | g.add_edge(2, 3); 323 | g.add_edge(3, 2); 324 | 325 | g.add_edge(4, 3); 326 | g.add_edge(4, 2); 327 | g.add_edge(6, 4); 328 | 329 | g.add_edge(6, 8); 330 | g.add_edge(8, 6); 331 | 332 | g.add_edge(7, 6); 333 | 334 | g.add_edge(7, 9); 335 | g.add_edge(6, 9); 336 | 337 | g.add_edge(9, 10); 338 | g.add_edge(10, 12); 339 | g.add_edge(9, 11); 340 | g.add_edge(12, 9); 341 | g.add_edge(11, 12); 342 | 343 | // println!("dot => \n {}", g.to_dot()); 344 | // println!("dot => \n {}", g.reverse().to_dot()); 345 | assert_eq!(format!("{:?}", g.dfs(0).path_to(3).unwrap()), "[0, 5, 4, 2, 3]"); 346 | assert_eq!(format!("{:?}", g.bfs(0).path_to(3).unwrap()), "[0, 5, 4, 3]"); 347 | 348 | // FIXME: bad test case 349 | assert_eq!( 350 | format!("{:?}", g.dfs_multi_source(vec![0, 4]).path_to(3).unwrap()), 351 | "[4, 2, 3]" 352 | ); 353 | 354 | let scc = g.kosaraju_sharir_scc(); 355 | 356 | assert!(scc.connected(6, 8)); 357 | assert!(scc.connected(9, 12)); 358 | assert!(!scc.connected(6, 7)); 359 | } 360 | 361 | #[test] 362 | fn test_digraph() { 363 | let mut g = Digraph::new(10); 364 | g.add_edge(0, 3); 365 | g.add_edge(0, 5); 366 | g.add_edge(4, 5); 367 | g.add_edge(2, 9); 368 | g.add_edge(2, 8); 369 | g.add_edge(3, 7); 370 | 371 | g.add_edge(1, 6); 372 | g.add_edge(6, 9); 373 | g.add_edge(5, 8); 374 | 375 | // println!("got => \n{}", g.to_dot()); 376 | 377 | assert_eq!(10, g.v()); 378 | assert_eq!(9, g.e()); 379 | assert_eq!(1, g.outdegree(5)); 380 | 381 | for w in g.adj(5) { 382 | assert!(vec![8, 4, 0].contains(&w)); 383 | } 384 | 385 | assert_eq!(g.number_of_self_loops(), 0); 386 | } 387 | 388 | #[test] 389 | fn test_digraph_functions() { 390 | let mut g = Digraph::new(5); 391 | for i in 0..5 { 392 | for j in 0..5 { 393 | g.add_edge(i, j); 394 | } 395 | } 396 | 397 | assert_eq!(2, g.number_of_self_loops()); 398 | } 399 | 400 | #[test] 401 | fn test_digraph_depth_first_search_order() { 402 | let mut g = Digraph::new(7); 403 | g.add_edge(0, 2); 404 | g.add_edge(0, 5); 405 | g.add_edge(0, 1); 406 | g.add_edge(6, 0); 407 | g.add_edge(5, 2); 408 | g.add_edge(3, 2); 409 | g.add_edge(3, 5); 410 | g.add_edge(1, 4); 411 | g.add_edge(3, 4); 412 | g.add_edge(3, 6); 413 | g.add_edge(6, 4); 414 | 415 | let dfo: Vec = g.reverse_dfs_postorder().collect(); 416 | assert_eq!(vec![3, 6, 0, 5, 2, 1, 4], dfo); 417 | } 418 | -------------------------------------------------------------------------------- /src/graph/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod directed; 2 | pub mod undirected; 3 | 4 | // reexports 5 | pub use self::directed::Digraph; 6 | pub use self::undirected::Graph; 7 | -------------------------------------------------------------------------------- /src/graph/undirected.rs: -------------------------------------------------------------------------------- 1 | use super::super::bag; 2 | use super::super::bag::Bag; 3 | use std::iter; 4 | 5 | #[derive(Clone, Debug)] 6 | pub struct Graph { 7 | v: usize, 8 | e: usize, 9 | adj: Vec>, 10 | } 11 | 12 | impl Graph { 13 | pub fn new(v: usize) -> Graph { 14 | Graph { 15 | v: v, 16 | e: 0, 17 | adj: iter::repeat(Bag::::new()).take(v).collect(), 18 | } 19 | } 20 | 21 | fn validate_vertex(&self, v: usize) { 22 | assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) 23 | } 24 | 25 | pub fn vertices(&self) -> usize { 26 | self.v 27 | } 28 | 29 | pub fn edges(&self) -> usize { 30 | self.e 31 | } 32 | 33 | pub fn add_edge(&mut self, v: usize, w: usize) { 34 | self.validate_vertex(v); 35 | self.validate_vertex(w); 36 | 37 | self.e += 1; 38 | self.adj[v].add(w); 39 | self.adj[w].add(v); 40 | } 41 | 42 | pub fn degree(&self, v: usize) -> usize { 43 | self.validate_vertex(v); 44 | self.adj[v].len() 45 | } 46 | 47 | pub fn to_dot(&self) -> String { 48 | let mut dot = String::new(); 49 | 50 | dot.push_str("graph G {\n"); 51 | for i in 0..self.v { 52 | dot.push_str(&format!(" {};\n", i)); 53 | } 54 | 55 | //let mut edges = Vec::new(); 56 | for (v, adj) in self.adj.iter().enumerate() { 57 | for w in adj.iter() { 58 | // if let iter::MinMaxResult::MinMax(mi, ma) = vec![v, *w].into_iter().min_max() { 59 | // if !edges.contains(&(mi, ma)) { 60 | // edges.push((mi, ma)) 61 | // } 62 | // } 63 | dot.push_str(&format!(" {} -- {};\n", v, w)); 64 | } 65 | } 66 | // for &(v, w) in edges.iter() { 67 | // dot.push_str(&format!(" {} -- {};\n", v, w)); 68 | // } 69 | dot.push_str("}\n"); 70 | dot 71 | } 72 | 73 | pub fn adj(&self, v: usize) -> bag::Iter { 74 | self.adj[v].iter() 75 | } 76 | } 77 | 78 | #[test] 79 | fn test_graph() { 80 | let mut g = Graph::new(10); 81 | g.add_edge(0, 3); 82 | g.add_edge(0, 5); 83 | g.add_edge(4, 5); 84 | g.add_edge(2, 9); 85 | g.add_edge(2, 8); 86 | g.add_edge(3, 7); 87 | 88 | g.add_edge(1, 6); 89 | g.add_edge(6, 9); 90 | g.add_edge(5, 8); 91 | 92 | println!("got => \n{}", g.to_dot()); 93 | 94 | assert_eq!(10, g.vertices()); 95 | assert_eq!(9, g.edges()); 96 | assert_eq!(3, g.degree(5)); 97 | 98 | for w in g.adj(5) { 99 | assert!(vec![8, 4, 0].contains(w)); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/hashst.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Borrow; 2 | use std::collections::hash_map::DefaultHasher; 3 | use std::hash::{Hash, Hasher}; 4 | use std::ops::Index; 5 | 6 | struct Node { 7 | key: K, 8 | val: V, 9 | next: Option>>, 10 | } 11 | 12 | impl Node { 13 | pub fn size(&self) -> usize { 14 | match self.next { 15 | None => 1, 16 | Some(ref next) => 1 + next.size(), 17 | } 18 | } 19 | } 20 | 21 | fn delete(x: Option>>, key: &K) -> Option>> { 22 | if let Some(mut x) = x { 23 | let next = x.next.take(); 24 | if x.key == *key { 25 | next // this will drop x 26 | } else { 27 | x.next = delete(next, key); 28 | Some(x) 29 | } 30 | } else { 31 | None 32 | } 33 | } 34 | 35 | const M: usize = 97; 36 | 37 | // separate chaining 38 | pub struct HashST { 39 | st: Vec>>>, 40 | } 41 | 42 | impl HashST { 43 | pub fn new() -> HashST { 44 | let mut st = Vec::with_capacity(M); 45 | (0..M).map(|_| st.push(None)).count(); 46 | HashST { st: st } 47 | } 48 | 49 | // FIXME: hash state bug 50 | fn hash(key: &K) -> usize { 51 | let mut hasher = DefaultHasher::new(); 52 | key.hash(&mut hasher); 53 | hasher.finish() as usize % M 54 | } 55 | 56 | pub fn get>(&self, key: T) -> Option<&V> { 57 | let key = key.borrow(); 58 | let i = Self::hash(key); 59 | let mut x = self.st[i].as_ref(); 60 | while x.is_some() { 61 | if *key == x.unwrap().key { 62 | return Some(&x.unwrap().val); 63 | } 64 | x = x.unwrap().next.as_ref(); 65 | } 66 | None 67 | } 68 | 69 | pub fn get_mut>(&mut self, key: T) -> Option<&mut V> { 70 | let key = key.borrow(); 71 | let i = Self::hash(key); 72 | let mut x = self.st[i].as_mut(); 73 | while x.is_some() { 74 | if x.as_ref().map_or(false, |n| n.key == *key) { 75 | return Some(&mut x.unwrap().val); 76 | } 77 | x = x.unwrap().next.as_mut(); 78 | } 79 | None 80 | } 81 | 82 | pub fn put(&mut self, key: K, val: V) { 83 | let i = Self::hash(&key); 84 | { 85 | let mut x = self.st[i].as_mut(); 86 | while x.is_some() { 87 | if x.as_ref().map_or(false, |x| x.key == key) { 88 | x.unwrap().val = val; 89 | return; 90 | } else { 91 | x = x.unwrap().next.as_mut(); 92 | } 93 | } 94 | } 95 | let old = self.st[i].take(); 96 | self.st[i] = Some(Box::new(Node { 97 | key: key, 98 | val: val, 99 | next: old, 100 | })) 101 | } 102 | 103 | pub fn delete(&mut self, key: &K) { 104 | let i = Self::hash(key); 105 | self.st[i] = delete(self.st[i].take(), key); 106 | } 107 | 108 | pub fn size(&self) -> usize { 109 | self.st 110 | .iter() 111 | .filter(|n| n.is_some()) 112 | .map(|h| h.as_ref().unwrap().size()) 113 | .sum() 114 | } 115 | } 116 | 117 | // TODO: how to implement IndexMut? 118 | impl Index for HashST { 119 | type Output = V; 120 | fn index(&self, index: K) -> &V { 121 | self.get(index).expect("key not exists") 122 | } 123 | } 124 | 125 | #[test] 126 | fn test_separate_chaining_hash_st() { 127 | let mut m = HashST::new(); 128 | assert_eq!(m.size(), 0); 129 | m.put("Name", "Feather"); 130 | m.put("Age", "25"); 131 | m.put("Address", "Beijing"); 132 | 133 | assert_eq!(m.size(), 3); 134 | assert_eq!(m.get("Age"), Some(&"25")); 135 | assert_eq!(m.get("Gender"), None); 136 | 137 | m.delete(&"Age"); 138 | assert_eq!(m.size(), 2); 139 | assert_eq!(m.get("Age"), None); 140 | 141 | m.get_mut("Address").map(|v| *v = "Shanghai"); 142 | assert_eq!(m.get("Address"), Some(&"Shanghai")); 143 | 144 | assert_eq!(m["Address"], "Shanghai"); 145 | } 146 | -------------------------------------------------------------------------------- /src/kdtree.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Borrow; 2 | use std::cmp::Ordering; 3 | use std::f64; 4 | use std::fmt; 5 | use std::iter; 6 | use std::vec::IntoIter; 7 | 8 | use super::primitive::{Point2D, RectHV}; 9 | use super::Queue; 10 | 11 | /// A generic multidimension point. 12 | pub trait Point: Copy { 13 | // const DIMENSION: usize = 2; 14 | fn get(&self, d: usize) -> f64; 15 | 16 | #[inline] 17 | fn dimension() -> usize { 18 | 2 19 | } 20 | } 21 | 22 | impl Point for Point2D { 23 | #[inline] 24 | fn get(&self, d: usize) -> f64 { 25 | if d == 0 { 26 | self.x 27 | } else if d == 1 { 28 | self.y 29 | } else { 30 | panic!("dimension not supported") 31 | } 32 | } 33 | } 34 | 35 | pub type NodeCell = Option>>; 36 | 37 | pub struct Node { 38 | pub key: K, 39 | pub val: V, 40 | pub left: NodeCell, 41 | pub right: NodeCell, 42 | pub depth: usize, 43 | } 44 | 45 | impl Node { 46 | pub fn new(key: K, val: V, depth: usize) -> Node { 47 | Node { 48 | key: key, 49 | val: val, 50 | left: None, 51 | right: None, 52 | // depth use (depth % k)-th dimension 53 | depth: depth, 54 | } 55 | } 56 | 57 | fn size(&self) -> usize { 58 | let mut ret = 1; 59 | if self.left.is_some() { 60 | ret += self.left.as_ref().unwrap().size() 61 | } 62 | if self.right.is_some() { 63 | ret += self.right.as_ref().unwrap().size() 64 | } 65 | ret 66 | } 67 | 68 | #[inline] 69 | fn comparator_for_current_dim(&self) -> f64 { 70 | // let dim = self.depth % ::dimension(); 71 | self.key.get(self.depth % ::dimension()) 72 | } 73 | } 74 | 75 | impl Node { 76 | fn dump(&self, depth: usize, f: &mut fmt::Formatter, symbol: char) { 77 | if depth == 0 { 78 | writeln!(f, "\n{:?}[{:?}]", self.key, self.val).unwrap(); 79 | } else { 80 | writeln!( 81 | f, 82 | "{}{}--{:?}[{:?}]", 83 | iter::repeat("| ").take(depth - 1).collect::>().concat(), 84 | symbol, 85 | self.key, 86 | self.val 87 | ) 88 | .unwrap(); 89 | } 90 | if self.left.is_some() { 91 | self.left.as_ref().unwrap().dump(depth + 1, f, '+'); 92 | } 93 | if self.right.is_some() { 94 | self.right.as_ref().unwrap().dump(depth + 1, f, '`'); 95 | } 96 | } 97 | } 98 | 99 | fn put(x: NodeCell, key: K, val: V, depth: usize) -> NodeCell { 100 | let mut x = x; 101 | if x.is_none() { 102 | return Some(Box::new(Node::new(key, val, depth))); 103 | } 104 | let depth = x.as_ref().unwrap().depth; 105 | let dimension = ::dimension(); 106 | let current_dim = x.as_ref().unwrap().depth % dimension; 107 | let mut dim = current_dim; 108 | 109 | loop { 110 | let cmp = key.get(dim).partial_cmp(&x.as_ref().unwrap().key.get(dim)).unwrap(); 111 | match cmp { 112 | Ordering::Less => { 113 | let left = x.as_mut().unwrap().left.take(); 114 | x.as_mut().unwrap().left = put(left, key, val, depth + 1); 115 | break; 116 | } 117 | Ordering::Greater => { 118 | let right = x.as_mut().unwrap().right.take(); 119 | x.as_mut().unwrap().right = put(right, key, val, depth + 1); 120 | break; 121 | } 122 | // when current dimension is equal, compare next non-equal dimension 123 | Ordering::Equal => { 124 | dim = (dim + 1) % dimension; 125 | if dim == current_dim { 126 | x.as_mut().unwrap().val = val; 127 | break; 128 | } 129 | } 130 | } 131 | } 132 | x 133 | } 134 | 135 | fn delete_min(x: NodeCell) -> (NodeCell, NodeCell) { 136 | let mut x = x; 137 | if x.is_none() { 138 | return (None, None); 139 | } 140 | match x.as_mut().unwrap().left.take() { 141 | None => (x.as_mut().unwrap().right.take(), x), 142 | left @ Some(_) => { 143 | let (t, deleted) = delete_min(left); 144 | x.as_mut().unwrap().left = t; 145 | (x, deleted) 146 | } 147 | } 148 | } 149 | 150 | fn delete(x: NodeCell, key: &K) -> NodeCell { 151 | if x.is_none() { 152 | return None; 153 | } 154 | 155 | let mut x = x; 156 | let dim = x.as_ref().unwrap().depth % ::dimension(); 157 | 158 | match key.get(dim).partial_cmp(&x.as_ref().unwrap().key.get(dim)).unwrap() { 159 | Ordering::Less => { 160 | let left = x.as_mut().unwrap().left.take(); 161 | x.as_mut().unwrap().left = delete(left, key); 162 | x 163 | } 164 | Ordering::Greater => { 165 | let right = x.as_mut().unwrap().right.take(); 166 | x.as_mut().unwrap().right = delete(right, key); 167 | x 168 | } 169 | Ordering::Equal => { 170 | if x.as_ref().unwrap().right.is_none() { 171 | return x.as_mut().unwrap().left.take(); 172 | } 173 | if x.as_ref().unwrap().left.is_none() { 174 | return x.as_mut().unwrap().right.take(); 175 | } 176 | 177 | // Save top 178 | let mut t = x; 179 | 180 | // split right into right without min, and the min 181 | let (right, right_min) = delete_min(t.as_mut().unwrap().right.take()); 182 | x = right_min; 183 | x.as_mut().unwrap().right = right; 184 | x.as_mut().unwrap().left = t.as_mut().unwrap().left.take(); 185 | x 186 | } 187 | } 188 | } 189 | 190 | pub struct KdTree { 191 | pub root: NodeCell, 192 | } 193 | 194 | impl KdTree { 195 | pub fn new() -> KdTree { 196 | assert!(K::dimension() >= 2); 197 | KdTree { root: None } 198 | } 199 | 200 | pub fn contains(&self, key: &K) -> bool { 201 | self.get(key).is_some() 202 | } 203 | 204 | pub fn get(&self, key: &K) -> Option<&V> { 205 | let mut x = self.root.as_ref(); 206 | let dimension = ::dimension(); 207 | let current_dim = x.as_ref().unwrap().depth % dimension; 208 | while x.is_some() { 209 | let mut dim = current_dim; 210 | loop { 211 | match key.get(dim).partial_cmp(&x.unwrap().key.get(dim)).unwrap() { 212 | Ordering::Less => { 213 | x = x.unwrap().left.as_ref(); 214 | break; 215 | } 216 | Ordering::Greater => { 217 | x = x.unwrap().right.as_ref(); 218 | break; 219 | } 220 | Ordering::Equal => { 221 | dim = (dim + 1) % dimension; 222 | if dim == current_dim { 223 | return Some(&x.unwrap().val); 224 | } 225 | } 226 | } 227 | } 228 | } 229 | None 230 | } 231 | 232 | pub fn put(&mut self, key: K, val: V) { 233 | self.root = put(self.root.take(), key, val, 0); 234 | } 235 | 236 | pub fn delete(&mut self, key: &K) { 237 | self.root = delete(self.root.take(), key); 238 | } 239 | 240 | pub fn is_empty(&self) -> bool { 241 | self.root.is_none() 242 | } 243 | 244 | /// number of key-value pairs in the table 245 | pub fn size(&self) -> usize { 246 | if self.is_empty() { 247 | 0 248 | } else { 249 | self.root.as_ref().unwrap().size() 250 | } 251 | } 252 | } 253 | 254 | impl KdTree { 255 | pub fn keys(&self) -> ::std::vec::IntoIter<&K> { 256 | fn inorder<'a, K: Point, V>(x: Option<&'a Box>>, queue: &mut Vec<&'a K>) { 257 | if x.is_none() { 258 | return; 259 | } 260 | inorder(x.unwrap().left.as_ref(), queue); 261 | queue.push(&x.unwrap().key); 262 | inorder(x.unwrap().right.as_ref(), queue); 263 | }; 264 | 265 | let mut queue = Vec::new(); 266 | inorder(self.root.as_ref(), &mut queue); 267 | queue.into_iter() 268 | } 269 | } 270 | 271 | impl KdTree { 272 | // add the point to the KdTree 273 | pub fn insert(&mut self, p: Point2D) { 274 | self.put(p, ()); 275 | } 276 | 277 | /// find all Point2D keys that lie in a 2d range 278 | pub fn range_search>(&self, rect: T) -> IntoIter<&Point2D> { 279 | let mut result = Vec::new(); 280 | let rect = rect.borrow(); 281 | // use stack approach 282 | let mut stack = Vec::new(); 283 | stack.push(self.root.as_ref()); 284 | while !stack.is_empty() { 285 | let x = stack.pop().unwrap(); 286 | 287 | if x.is_none() { 288 | continue; 289 | } 290 | 291 | let dim = x.as_ref().unwrap().depth % 2; 292 | 293 | // Check if point in node lies in given rectangle 294 | if rect.contains(x.as_ref().unwrap().key) { 295 | result.push(&x.as_ref().unwrap().key) 296 | } 297 | // Recursively search left/bottom (if any could fall in rectangle) 298 | // Recursively search right/top (if any could fall in rectangle) 299 | if dim == 0 { 300 | if rect.xmin < x.as_ref().unwrap().comparator_for_current_dim() { 301 | stack.push(x.unwrap().left.as_ref()) 302 | } 303 | if rect.xmax > x.as_ref().unwrap().comparator_for_current_dim() { 304 | stack.push(x.unwrap().right.as_ref()) 305 | } 306 | } else { 307 | // dim == 1: y 308 | if rect.ymin < x.as_ref().unwrap().comparator_for_current_dim() { 309 | stack.push(x.unwrap().left.as_ref()) 310 | } 311 | if rect.ymax > x.as_ref().unwrap().comparator_for_current_dim() { 312 | stack.push(x.unwrap().right.as_ref()) 313 | } 314 | } 315 | } 316 | result.into_iter() 317 | } 318 | 319 | /// number of keys that lie in a 2d range 320 | pub fn range_count>(&self, rect: T) -> usize { 321 | self.range_search(rect).count() 322 | } 323 | 324 | // TODO: refactor to a generic solution 325 | pub fn nearest>(&self, p: T) -> Option<&Point2D> { 326 | let mut result = None; 327 | let mut min_distance = f64::MAX; 328 | let p = p.borrow(); 329 | 330 | // use FIFO queue 331 | let mut queue = Queue::new(); 332 | queue.enqueue(self.root.as_ref()); 333 | while !queue.is_empty() { 334 | let x = queue.dequeue().unwrap(); 335 | 336 | if x.is_none() { 337 | continue; 338 | } 339 | 340 | let dim = x.as_ref().unwrap().depth % 2; 341 | 342 | // Check distance from point in node to query point 343 | let dist = x.as_ref().unwrap().key.distance_to(p); 344 | if dist < min_distance { 345 | result = Some(&x.as_ref().unwrap().key); 346 | min_distance = dist; 347 | } 348 | 349 | // Recursively search left/bottom (if it could contain a closer point) 350 | // Recursively search right/top (if it could contain a closer point) 351 | // FIXME: duplicated code 352 | if dim == 0 { 353 | // p in left 354 | if p.x < x.unwrap().key.x { 355 | queue.enqueue(x.unwrap().left.as_ref()); 356 | if x.unwrap().right.is_some() { 357 | let perpendicular_len = (p.y - x.unwrap().right.as_ref().unwrap().key.y).abs(); 358 | if perpendicular_len < min_distance { 359 | queue.enqueue(x.unwrap().right.as_ref()); 360 | } 361 | } 362 | } else { 363 | // p in right 364 | queue.enqueue(x.unwrap().right.as_ref()); 365 | if x.unwrap().left.is_some() { 366 | let perpendicular_len = (p.y - x.unwrap().left.as_ref().unwrap().key.y).abs(); 367 | if perpendicular_len < min_distance { 368 | queue.enqueue(x.unwrap().left.as_ref()); 369 | } 370 | } 371 | } 372 | } else if p.y < x.unwrap().key.y { 373 | queue.enqueue(x.unwrap().left.as_ref()); 374 | if x.unwrap().right.is_some() { 375 | let perpendicular_len = (p.x - x.unwrap().right.as_ref().unwrap().key.x).abs(); 376 | if perpendicular_len < min_distance { 377 | queue.enqueue(x.unwrap().right.as_ref()); 378 | } 379 | } 380 | } else { 381 | queue.enqueue(x.unwrap().right.as_ref()); 382 | if x.unwrap().left.is_some() { 383 | let perpendicular_len = (p.x - x.unwrap().left.as_ref().unwrap().key.x).abs(); 384 | if perpendicular_len < min_distance { 385 | queue.enqueue(x.unwrap().left.as_ref()); 386 | } 387 | } 388 | } 389 | } 390 | result 391 | } 392 | } 393 | 394 | impl fmt::Debug for KdTree { 395 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 396 | if self.root.is_none() { 397 | write!(f, "") 398 | } else { 399 | self.root.as_ref().unwrap().dump(0, f, ' '); 400 | Ok(()) 401 | } 402 | } 403 | } 404 | 405 | #[test] 406 | fn test_kd_tree_with_point_2d() { 407 | let mut t = KdTree::::new(); 408 | 409 | assert!(t.nearest(Point2D::new(0.9, 0.8)).is_none()); 410 | 411 | t.put(Point2D::new(0.7, 0.2), ()); 412 | t.put(Point2D::new(0.5, 0.4), ()); 413 | t.put(Point2D::new(0.2, 0.3), ()); 414 | t.put(Point2D::new(0.4, 0.7), ()); 415 | t.put(Point2D::new(0.9, 0.6), ()); 416 | 417 | // println!("got => {:?}", t); 418 | 419 | assert_eq!(5, t.range_search(RectHV::new(0.1, 0.1, 0.9, 0.9)).count()); 420 | assert_eq!(1, t.range_search(RectHV::new(0.1, 0.1, 0.4, 0.4)).count()); 421 | 422 | assert_eq!(&Point2D::new(0.2, 0.3), t.nearest(Point2D::new(0.1, 0.1)).unwrap()); 423 | assert_eq!(&Point2D::new(0.9, 0.6), t.nearest(Point2D::new(0.9, 0.8)).unwrap()); 424 | } 425 | 426 | #[test] 427 | fn test_kd_tree_with_point_2d_duplicated() { 428 | let mut t = KdTree::::new(); 429 | 430 | t.put(Point2D::new(0.7, 0.2), ()); 431 | t.put(Point2D::new(0.5, 0.4), ()); 432 | t.put(Point2D::new(0.2, 0.3), ()); 433 | t.put(Point2D::new(0.2, 0.7), ()); 434 | t.put(Point2D::new(0.4, 0.7), ()); 435 | t.put(Point2D::new(0.4, 0.2), ()); 436 | t.put(Point2D::new(0.9, 0.6), ()); 437 | t.put(Point2D::new(0.7, 0.4), ()); 438 | // same node, this is replace behavior, no new node 439 | t.put(Point2D::new(0.9, 0.6), ()); 440 | 441 | assert_eq!(8, t.size()); 442 | assert!(t.contains(&Point2D::new(0.7, 0.2))); 443 | assert!(t.contains(&Point2D::new(0.7, 0.4))); 444 | assert!(!t.contains(&Point2D::new(0.7, 0.3))); 445 | assert!(!t.contains(&Point2D::new(0.4, 0.3))); 446 | assert_eq!(8, t.range_search(RectHV::new(0.1, 0.1, 0.9, 0.9)).count()); 447 | assert_eq!(2, t.range_search(RectHV::new(0.1, 0.1, 0.4, 0.4)).count()); 448 | 449 | assert_eq!(t.nearest(&Point2D::new(0.7, 0.39)).unwrap(), &Point2D::new(0.7, 0.4)); 450 | } 451 | 452 | // A B E C D H F G 453 | #[test] 454 | fn test_kd_tree_quiz_777404() { 455 | let mut t = KdTree::::new(); 456 | 457 | t.put(Point2D::new(0.50, 0.23), 'A'); 458 | t.put(Point2D::new(0.25, 0.75), 'B'); 459 | t.put(Point2D::new(0.17, 0.72), 'C'); 460 | t.put(Point2D::new(0.01, 0.82), 'D'); 461 | t.put(Point2D::new(0.71, 0.86), 'E'); 462 | t.put(Point2D::new(0.98, 0.94), 'F'); 463 | t.put(Point2D::new(0.08, 0.66), 'G'); 464 | t.put(Point2D::new(0.57, 0.20), 'H'); 465 | 466 | println!("tree : {:?}", t); 467 | } 468 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(associated_type_defaults, plugin)] 2 | #![allow(mutable_transmutes)] 3 | #![cfg_attr(feature = "dev", plugin(clippy))] 4 | #![cfg_attr(not(feature = "dev"), allow(unknown_lints))] 5 | 6 | pub mod bag; 7 | pub mod deque; 8 | pub mod graph; 9 | pub mod hashst; 10 | pub mod priority_queue; 11 | pub mod queue; 12 | pub mod stack; 13 | pub mod tries; 14 | 15 | pub mod splay_tree; 16 | pub mod suffix_tree; 17 | 18 | pub mod rope; 19 | 20 | pub mod skip_list; 21 | 22 | pub mod rbtree; 23 | 24 | pub mod kdtree; 25 | pub mod primitive; 26 | 27 | pub mod union_find; 28 | 29 | pub mod prelude; 30 | pub use prelude::*; 31 | -------------------------------------------------------------------------------- /src/misc.rs: -------------------------------------------------------------------------------- 1 | fn fourier_transform(polynomial: &mut [f64], n: usize) -> *mut [f64] { 2 | // Fourier transform of Polynomial with degree n 3 | // n is assumed to be a power of 2 4 | 5 | let mut even = (0..n).steb_by(2).map(|i| polynomial[i]).collect::>(); 6 | let mut odd = (1..n).steb_by(2).map(|i| polynomial[i]).collect::>(); 7 | 8 | let list1 = fourier_transform(&mut even, n/2); 9 | let list2 = fourier_transform(&mut odd, n/2); 10 | for j in 0..n { 11 | let z = pow(e, 2*i*PI*j/n); // imaginary 12 | k = j % (n/2); 13 | polynomial[j] = list1[k] + z*list2[k]; 14 | } 15 | 16 | return polynomial 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | pub use super::bag::Bag; 2 | 3 | pub use super::stack::Stack; 4 | 5 | pub use super::queue::Queue; 6 | 7 | pub use super::deque::Deque; 8 | 9 | pub use super::graph::Graph; 10 | 11 | pub use super::graph::Digraph; 12 | 13 | pub use super::priority_queue::{IndexMinPQ, MaxPQ, MinPQ}; 14 | 15 | pub use super::tries::TernarySearchTrie; 16 | 17 | pub use super::rope::{IntoRope, Rope}; 18 | 19 | pub use super::skip_list::SkipList; 20 | 21 | pub use super::rbtree::RedBlackBST; 22 | 23 | pub use super::union_find::UnionFind; 24 | -------------------------------------------------------------------------------- /src/primitive.rs: -------------------------------------------------------------------------------- 1 | use super::rbtree::RedBlackBST; 2 | use rand::distributions::{Distribution, Standard}; 3 | use rand::Rng; 4 | use std::borrow::Borrow; 5 | use std::f64; 6 | use std::fmt; 7 | use std::vec::IntoIter; 8 | 9 | #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] 10 | pub struct Point2D { 11 | pub x: f64, 12 | pub y: f64, 13 | } 14 | 15 | impl Point2D { 16 | pub fn new(x: f64, y: f64) -> Point2D { 17 | Point2D { x: x, y: y } 18 | } 19 | 20 | pub fn distance_to>(&self, that: T) -> f64 { 21 | self.distance_squared_to(that).sqrt() 22 | } 23 | 24 | pub fn distance_squared_to>(&self, that: T) -> f64 { 25 | (self.x - that.borrow().x).powi(2) + (self.y - that.borrow().y).powi(2) 26 | } 27 | } 28 | 29 | impl fmt::Display for Point2D { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | write!(f, "({}, {})", self.x, self.y) 32 | } 33 | } 34 | 35 | impl Distribution for Standard { 36 | #[inline] 37 | fn sample(&self, rng: &mut R) -> Point2D { 38 | Point2D { 39 | x: rng.gen(), 40 | y: rng.gen(), 41 | } 42 | } 43 | } 44 | 45 | #[test] 46 | fn test_point2d() { 47 | let p1 = Point2D::new(0.0, 0.0); 48 | let p2 = Point2D::new(1.0, 1.0); 49 | 50 | // maybe bad :( 51 | assert_eq!(p1.distance_to(p2), (2.0f64).sqrt()); 52 | } 53 | 54 | #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] 55 | /// Implementation of 2D axis-aligned rectangle 56 | pub struct RectHV { 57 | pub xmin: f64, 58 | pub ymin: f64, 59 | pub xmax: f64, 60 | pub ymax: f64, 61 | } 62 | 63 | impl RectHV { 64 | pub fn new(xmin: f64, ymin: f64, xmax: f64, ymax: f64) -> RectHV { 65 | RectHV { 66 | xmin: xmin, 67 | ymin: ymin, 68 | xmax: xmax, 69 | ymax: ymax, 70 | } 71 | } 72 | 73 | pub fn width(&self) -> f64 { 74 | self.xmax - self.xmin 75 | } 76 | 77 | pub fn height(&self) -> f64 { 78 | self.ymax - self.ymin 79 | } 80 | 81 | pub fn contains>(&self, p: T) -> bool { 82 | let p = p.borrow(); 83 | p.x >= self.xmin && p.y >= self.ymin && p.x <= self.xmax && p.y <= self.ymax 84 | } 85 | 86 | /// does this axis-aligned rectangle intersect that one? 87 | pub fn intersects>(&self, that: T) -> bool { 88 | let that = that.borrow(); 89 | self.xmax >= that.xmin && self.ymax >= that.ymin && that.xmax >= self.xmin && that.ymax >= self.ymin 90 | } 91 | 92 | /// distance from p to closest point on this axis-aligned rectangle 93 | pub fn distance_to>(&self, p: T) -> f64 { 94 | self.distance_squared_to(p).sqrt() 95 | } 96 | 97 | /// distance squared from p to closest point on this axis-aligned rectangle 98 | pub fn distance_squared_to>(&self, p: T) -> f64 { 99 | let p = p.borrow(); 100 | let mut dx = 0.0; 101 | let mut dy = 0.0; 102 | if p.x < self.xmin { 103 | dx = p.x - self.xmin; 104 | } else if p.x > self.xmax { 105 | dx = p.x - self.xmax; 106 | } 107 | if p.y < self.ymin { 108 | dy = p.y - self.ymin; 109 | } else if p.y > self.ymax { 110 | dy = p.y - self.ymax; 111 | } 112 | dx.powi(2) + dy.powi(2) 113 | } 114 | } 115 | 116 | impl fmt::Display for RectHV { 117 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 118 | write!(f, "[{}, {}] x [{}, {}]", self.xmin, self.xmax, self.ymin, self.ymax) 119 | } 120 | } 121 | 122 | #[test] 123 | fn test_rect() { 124 | let r1 = RectHV::new(0.0, 0.0, 1.1, 1.1); 125 | let r2 = RectHV::new(1.2, 2.0, 3.1, 4.1); 126 | assert!(!r1.intersects(r2)); 127 | } 128 | 129 | /// Represents a set of points in the unit square 130 | /// implemented using `RedBlackBST` 131 | pub struct PointSet { 132 | pset: RedBlackBST, 133 | } 134 | 135 | impl Default for PointSet { 136 | fn default() -> Self { 137 | Self::new() 138 | } 139 | } 140 | 141 | impl PointSet { 142 | pub fn new() -> PointSet { 143 | PointSet { 144 | pset: RedBlackBST::new(), 145 | } 146 | } 147 | 148 | pub fn size(&self) -> usize { 149 | self.pset.size() 150 | } 151 | 152 | pub fn insert(&mut self, p: Point2D) { 153 | if !self.pset.contains(&p) { 154 | self.pset.put(p, ()) 155 | } 156 | } 157 | 158 | pub fn contains>(&self, p: T) -> bool { 159 | self.pset.contains(p.borrow()) 160 | } 161 | 162 | pub fn range_search>(&self, rect: T) -> IntoIter<&Point2D> { 163 | let mut result = Vec::new(); 164 | for p in self.pset.keys() { 165 | if rect.borrow().contains(p) { 166 | result.push(p); 167 | } 168 | } 169 | result.into_iter() 170 | } 171 | 172 | pub fn range_count>(&self, rect: T) -> usize { 173 | self.range_search(rect).count() 174 | } 175 | 176 | pub fn nearest>(&self, p: T) -> Option<&Point2D> { 177 | let mut min_distance = f64::MAX; 178 | let mut result = None; 179 | for q in self.pset.keys() { 180 | let dist = p.borrow().distance_to(q); 181 | if dist < min_distance { 182 | result = Some(q); 183 | min_distance = dist; 184 | } 185 | } 186 | result 187 | } 188 | } 189 | 190 | #[test] 191 | fn test_point_set() { 192 | use rand::thread_rng; 193 | 194 | let mut rng = thread_rng(); 195 | let mut ps = PointSet::new(); 196 | for _ in 0..100 { 197 | ps.insert(rng.gen()) 198 | } 199 | assert_eq!(ps.size(), 100); 200 | 201 | assert!(ps.nearest(Point2D::new(0.5, 0.5)).is_some()); 202 | assert!(ps.range_search(RectHV::new(0.1, 0.1, 0.9, 0.9)).count() > 0); 203 | } 204 | -------------------------------------------------------------------------------- /src/priority_queue/binary_heaps.rs: -------------------------------------------------------------------------------- 1 | const INITIAL_SIZE: usize = 1; 2 | 3 | /// Generic max priority queue implementation with a binary heap 4 | pub struct MaxPQ { 5 | pq: Vec>, 6 | n: usize, 7 | } 8 | 9 | impl MaxPQ { 10 | fn with_capacity(capacity: usize) -> MaxPQ { 11 | let mut pq = Vec::with_capacity(capacity + 1); 12 | for _ in 0..capacity + 1 { 13 | pq.push(None); 14 | } 15 | MaxPQ { pq: pq, n: 0 } 16 | } 17 | 18 | fn resize(&mut self, capacity: usize) { 19 | assert!(capacity > self.n); 20 | let mut temp = Vec::with_capacity(capacity); 21 | for i in 0..capacity { 22 | if i >= 1 && i <= self.n { 23 | temp.push(self.pq[i].take()); 24 | } else { 25 | temp.push(None); 26 | } 27 | } 28 | self.pq = temp; 29 | } 30 | 31 | fn swim(&mut self, k: usize) { 32 | let mut k = k; 33 | while k > 1 && self.pq[k / 2] < self.pq[k] { 34 | self.pq.swap(k, k / 2); 35 | k /= 2; 36 | } 37 | } 38 | 39 | fn sink(&mut self, k: usize) { 40 | let mut k = k; 41 | while 2 * k <= self.n { 42 | let mut j = 2 * k; 43 | if j < self.n && self.pq[j] < self.pq[j + 1] { 44 | j += 1; 45 | } 46 | if self.pq[k] >= self.pq[j] { 47 | break; 48 | } 49 | self.pq.swap(k, j); 50 | k = j; 51 | } 52 | } 53 | } 54 | 55 | impl MaxPQ { 56 | /// create an empty priority queue 57 | pub fn new() -> Self { 58 | MaxPQ::with_capacity(INITIAL_SIZE) 59 | } 60 | 61 | /// create a priority queue with given keys 62 | pub fn from_vec(a: Vec) -> Self { 63 | let mut pq = Self::new(); 64 | for i in a { 65 | pq.insert(i); 66 | } 67 | pq 68 | } 69 | 70 | /// insert a key into the priority queue 71 | pub fn insert(&mut self, x: Key) { 72 | let len = self.pq.len(); 73 | if self.n == len - 1 { 74 | self.resize(2 * len); 75 | } 76 | self.n += 1; 77 | let n = self.n; 78 | self.pq[n] = Some(x); 79 | self.swim(n); 80 | } 81 | 82 | /// return and remove the largest key 83 | pub fn del_max(&mut self) -> Option { 84 | let max = self.pq[1].take(); 85 | self.pq.swap(1, self.n); 86 | self.n -= 1; 87 | self.sink(1); 88 | let len = self.pq.len(); 89 | if self.n > 0 && self.n == (len - 1) / 4 { 90 | self.resize(len / 2); 91 | } 92 | max 93 | } 94 | 95 | /// is the priority queue empty? 96 | #[inline] 97 | pub fn is_empty(&self) -> bool { 98 | self.n == 0 99 | } 100 | 101 | /// return the largest key 102 | pub fn max(&self) -> Option<&Key> { 103 | self.pq[1].as_ref() 104 | } 105 | 106 | /// number of entries in the priority queue 107 | #[inline] 108 | pub fn size(&self) -> usize { 109 | self.n 110 | } 111 | } 112 | 113 | /// Generic min priority queue implementation with a binary heap 114 | pub struct MinPQ { 115 | pq: Vec>, 116 | n: usize, 117 | } 118 | 119 | impl MinPQ { 120 | fn with_capacity(capacity: usize) -> MinPQ { 121 | let mut pq = Vec::with_capacity(capacity + 1); 122 | for _ in 0..capacity + 1 { 123 | pq.push(None); 124 | } 125 | MinPQ { pq: pq, n: 0 } 126 | } 127 | 128 | fn resize(&mut self, capacity: usize) { 129 | assert!(capacity > self.n); 130 | let mut temp = Vec::with_capacity(capacity); 131 | for i in 0..capacity { 132 | if i >= 1 && i <= self.n { 133 | temp.push(self.pq[i].take()); 134 | } else { 135 | temp.push(None); 136 | } 137 | } 138 | self.pq = temp; 139 | } 140 | 141 | fn swim(&mut self, k: usize) { 142 | let mut k = k; 143 | while k > 1 && self.pq[k / 2] > self.pq[k] { 144 | self.pq.swap(k, k / 2); 145 | k /= 2; 146 | } 147 | } 148 | 149 | fn sink(&mut self, k: usize) { 150 | let mut k = k; 151 | while 2 * k <= self.n { 152 | let mut j = 2 * k; 153 | if j < self.n && self.pq[j] > self.pq[j + 1] { 154 | j += 1; 155 | } 156 | if self.pq[k] <= self.pq[j] { 157 | break; 158 | } 159 | self.pq.swap(k, j); 160 | k = j; 161 | } 162 | } 163 | } 164 | 165 | impl MinPQ { 166 | /// create an empty priority queue 167 | pub fn new() -> Self { 168 | MinPQ::with_capacity(INITIAL_SIZE) 169 | } 170 | 171 | /// create a priority queue with given keys 172 | pub fn from_vec(a: Vec) -> Self { 173 | let mut pq = Self::new(); 174 | for i in a { 175 | pq.insert(i); 176 | } 177 | pq 178 | } 179 | 180 | /// insert a key into the priority queue 181 | pub fn insert(&mut self, x: Key) { 182 | let len = self.pq.len(); 183 | if self.n == len - 1 { 184 | self.resize(2 * len); 185 | } 186 | self.n += 1; 187 | let n = self.n; 188 | self.pq[n] = Some(x); 189 | self.swim(n); 190 | } 191 | 192 | /// return and remove the smallest key 193 | pub fn del_min(&mut self) -> Option { 194 | let min = self.pq[1].take(); 195 | self.pq.swap(1, self.n); 196 | self.n -= 1; 197 | self.sink(1); 198 | let len = self.pq.len(); 199 | if self.n > 0 && self.n == (len - 1) / 4 { 200 | self.resize(len / 2); 201 | } 202 | min 203 | } 204 | 205 | /// is the priority queue empty? 206 | #[inline] 207 | pub fn is_empty(&self) -> bool { 208 | self.n == 0 209 | } 210 | 211 | /// return the smallest key 212 | pub fn min(&self) -> Option<&Key> { 213 | self.pq[1].as_ref() 214 | } 215 | 216 | /// number of entries in the priority queue 217 | pub fn size(&self) -> usize { 218 | self.n 219 | } 220 | } 221 | 222 | #[test] 223 | fn test_binary_heap_min_priority_queue() { 224 | let mut pq: MinPQ = MinPQ::new(); 225 | 226 | pq.insert('P'); 227 | pq.insert('Q'); 228 | pq.insert('E'); 229 | 230 | assert_eq!(pq.size(), 3); 231 | assert_eq!(pq.del_min().unwrap(), 'E'); 232 | assert_eq!(pq.size(), 2); 233 | 234 | pq.insert('X'); 235 | pq.insert('A'); 236 | pq.insert('M'); 237 | 238 | assert_eq!(pq.del_min().unwrap(), 'A'); 239 | 240 | pq.insert('P'); 241 | pq.insert('L'); 242 | pq.insert('B'); 243 | 244 | assert_eq!(pq.del_min().unwrap(), 'B'); 245 | 246 | assert_eq!(pq.size(), 6); 247 | } 248 | 249 | #[test] 250 | fn test_binary_heap_max_priority_queue() { 251 | let mut pq: MaxPQ = MaxPQ::new(); 252 | 253 | pq.insert('P'); 254 | pq.insert('Q'); 255 | pq.insert('E'); 256 | 257 | assert_eq!(pq.size(), 3); 258 | assert_eq!(pq.del_max().unwrap(), 'Q'); 259 | assert_eq!(pq.size(), 2); 260 | 261 | pq.insert('X'); 262 | pq.insert('A'); 263 | pq.insert('M'); 264 | 265 | assert_eq!(pq.del_max().unwrap(), 'X'); 266 | 267 | pq.insert('P'); 268 | pq.insert('L'); 269 | pq.insert('E'); 270 | 271 | assert_eq!(pq.del_max().unwrap(), 'P'); 272 | 273 | assert_eq!(pq.size(), 6); 274 | } 275 | 276 | #[test] 277 | fn test_empty_binary_heap() { 278 | let mut pq: MaxPQ = MaxPQ::new(); 279 | pq.insert('P'); 280 | assert_eq!(pq.is_empty(), false); 281 | assert_eq!(pq.size(), 1); 282 | pq.del_max(); 283 | assert_eq!(pq.size(), 0); 284 | assert_eq!(pq.is_empty(), true); 285 | } 286 | -------------------------------------------------------------------------------- /src/priority_queue/index_pq.rs: -------------------------------------------------------------------------------- 1 | use std::iter; 2 | use std::usize; 3 | 4 | pub struct IndexMinPQ { 5 | nmax: usize, 6 | n: usize, 7 | pq: Vec, 8 | qp: Vec, 9 | keys: Vec>, 10 | } 11 | 12 | impl IndexMinPQ { 13 | pub fn with_capacity(nmax: usize) -> IndexMinPQ { 14 | let mut keys = Vec::new(); 15 | for _ in 0..nmax + 1 { 16 | keys.push(None); 17 | } 18 | IndexMinPQ { 19 | nmax: nmax, 20 | n: 0, 21 | pq: iter::repeat(0).take(nmax + 1).collect(), 22 | qp: iter::repeat(usize::MAX).take(nmax + 1).collect(), 23 | keys: keys, 24 | } 25 | } 26 | 27 | pub fn is_empty(&self) -> bool { 28 | self.n == 0 29 | } 30 | 31 | pub fn contains(&self, i: usize) -> bool { 32 | assert!(i < self.nmax, "index out of bounds"); 33 | self.qp[i] != usize::MAX 34 | } 35 | 36 | pub fn size(&self) -> usize { 37 | self.n 38 | } 39 | 40 | // Associates key with index i 41 | pub fn insert(&mut self, i: usize, key: T) { 42 | assert!(i < self.nmax, "index out of bounds"); 43 | if self.contains(i) { 44 | panic!("index already in pq"); 45 | } 46 | self.n += 1; 47 | self.qp[i] = self.n; 48 | self.pq[self.n] = i; 49 | self.keys[i] = Some(key); 50 | let n = self.n; 51 | self.swim(n) 52 | } 53 | 54 | pub fn min_index(&self) -> usize { 55 | assert!(self.n != 0, "priority queue underflow"); 56 | self.pq[1] 57 | } 58 | 59 | pub fn min_key(&self) -> Option<&T> { 60 | if self.n == 0 { 61 | None 62 | } else { 63 | self.keys[self.pq[1]].as_ref() 64 | } 65 | } 66 | 67 | pub fn del_min(&mut self) -> Option { 68 | if self.n == 0 { 69 | None 70 | } else { 71 | let min = self.pq[1]; 72 | let n = self.n; 73 | self.exch(1, n); 74 | self.n -= 1; 75 | self.sink(1); 76 | self.qp[min] = usize::MAX; // delete 77 | // help with gc 78 | self.keys[self.pq[self.n + 1]] = None; 79 | self.pq[self.n + 1] = usize::MAX; 80 | Some(min) 81 | } 82 | } 83 | 84 | pub fn key_of(&self, i: usize) -> Option<&T> { 85 | if i >= self.nmax || !self.contains(i) { 86 | None 87 | } else { 88 | self.keys[i].as_ref() 89 | } 90 | } 91 | 92 | pub fn change_key(&mut self, i: usize, key: T) { 93 | if i >= self.nmax || !self.contains(i) { 94 | panic!("blah...."); 95 | } 96 | self.keys[i] = Some(key); 97 | let p = self.qp[i]; 98 | self.swim(p); 99 | let p = self.qp[i]; 100 | self.sink(p); 101 | } 102 | 103 | pub fn decrease_key(&mut self, i: usize, key: T) { 104 | if i >= self.nmax || !self.contains(i) { 105 | panic!("decrease_key"); 106 | } 107 | self.keys[i] = Some(key); 108 | let p = self.qp[i]; 109 | self.swim(p); 110 | } 111 | 112 | pub fn increase_key(&mut self, i: usize, key: T) { 113 | if i >= self.nmax || !self.contains(i) { 114 | panic!("increase_key"); 115 | } 116 | self.keys[i] = Some(key); 117 | let p = self.qp[i]; 118 | self.sink(p); 119 | } 120 | 121 | pub fn delete(&mut self, i: usize) { 122 | if i >= self.nmax || !self.contains(i) { 123 | panic!("delete"); 124 | } 125 | let index = self.qp[i]; 126 | let n = self.n; 127 | self.exch(index, n); 128 | self.n -= 1; 129 | self.swim(index); 130 | self.sink(index); 131 | self.keys[i] = None; 132 | self.qp[i] = usize::MAX; 133 | } 134 | 135 | #[inline] 136 | fn greater(&self, i: usize, j: usize) -> bool { 137 | self.keys[self.pq[i]] > self.keys[self.pq[j]] 138 | } 139 | 140 | fn exch(&mut self, i: usize, j: usize) { 141 | self.pq.swap(i, j); 142 | self.qp.swap(self.pq[i], self.pq[j]); 143 | } 144 | 145 | fn swim(&mut self, k: usize) { 146 | let mut k = k; 147 | while k > 1 && self.greater(k / 2, k) { 148 | self.exch(k, k / 2); 149 | k /= 2; 150 | } 151 | } 152 | 153 | fn sink(&mut self, k: usize) { 154 | let mut k = k; 155 | while 2 * k <= self.n { 156 | let mut j = 2 * k; 157 | if j < self.n && self.greater(j, j + 1) { 158 | j += 1; 159 | } 160 | if !self.greater(k, j) { 161 | break; 162 | } 163 | self.exch(k, j); 164 | k = j; 165 | } 166 | } 167 | } 168 | 169 | #[test] 170 | fn test_index_min_pq() { 171 | let strings = vec!["it", "was", "the", "best", "of", "times", "it", "was", "the", "worst"]; 172 | let mut pq = IndexMinPQ::with_capacity(strings.len()); 173 | 174 | for (i, s) in strings.iter().enumerate() { 175 | pq.insert(i, s); 176 | } 177 | 178 | while !pq.is_empty() { 179 | let i = pq.del_min().unwrap(); 180 | assert!(!strings[i].is_empty()); 181 | } 182 | 183 | for (i, s) in strings.iter().enumerate() { 184 | pq.insert(i, s); 185 | } 186 | 187 | while !pq.is_empty() { 188 | pq.del_min(); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/priority_queue/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod binary_heaps; 2 | pub mod index_pq; 3 | 4 | pub use self::binary_heaps::{MaxPQ, MinPQ}; 5 | pub use self::index_pq::IndexMinPQ; 6 | -------------------------------------------------------------------------------- /src/queue.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | use std::ptr; 3 | 4 | struct Rawlink { 5 | p: *mut T, 6 | } 7 | 8 | impl Rawlink { 9 | fn none() -> Rawlink { 10 | Rawlink { p: ptr::null_mut() } 11 | } 12 | 13 | fn some(n: &mut T) -> Rawlink { 14 | Rawlink { p: n } 15 | } 16 | 17 | fn take(&mut self) -> Rawlink { 18 | mem::replace(self, Rawlink::none()) 19 | } 20 | } 21 | 22 | struct Node { 23 | val: T, 24 | next: Option>>, 25 | } 26 | 27 | impl Node { 28 | /// work around for moved value 29 | fn into_val_and_next(self) -> (T, Option>>) { 30 | (self.val, self.next) 31 | } 32 | 33 | fn len(&self) -> usize { 34 | self.next.as_ref().map_or(1, |n| 1 + n.len()) 35 | } 36 | } 37 | 38 | impl Clone for Node { 39 | fn clone(&self) -> Self { 40 | Node { 41 | val: self.val.clone(), 42 | next: self.next.clone(), 43 | } 44 | } 45 | } 46 | 47 | pub struct Queue { 48 | first: Option>>, 49 | last: Rawlink>, 50 | } 51 | 52 | impl Clone for Queue { 53 | fn clone(&self) -> Self { 54 | let mut first = self.first.clone(); 55 | let last = { 56 | let mut p = first.as_mut(); 57 | while p.as_ref().map_or(false, |n| n.next.is_some()) { 58 | p = p.unwrap().next.as_mut(); 59 | } 60 | p.map_or_else(Rawlink::none, |n| Rawlink::some(&mut **n)) 61 | }; 62 | Queue { 63 | first: first, 64 | last: last, 65 | } 66 | } 67 | } 68 | 69 | impl Queue { 70 | pub fn new() -> Queue { 71 | Queue { 72 | first: None, 73 | last: Rawlink::none(), 74 | } 75 | } 76 | 77 | pub fn is_empty(&self) -> bool { 78 | self.first.is_none() 79 | } 80 | 81 | pub fn enqueue(&mut self, val: T) { 82 | let old_last = &self.last.take(); 83 | let mut last = Box::new(Node { val: val, next: None }); 84 | self.last = Rawlink::some(&mut last); 85 | if self.is_empty() { 86 | self.first = Some(last) 87 | } else { 88 | unsafe { (*old_last.p).next = Some(last) } 89 | } 90 | } 91 | 92 | pub fn dequeue(&mut self) -> Option { 93 | if self.first.is_none() { 94 | return None; 95 | } 96 | let old_first = self.first.take(); 97 | let (val, first) = old_first.unwrap().into_val_and_next(); 98 | self.first = first; 99 | if self.first.is_none() { 100 | self.last = Rawlink::none() 101 | } 102 | Some(val) 103 | } 104 | 105 | pub fn peek(&self) -> Option<&T> { 106 | self.first.as_ref().map(|n| &(*n).val) 107 | } 108 | 109 | pub fn peek_mut(&mut self) -> Option<&mut T> { 110 | self.first.as_mut().map(|n| &mut (*n).val) 111 | } 112 | 113 | pub fn len(&self) -> usize { 114 | self.first.as_ref().map_or(0, |n| n.len()) 115 | } 116 | } 117 | 118 | pub struct IntoIter { 119 | queue: Queue, 120 | } 121 | 122 | impl Iterator for IntoIter { 123 | type Item = T; 124 | 125 | fn next(&mut self) -> Option { 126 | self.queue.dequeue() 127 | } 128 | 129 | fn size_hint(&self) -> (usize, Option) { 130 | let length = self.queue.len(); 131 | (length, Some(length)) 132 | } 133 | } 134 | 135 | impl IntoIterator for Queue { 136 | type Item = T; 137 | type IntoIter = IntoIter; 138 | 139 | fn into_iter(self) -> Self::IntoIter { 140 | IntoIter { queue: self } 141 | } 142 | } 143 | 144 | pub struct Iter<'a, T> 145 | where 146 | T: 'a, 147 | { 148 | node: Option<&'a Box>>, 149 | } 150 | 151 | impl<'a, T> Iterator for Iter<'a, T> { 152 | type Item = &'a T; 153 | 154 | fn next(&mut self) -> Option<&'a T> { 155 | let ret = self.node.map(|n| &n.val); 156 | self.node = self.node.map_or(None, |n| n.next.as_ref()); 157 | ret 158 | } 159 | 160 | // Bad 161 | fn size_hint(&self) -> (usize, Option) { 162 | let mut sz = 0; 163 | let mut p = self.node; 164 | while p.is_some() { 165 | p = p.map_or(None, |n| n.next.as_ref()); 166 | sz += 1; 167 | } 168 | (sz, Some(sz)) 169 | } 170 | } 171 | 172 | impl<'a, T> ExactSizeIterator for Iter<'a, T> { 173 | fn len(&self) -> usize { 174 | self.size_hint().0 175 | } 176 | } 177 | 178 | impl Queue { 179 | pub fn iter(&self) -> Iter { 180 | Iter { 181 | node: self.first.as_ref(), 182 | } 183 | } 184 | } 185 | 186 | #[test] 187 | fn test_queue() { 188 | let mut queue = Queue::<&str>::new(); 189 | assert!(queue.is_empty()); 190 | assert_eq!(queue.len(), 0); 191 | 192 | assert_eq!(queue.peek(), None); 193 | 194 | queue.enqueue("welcome"); 195 | queue.enqueue("to"); 196 | queue.enqueue("china"); 197 | assert!(!queue.is_empty()); 198 | assert_eq!(queue.len(), 3); 199 | 200 | assert_eq!(queue.peek(), Some(&"welcome")); 201 | queue.peek_mut().map(|val| *val = "go"); 202 | assert_eq!(queue.peek(), Some(&"go")); 203 | } 204 | 205 | #[test] 206 | fn test_queue_clone() { 207 | let mut queue1 = Queue::<&str>::new(); 208 | queue1.enqueue("welcome"); 209 | queue1.enqueue("to"); 210 | queue1.enqueue("china"); 211 | 212 | let mut queue2 = queue1.clone(); 213 | queue2.dequeue(); 214 | assert_eq!(queue1.peek(), Some(&"welcome")); 215 | assert_eq!(queue2.peek(), Some(&"to")); 216 | 217 | queue2.dequeue(); 218 | queue2.dequeue(); 219 | queue2.enqueue("beijing"); 220 | 221 | assert_eq!(queue1.peek(), Some(&"welcome")); 222 | assert_eq!(queue2.peek(), Some(&"beijing")); 223 | } 224 | 225 | #[test] 226 | fn test_queue_into_iter() { 227 | let mut queue = Queue::<&str>::new(); 228 | queue.enqueue("welcome"); 229 | queue.enqueue("to"); 230 | queue.enqueue("china"); 231 | 232 | let result = vec!["welcome", "to", "china"]; 233 | for i in queue { 234 | assert!(result.contains(&i)); 235 | } 236 | } 237 | 238 | #[test] 239 | fn test_queue_iter() { 240 | let mut queue = Queue::<&str>::new(); 241 | queue.enqueue("welcome"); 242 | queue.enqueue("to"); 243 | queue.enqueue("china"); 244 | 245 | let mut rit = vec!["welcome", "to", "china"].into_iter(); 246 | for i in queue.iter() { 247 | assert_eq!(i, &rit.next().unwrap()) 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /src/rbtree.rs: -------------------------------------------------------------------------------- 1 | use self::Color::*; 2 | use std::cmp::Ordering; 3 | use std::fmt; 4 | use std::iter; 5 | use std::mem; 6 | 7 | fn max(a: T, b: T) -> T { 8 | if a >= b { 9 | a 10 | } else { 11 | b 12 | } 13 | } 14 | 15 | // fn min(a: T, b: T) -> T { 16 | // if a >= b { 17 | // b 18 | // } else { 19 | // a 20 | // } 21 | // } 22 | 23 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 24 | pub enum Color { 25 | Red, 26 | Black, 27 | } 28 | 29 | pub type NodeCell = Option>>; 30 | 31 | pub struct Node { 32 | pub key: K, 33 | pub val: V, 34 | pub left: Option>>, 35 | pub right: Option>>, 36 | pub color: Color, 37 | } 38 | 39 | impl Node { 40 | #[inline] 41 | pub fn new(key: K, val: V, color: Color) -> Node { 42 | Node { 43 | key: key, 44 | val: val, 45 | left: None, 46 | right: None, 47 | color: color, 48 | } 49 | } 50 | 51 | #[inline] 52 | fn is_red(&self) -> bool { 53 | self.color == Red 54 | } 55 | 56 | fn depth(&self) -> usize { 57 | let lsz = self.left.as_ref().map_or(0, |n| n.depth()); 58 | let rsz = self.right.as_ref().map_or(0, |n| n.depth()); 59 | max(lsz, rsz) + 1 60 | } 61 | 62 | fn size(&self) -> usize { 63 | 1 + self.left.as_ref().map_or(0, |n| n.size()) + self.right.as_ref().map_or(0, |n| n.size()) 64 | } 65 | 66 | /// Left rotation. Orient a (temporarily) right-leaning red link to lean left. 67 | fn rotate_left(&mut self) { 68 | assert!(is_red(&self.right)); 69 | let mut x = self.right.take(); 70 | self.right = x.as_mut().unwrap().left.take(); 71 | x.as_mut().unwrap().color = self.color; 72 | self.color = Red; 73 | let old_self = mem::replace(self, *x.unwrap()); 74 | self.left = Some(Box::new(old_self)); 75 | } 76 | 77 | /// Right rotation. Orient a left-leaning red link to (temporarily) lean right 78 | fn rotate_right(&mut self) { 79 | assert!(is_red(&self.left)); 80 | let mut x = self.left.take(); 81 | self.left = x.as_mut().unwrap().right.take(); 82 | x.as_mut().unwrap().color = self.color; 83 | self.color = Red; 84 | let old_self = mem::replace(self, *x.unwrap()); 85 | self.right = Some(Box::new(old_self)); 86 | } 87 | 88 | /// Color flip. Recolor to split a (temporary) 4-node. 89 | fn flip_color(&mut self) { 90 | assert!(!self.is_red()); 91 | assert!(is_red(&self.left)); 92 | assert!(is_red(&self.right)); 93 | self.color = Red; 94 | self.left.as_mut().map(|n| n.color = Black); 95 | self.right.as_mut().map(|n| n.color = Black); 96 | } 97 | } 98 | 99 | impl Node { 100 | fn dump(&self, depth: usize, f: &mut fmt::Formatter, symbol: char) { 101 | if depth == 0 { 102 | writeln!(f, "\n{:?}[{:?}]", self.key, self.val).unwrap(); 103 | } else if self.is_red() { 104 | writeln!( 105 | f, 106 | "{}{}=={:?}[{:?}]", 107 | iter::repeat("| ").take(depth - 1).collect::>().concat(), 108 | symbol, 109 | self.key, 110 | self.val 111 | ) 112 | .unwrap(); 113 | } else { 114 | writeln!( 115 | f, 116 | "{}{}--{:?}[{:?}]", 117 | iter::repeat("| ").take(depth - 1).collect::>().concat(), 118 | symbol, 119 | self.key, 120 | self.val 121 | ) 122 | .unwrap(); 123 | } 124 | if self.left.is_some() { 125 | self.left.as_ref().unwrap().dump(depth + 1, f, '+'); 126 | } 127 | if self.right.is_some() { 128 | self.right.as_ref().unwrap().dump(depth + 1, f, '`'); 129 | } 130 | } 131 | } 132 | 133 | fn is_red(x: &NodeCell) -> bool { 134 | if x.as_ref().is_none() { 135 | false 136 | } else { 137 | x.as_ref().unwrap().color == Red 138 | } 139 | } 140 | 141 | fn put(mut x: NodeCell, key: K, val: V) -> NodeCell { 142 | if x.is_none() { 143 | return Some(Box::new(Node::new(key, val, Red))); 144 | } 145 | let cmp = key.partial_cmp(&x.as_ref().unwrap().key).unwrap(); 146 | match cmp { 147 | Ordering::Less => { 148 | let left = x.as_mut().unwrap().left.take(); 149 | x.as_mut().unwrap().left = put(left, key, val) 150 | } 151 | Ordering::Greater => { 152 | let right = x.as_mut().unwrap().right.take(); 153 | x.as_mut().unwrap().right = put(right, key, val) 154 | } 155 | Ordering::Equal => x.as_mut().unwrap().val = val, 156 | } 157 | 158 | if is_red(&x.as_ref().unwrap().right) && !is_red(&x.as_ref().unwrap().left) { 159 | x.as_mut().unwrap().rotate_left(); 160 | } 161 | if is_red(&x.as_ref().unwrap().left) && is_red(&x.as_ref().unwrap().left.as_ref().unwrap().left) { 162 | x.as_mut().unwrap().rotate_right(); 163 | } 164 | if is_red(&x.as_ref().unwrap().left) && is_red(&x.as_ref().unwrap().right) { 165 | x.as_mut().unwrap().flip_color(); 166 | } 167 | x 168 | } 169 | 170 | fn delete(mut x: NodeCell, key: &K) -> NodeCell { 171 | if x.is_none() { 172 | return None; 173 | } 174 | 175 | match key.partial_cmp(&x.as_ref().unwrap().key).unwrap() { 176 | Ordering::Less => { 177 | let left = x.as_mut().unwrap().left.take(); 178 | x.as_mut().unwrap().left = delete(left, key); 179 | x 180 | } 181 | Ordering::Greater => { 182 | let right = x.as_mut().unwrap().right.take(); 183 | x.as_mut().unwrap().right = delete(right, key); 184 | x 185 | } 186 | Ordering::Equal => { 187 | if x.as_ref().unwrap().right.is_none() { 188 | return x.as_mut().unwrap().left.take(); 189 | } 190 | if x.as_ref().unwrap().left.is_none() { 191 | return x.as_mut().unwrap().right.take(); 192 | } 193 | 194 | // Save top 195 | let mut t = x; 196 | 197 | // split right into right without min, and the min 198 | let (right, right_min) = delete_min(t.as_mut().unwrap().right.take()); 199 | x = right_min; 200 | x.as_mut().unwrap().right = right; 201 | x.as_mut().unwrap().left = t.as_mut().unwrap().left.take(); 202 | x 203 | } 204 | } 205 | } 206 | 207 | pub struct RedBlackBST { 208 | pub root: Option>>, 209 | } 210 | 211 | impl RedBlackBST { 212 | pub fn depth(&self) -> usize { 213 | match self.root { 214 | None => 0, 215 | Some(ref x) => x.depth(), 216 | } 217 | } 218 | } 219 | 220 | impl RedBlackBST { 221 | pub fn new() -> RedBlackBST { 222 | RedBlackBST { root: None } 223 | } 224 | 225 | pub fn contains(&self, key: &K) -> bool { 226 | self.get(key).is_some() 227 | } 228 | 229 | pub fn get(&self, key: &K) -> Option<&V> { 230 | let mut x = self.root.as_ref(); 231 | while x.is_some() { 232 | match key.partial_cmp(&x.unwrap().key).unwrap() { 233 | Ordering::Less => { 234 | x = x.unwrap().left.as_ref(); 235 | } 236 | Ordering::Greater => { 237 | x = x.unwrap().right.as_ref(); 238 | } 239 | Ordering::Equal => return Some(&x.unwrap().val), 240 | } 241 | } 242 | None 243 | } 244 | 245 | pub fn put(&mut self, key: K, val: V) { 246 | self.root = put(self.root.take(), key, val); 247 | // FIXME: too bad 248 | self.root.as_mut().unwrap().color = Black; 249 | } 250 | 251 | pub fn delete(&mut self, key: &K) { 252 | self.root = delete(self.root.take(), key); 253 | } 254 | 255 | pub fn is_empty(&self) -> bool { 256 | self.root.is_none() 257 | } 258 | 259 | /// number of key-value pairs in the table 260 | pub fn size(&self) -> usize { 261 | if self.is_empty() { 262 | 0 263 | } else { 264 | self.root.as_ref().unwrap().size() 265 | } 266 | } 267 | } 268 | 269 | fn floor<'a, K: PartialOrd, V>(x: Option<&'a Box>>, key: &K) -> Option<&'a Node> { 270 | if x.is_none() { 271 | return None; 272 | } 273 | 274 | match key.partial_cmp(&x.unwrap().key).unwrap() { 275 | Ordering::Equal => { 276 | return Some(&(**x.unwrap())); 277 | } 278 | Ordering::Less => { 279 | return floor(x.unwrap().left.as_ref(), key); 280 | } 281 | _ => (), 282 | } 283 | 284 | let t = floor(x.unwrap().right.as_ref(), key); 285 | if t.is_some() { 286 | t 287 | } else { 288 | Some(x.unwrap()) 289 | } 290 | } 291 | 292 | fn ceiling<'a, K: PartialOrd, V>(x: Option<&'a Box>>, key: &K) -> Option<&'a Node> { 293 | if x.is_none() { 294 | return None; 295 | } 296 | 297 | match key.partial_cmp(&x.unwrap().key).unwrap() { 298 | Ordering::Equal => { 299 | return Some(&(**x.unwrap())); 300 | } 301 | Ordering::Greater => { 302 | return ceiling(x.unwrap().right.as_ref(), key); 303 | } 304 | _ => (), 305 | } 306 | 307 | let t = ceiling(x.unwrap().left.as_ref(), key); 308 | if t.is_some() { 309 | t 310 | } else { 311 | Some(x.unwrap()) 312 | } 313 | } 314 | 315 | // delete_min helper 316 | // returns: top, deleted 317 | fn delete_min(mut x: NodeCell) -> (NodeCell, NodeCell) { 318 | if x.is_none() { 319 | return (None, None); 320 | } 321 | match x.as_mut().unwrap().left.take() { 322 | None => (x.as_mut().unwrap().right.take(), x), 323 | left @ Some(_) => { 324 | let (t, deleted) = delete_min(left); 325 | x.as_mut().unwrap().left = t; 326 | (x, deleted) 327 | } 328 | } 329 | } 330 | 331 | // delete_max helper 332 | // returns: top, deleted 333 | fn delete_max(mut x: NodeCell) -> (NodeCell, NodeCell) { 334 | if x.is_none() { 335 | return (None, None); 336 | } 337 | match x.as_mut().unwrap().right.take() { 338 | None => (x.as_mut().unwrap().left.take(), x), 339 | right @ Some(_) => { 340 | let (t, deleted) = delete_max(right); 341 | x.as_mut().unwrap().right = t; 342 | (x, deleted) 343 | } 344 | } 345 | } 346 | 347 | fn find_max(x: Option<&Box>>) -> Option<&Box>> { 348 | if x.is_none() { 349 | return None; 350 | } 351 | match x.as_ref().unwrap().right.as_ref() { 352 | None => x, 353 | right @ Some(_) => find_max(right), 354 | } 355 | } 356 | 357 | fn find_min(x: Option<&Box>>) -> Option<&Box>> { 358 | if x.is_none() { 359 | return None; 360 | } 361 | match x.as_ref().unwrap().left.as_ref() { 362 | None => x, 363 | left @ Some(_) => find_min(left), 364 | } 365 | } 366 | 367 | impl RedBlackBST { 368 | /// smallest key 369 | pub fn min(&self) -> Option<&K> { 370 | find_min(self.root.as_ref()).map(|n| &n.key) 371 | } 372 | 373 | /// largest key 374 | pub fn max(&self) -> Option<&K> { 375 | find_max(self.root.as_ref()).map(|n| &n.key) 376 | } 377 | 378 | /// largest key less than or equal to key 379 | pub fn floor(&self, key: &K) -> Option<&K> { 380 | let x = floor(self.root.as_ref(), key); 381 | if x.is_none() { 382 | None 383 | } else { 384 | Some(&x.unwrap().key) 385 | } 386 | } 387 | 388 | /// smallest key greater than or equal to key 389 | pub fn ceiling(&self, key: &K) -> Option<&K> { 390 | let x = ceiling(self.root.as_ref(), key); 391 | if x.is_none() { 392 | None 393 | } else { 394 | Some(&x.unwrap().key) 395 | } 396 | } 397 | 398 | /// number of keys less than key 399 | pub fn rank(&self, key: &K) -> usize { 400 | fn rank_helper(x: Option<&Box>>, key: &K) -> usize { 401 | if x.is_none() { 402 | return 0; 403 | } 404 | 405 | match key.partial_cmp(&x.unwrap().key).unwrap() { 406 | Ordering::Less => rank_helper(x.unwrap().left.as_ref(), key), 407 | Ordering::Greater => { 408 | 1 + x.as_ref().unwrap().left.as_ref().map_or(0, |n| n.size()) + 409 | rank_helper(x.unwrap().right.as_ref(), key) 410 | } 411 | Ordering::Equal => x.as_ref().unwrap().left.as_ref().map_or(0, |n| n.size()), 412 | } 413 | } 414 | 415 | rank_helper(self.root.as_ref(), key) 416 | } 417 | 418 | /// key of rank k 419 | pub fn select(&self, k: usize) -> Option<&K> { 420 | for key in self.keys() { 421 | if self.rank(key) == k { 422 | return Some(key); 423 | } 424 | } 425 | None 426 | } 427 | 428 | /// delete smallest key 429 | pub fn delete_min(&mut self) { 430 | self.root = delete_min(self.root.take()).0; 431 | } 432 | 433 | /// delete largest key 434 | pub fn delete_max(&mut self) { 435 | self.root = delete_max(self.root.take()).0; 436 | } 437 | } 438 | 439 | impl RedBlackBST { 440 | pub fn keys(&self) -> ::std::vec::IntoIter<&K> { 441 | fn inorder<'a, K, V>(x: Option<&'a Box>>, queue: &mut Vec<&'a K>) { 442 | if x.is_none() { 443 | return; 444 | } 445 | inorder(x.unwrap().left.as_ref(), queue); 446 | queue.push(&x.unwrap().key); 447 | inorder(x.unwrap().right.as_ref(), queue); 448 | }; 449 | let mut queue = Vec::new(); 450 | inorder(self.root.as_ref(), &mut queue); 451 | queue.into_iter() 452 | } 453 | } 454 | 455 | impl fmt::Debug for RedBlackBST { 456 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 457 | if self.root.is_none() { 458 | write!(f, "") 459 | } else { 460 | self.root.as_ref().unwrap().dump(0, f, ' '); 461 | Ok(()) 462 | } 463 | } 464 | } 465 | 466 | #[test] 467 | fn test_red_black_tree_shape() { 468 | let mut t = RedBlackBST::::new(); 469 | assert_eq!(0, t.depth()); 470 | for c in 0..255 { 471 | t.put(c, ()); 472 | } 473 | // println!("{:?}", t); 474 | assert_eq!(255, t.size()); 475 | // max for n=255 476 | assert!(t.depth() <= 8); 477 | } 478 | 479 | #[test] 480 | fn test_red_black_tree() { 481 | use std::iter::FromIterator; 482 | 483 | let mut t = RedBlackBST::::new(); 484 | for (i, c) in "SEARCHEXAMP".chars().enumerate() { 485 | t.put(c, i); 486 | } 487 | 488 | // println!("{:?}", t); 489 | assert_eq!(t.get(&'E'), Some(&6)); 490 | assert_eq!(t.floor(&'O'), Some(&'M')); 491 | assert_eq!(t.ceiling(&'Q'), Some(&'R')); 492 | assert_eq!(t.size(), 9); 493 | assert_eq!(t.rank(&'E'), 2); 494 | assert_eq!(t.select(2), Some(&'E')); 495 | assert_eq!(t.rank(&'M'), 4); 496 | assert_eq!(t.select(4), Some(&'M')); 497 | assert_eq!(t.max(), Some(&'X')); 498 | assert_eq!(t.min(), Some(&'A')); 499 | // inorder visite 500 | assert_eq!(String::from_iter(t.keys().map(|&c| c)), "ACEHMPRSX"); 501 | } 502 | -------------------------------------------------------------------------------- /src/rope/mod.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::ops; 3 | 4 | use self::Rope::*; 5 | 6 | fn max(x: T, y: T) -> T { 7 | if x >= y { 8 | x 9 | } else { 10 | y 11 | } 12 | } 13 | 14 | #[derive(Clone)] 15 | pub enum Rope { 16 | FlatCharVec { 17 | seq: Vec, 18 | }, 19 | Concatenation { 20 | left: Box, 21 | right: Box, 22 | depth: usize, 23 | length: usize, 24 | }, 25 | Reverse { 26 | rope: Box, 27 | }, 28 | SubString { 29 | rope: Box, 30 | offset: usize, 31 | length: usize, 32 | }, 33 | } 34 | 35 | fn write_rope_to_string(rope: &Rope, s: &mut String) { 36 | match *rope { 37 | FlatCharVec { ref seq } => { 38 | s.push_str(&seq.iter().cloned().collect::()); 39 | } 40 | Concatenation { 41 | ref left, ref right, .. 42 | } => { 43 | write_rope_to_string(left, s); 44 | write_rope_to_string(right, s); 45 | } 46 | Reverse { ref rope } => { 47 | let inner = rope.to_string(); 48 | s.push_str(&inner.chars().rev().collect::()); 49 | } 50 | SubString { 51 | ref rope, 52 | offset, 53 | length, 54 | } => { 55 | let inner = rope.to_string(); 56 | s.push_str(&inner[offset..offset + length]); 57 | } 58 | } 59 | } 60 | 61 | fn concatenate(left: Rope, right: Rope) -> Rope { 62 | const COMBINE_LENGTH: usize = 17; 63 | 64 | if left.is_empty() { 65 | return right; 66 | } 67 | if right.is_empty() { 68 | return left; 69 | } 70 | 71 | let length = left.len() + right.len(); 72 | if length < COMBINE_LENGTH { 73 | let mut lchs = left.into_chars(); 74 | lchs.extend(right.into_chars()); 75 | return FlatCharVec { seq: lchs }; 76 | } 77 | let depth = max(left.depth(), right.depth()) + 1; 78 | Concatenation { 79 | left: Box::new(left), 80 | right: Box::new(right), 81 | depth: depth, 82 | length: length, 83 | } 84 | } 85 | 86 | impl Rope { 87 | pub fn from_vec(seq: Vec) -> Rope { 88 | Rope::FlatCharVec { seq: seq } 89 | } 90 | 91 | pub fn len(&self) -> usize { 92 | match *self { 93 | FlatCharVec { ref seq } => seq.len(), 94 | Reverse { ref rope } => rope.len(), 95 | SubString { length, .. } | Concatenation { length, .. } => length, 96 | } 97 | } 98 | 99 | pub fn is_empty(&self) -> bool { 100 | self.len() == 0 101 | } 102 | 103 | pub fn depth(&self) -> usize { 104 | match *self { 105 | FlatCharVec { .. } => 0, 106 | Concatenation { depth, .. } => depth, 107 | Reverse { ref rope } | SubString { ref rope, .. } => rope.depth(), 108 | } 109 | } 110 | 111 | pub fn append(self, rhs: RHS) -> Self { 112 | concatenate(self, rhs.into_rope()) 113 | } 114 | 115 | pub fn to_string(&self) -> String { 116 | let mut s = String::new(); 117 | write_rope_to_string(self, &mut s); 118 | s 119 | } 120 | 121 | pub fn reverse(self) -> Self { 122 | match self { 123 | Reverse { rope } => *rope, 124 | Concatenation { left, right, .. } => concatenate(right.reverse(), left.reverse()), 125 | this => Reverse { rope: Box::new(this) }, 126 | } 127 | } 128 | 129 | pub fn char_ref(&self, idx: usize) -> Option<&char> { 130 | match *self { 131 | Concatenation { 132 | ref left, ref right, .. 133 | } => { 134 | let llen = left.len(); 135 | if idx < llen { 136 | left.char_ref(idx) 137 | } else if idx < llen + right.len() { 138 | right.char_ref(idx - llen) 139 | } else { 140 | None 141 | } 142 | } 143 | FlatCharVec { ref seq } => { 144 | if idx < seq.len() { 145 | Some(&seq[idx]) 146 | } else { 147 | None 148 | } 149 | } 150 | SubString { 151 | ref rope, 152 | ref offset, 153 | ref length, 154 | } => { 155 | if idx < *length { 156 | rope.char_ref(offset + idx) 157 | } else { 158 | None 159 | } 160 | } 161 | Reverse { ref rope } => { 162 | let len = rope.len(); 163 | rope.char_ref(len - idx - 1) 164 | } 165 | } 166 | } 167 | 168 | pub fn char_ref_mut(&mut self, idx: usize) -> Option<&mut char> { 169 | match *self { 170 | Concatenation { 171 | ref mut left, 172 | ref mut right, 173 | .. 174 | } => { 175 | let llen = left.len(); 176 | if idx < llen { 177 | left.char_ref_mut(idx) 178 | } else if idx < llen + right.len() { 179 | right.char_ref_mut(idx - llen) 180 | } else { 181 | None 182 | } 183 | } 184 | FlatCharVec { ref mut seq } => { 185 | if idx < seq.len() { 186 | Some(&mut seq[idx]) 187 | } else { 188 | None 189 | } 190 | } 191 | SubString { 192 | ref mut rope, 193 | ref offset, 194 | ref length, 195 | } => { 196 | if idx < *length { 197 | rope.char_ref_mut(offset + idx) 198 | } else { 199 | None 200 | } 201 | } 202 | Reverse { ref mut rope } => { 203 | let len = rope.len(); 204 | rope.char_ref_mut(len - idx - 1) 205 | } 206 | } 207 | } 208 | 209 | // FIXME: clone? 210 | pub fn delete(self, start: usize, end: usize) -> Self { 211 | let tail = self.clone().slice_from(end); 212 | self.slice_to(start).append(tail) 213 | } 214 | 215 | pub fn slice_from(self, start: usize) -> Self { 216 | let len = self.len(); 217 | self.slice(start, len) 218 | } 219 | 220 | pub fn slice_to(self, end: usize) -> Self { 221 | self.slice(0, end) 222 | } 223 | 224 | pub fn slice(self, start: usize, end: usize) -> Self { 225 | assert!(end <= self.len(), "illegal slice()"); 226 | let slen = self.len(); 227 | if start == 0 && end == slen { 228 | self 229 | } else { 230 | match self { 231 | Concatenation { left, right, .. } => { 232 | let llen = left.len(); 233 | if end <= llen { 234 | left.slice(start, end) 235 | } else if start >= llen { 236 | right.slice(start - llen, end - llen) 237 | } else { 238 | concatenate(left.slice(start, llen), right.slice(0, end - llen)) 239 | } 240 | } 241 | this @ FlatCharVec { .. } => { 242 | if end - start < 16 { 243 | if let FlatCharVec { seq } = this { 244 | FlatCharVec { 245 | seq: seq[start..end].to_vec(), 246 | } 247 | } else { 248 | unreachable!() 249 | } 250 | } else { 251 | SubString { 252 | rope: Box::new(this), 253 | offset: start, 254 | length: end - start, 255 | } 256 | } 257 | } 258 | SubString { rope, offset, length } => { 259 | assert!(end - start <= length); 260 | SubString { 261 | rope: rope, 262 | offset: offset + start, 263 | length: end - start, 264 | } 265 | } 266 | Reverse { rope } => rope.slice(slen - end, slen - start).reverse(), 267 | } 268 | } 269 | } 270 | 271 | pub fn insert(self, offset: usize, s: T) -> Self { 272 | assert!(offset <= self.len()); 273 | let r = s.into_rope(); 274 | if offset == 0 { 275 | r.append(self) 276 | } else if offset == self.len() { 277 | self.append(r) 278 | } else { 279 | self.clone().slice_to(offset).append(r).append(self.slice_from(offset)) 280 | } 281 | } 282 | 283 | pub fn peek(self, mut f: F) -> Self 284 | where 285 | F: FnMut(&Self), 286 | { 287 | f(&self); 288 | self 289 | } 290 | 291 | fn into_chars(self) -> Vec { 292 | match self { 293 | FlatCharVec { seq } => seq, 294 | Concatenation { left, right, .. } => { 295 | let mut lchs = left.into_chars(); 296 | let rchs = right.into_chars(); 297 | lchs.extend(rchs); 298 | lchs 299 | } 300 | Reverse { rope } => { 301 | let mut inner = rope.into_chars(); 302 | inner.reverse(); 303 | inner 304 | } 305 | SubString { rope, offset, length } => { 306 | let inner = rope.into_chars(); 307 | inner[offset..offset + length].to_vec() 308 | } 309 | } 310 | } 311 | } 312 | 313 | impl<'a> ::std::convert::From<&'a str> for Rope { 314 | fn from(s: &'a str) -> Rope { 315 | Rope::from_vec(s.chars().collect()) 316 | } 317 | } 318 | 319 | impl ::std::convert::From for Rope { 320 | fn from(s: String) -> Rope { 321 | Rope::from_vec(s.chars().collect()) 322 | } 323 | } 324 | 325 | impl ops::Index for Rope { 326 | type Output = char; 327 | fn index(&self, index: usize) -> &Self::Output { 328 | self.char_ref(index).unwrap() 329 | } 330 | } 331 | 332 | // FIXME: Rope should not be a mutable structure 333 | impl ops::IndexMut for Rope { 334 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { 335 | self.char_ref_mut(index).unwrap() 336 | } 337 | } 338 | 339 | // TODO: how to implement this? 340 | // impl ops::Index> for Rope { 341 | // } 342 | 343 | impl fmt::Display for Rope { 344 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 345 | write!(f, "{}", self.to_string()) 346 | } 347 | } 348 | 349 | impl fmt::Debug for Rope { 350 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 351 | write!(f, "R{:?}", self.to_string()) 352 | } 353 | } 354 | 355 | pub trait IntoRope { 356 | fn into_rope(self) -> Rope; 357 | } 358 | 359 | impl IntoRope for char { 360 | fn into_rope(self) -> Rope { 361 | FlatCharVec { seq: vec![self] } 362 | } 363 | } 364 | 365 | impl IntoRope for String { 366 | fn into_rope(self) -> Rope { 367 | FlatCharVec { 368 | seq: self.chars().collect(), 369 | } 370 | } 371 | } 372 | 373 | impl IntoRope for Rope { 374 | fn into_rope(self) -> Rope { 375 | self 376 | } 377 | } 378 | 379 | impl<'a> IntoRope for &'a str { 380 | fn into_rope(self) -> Rope { 381 | FlatCharVec { 382 | seq: self.chars().collect(), 383 | } 384 | } 385 | } 386 | 387 | #[test] 388 | fn test_rope() { 389 | let s = Rope::from("Hello").append(' ').append("World").append('!'); 390 | 391 | println!("depth => {}", s.depth()); 392 | println!("len => {}", s.len()); 393 | println!("got => {:?}", s); 394 | 395 | let s = s.insert(0, "Oh, man, "); 396 | 397 | println!("got => {:?}", s); 398 | 399 | let s = s.insert(9, "wait! "); 400 | println!("got => {:?}", s); 401 | println!("got => {:?}", s.reverse()); 402 | } 403 | 404 | #[test] 405 | fn test_rope2() { 406 | let s = Rope::from("Hello") 407 | .append(" abcdefghijklmnopqrstuvwxyz") 408 | .append(" World") 409 | .peek(|r| println!("D1 got => {}", r)) 410 | .append(" abcdefghijklmnopqrstuvwxyz") 411 | .peek(|r| println!("D2 depth => {}", r.depth())) 412 | .append(" abcdefghijklmnopqrstuvwxyz") 413 | .append(" abcdefghijklmnopqrstuvwxyz"); 414 | 415 | println!("depth => {}", s.depth()); 416 | println!("len => {}", s.len()); 417 | println!("got => {:?}", s); 418 | let s2 = s.slice(10, 50); 419 | println!("got => {:?}", s2); 420 | println!("len => {:?}", s2.len()); 421 | } 422 | 423 | #[test] 424 | fn test_rope_char_at() { 425 | // Note: if str to short, will be automaticlly flatten. 426 | let s = Rope::from("zzzzzzzzzzzzzzzzzzzzHello !").insert(26, "Worldxxxxxxxxxxxxxxxxxxxx"); 427 | // case 0 flat 428 | assert_eq!(s.char_ref(20), Some(&'H')); 429 | // assert_eq!(s[20], 'H'); 430 | // case 1 concat 431 | assert_eq!(s.char_ref(26), Some(&'W')); 432 | // will be "Held!" 433 | let s = s.delete(23, 30); 434 | assert_eq!(s.char_ref(23), Some(&'d')); 435 | // reverse 436 | let s = s.reverse().insert(30, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").delete(35, 40); 437 | for i in 0..s.len() { 438 | assert_eq!( 439 | s.to_string().chars().skip(i).next().unwrap(), 440 | s.char_ref(i).map(|&c| c).unwrap() 441 | ); 442 | } 443 | } 444 | 445 | #[test] 446 | fn test_rope_index_mut() { 447 | let mut s = Rope::from("zzzzzzzzzzzzzzzzzzzzHello !") 448 | .insert(23, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") 449 | .reverse() 450 | .delete(35, 40) 451 | .insert(26, "Worldxxxxxxxxxxxxxxxxxxxx"); 452 | 453 | assert!(s[20] != 'd'); 454 | s[20] = 'd'; 455 | assert_eq!(s[20], 'd'); 456 | } 457 | 458 | // TODO: 459 | // pub trait Rope { 460 | // fn starts_with(self, prefix: &str) -> bool; 461 | // fn ends_with(self, suffix: &str) -> bool; 462 | // } 463 | -------------------------------------------------------------------------------- /src/skip_list.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::iter; 3 | use std::mem; 4 | use std::ptr; 5 | 6 | use std::collections::BTreeMap; 7 | 8 | use rand::{thread_rng, Rng}; 9 | 10 | #[cfg(test)] 11 | use quickcheck::quickcheck; 12 | 13 | const DEFAULT_LEVEL: usize = 4; 14 | 15 | type Link = Option>; 16 | 17 | #[derive(Debug)] 18 | struct Rawlink { 19 | p: *mut T, 20 | } 21 | 22 | impl Clone for Rawlink { 23 | fn clone(&self) -> Self { 24 | Rawlink { p: self.p } 25 | } 26 | } 27 | 28 | impl Copy for Rawlink {} 29 | unsafe impl Send for Rawlink {} 30 | unsafe impl Sync for Rawlink {} 31 | 32 | fn random_level() -> usize { 33 | let mut rng = thread_rng(); 34 | let mut level = 0; 35 | loop { 36 | if rng.gen_ratio(1, 2) { 37 | level += 1; 38 | continue; 39 | } 40 | break; 41 | } 42 | 43 | level 44 | } 45 | 46 | #[derive(Debug)] 47 | pub struct SkipNode { 48 | key: Key, 49 | it: E, 50 | next: Link>, 51 | // level 0 to DEFAULT_LEVEL 52 | forward: Vec>>, 53 | level: usize, 54 | } 55 | 56 | impl SkipNode { 57 | // level: 0 ~ DEFAULT_LEVEL 58 | fn new(key: Key, it: E, level: usize) -> SkipNode { 59 | SkipNode { 60 | key: key, 61 | it: it, 62 | next: None, 63 | forward: vec![Rawlink::none(); level], 64 | level: level, 65 | } 66 | } 67 | 68 | #[inline] 69 | fn level(&self) -> usize { 70 | self.forward.len() 71 | } 72 | 73 | fn promote_level(&mut self, new_level: usize, forward: Vec>) { 74 | let level = self.level(); 75 | // for i in level .. new_level 76 | for item in forward.into_iter().take(new_level).skip(level) { 77 | self.forward.push(item); 78 | } 79 | assert!(self.level() == new_level, "promote_level()"); 80 | } 81 | } 82 | 83 | pub struct SkipList { 84 | head: Link>, 85 | forward: Vec>>, 86 | level: usize, 87 | size: usize, 88 | } 89 | 90 | impl SkipList { 91 | /// create new empty SkipList 92 | pub fn new() -> SkipList { 93 | SkipList { 94 | head: None, 95 | forward: vec![Rawlink::none(); DEFAULT_LEVEL], 96 | level: DEFAULT_LEVEL, 97 | size: 0, 98 | } 99 | } 100 | 101 | pub fn level(&self) -> usize { 102 | self.level 103 | } 104 | 105 | pub fn contains_key(&self, key: &Key) -> bool { 106 | self.find(key).is_some() 107 | } 108 | 109 | pub fn find(&self, key: &Key) -> Option<&E> { 110 | let level = self.level(); 111 | let mut x = self.forward[level - 1]; 112 | for i in (0..level).rev() { 113 | while x 114 | .resolve() 115 | .map_or(false, |n| n.forward[i].resolve().map_or(false, |nx| nx.key < *key)) 116 | { 117 | x = x.resolve().map(|n| n.forward[i]).unwrap(); 118 | } 119 | } 120 | 121 | while x 122 | .resolve() 123 | .map_or(false, |n| n.next.as_ref().map_or(false, |nx| nx.key < *key)) 124 | { 125 | x = x.resolve_mut().map(|n| Rawlink::from(&mut n.next)).unwrap(); 126 | } 127 | 128 | // head 129 | if x.resolve().map_or(false, |n| n.key == *key) { 130 | return x.resolve().map(|n| &n.it); 131 | } 132 | // current x.key is lower than key 133 | // jump next 134 | x = x 135 | .resolve_mut() 136 | .map_or_else(Rawlink::none, |n| Rawlink::from(&mut n.next)); 137 | x.resolve() 138 | .map_or(None, |n| if n.key == *key { Some(&n.it) } else { None }) 139 | } 140 | 141 | fn adjust_head(&mut self, new_level: usize) { 142 | let head_link = Rawlink::from(&mut self.head); 143 | let level = self.level(); 144 | 145 | for _ in level..new_level { 146 | self.forward.push(head_link); 147 | self.head.as_mut().map(|n| n.forward.push(Rawlink::none())); 148 | } 149 | assert_eq!(self.forward.len(), new_level); 150 | assert_eq!(self.head.as_ref().map_or(new_level, |n| n.level()), new_level); 151 | } 152 | 153 | // Due to head node must be of same level as List, 154 | // inserting with decreasing order will lead to almost same bad performance as a linked list 155 | pub fn insert(&mut self, key: Key, it: E) -> Option { 156 | let mut new_level = random_level(); 157 | if new_level > self.level { 158 | // new node will be deepest 159 | self.adjust_head(new_level); 160 | self.level = new_level; 161 | } 162 | if self.head.is_none() { 163 | new_level = self.level; 164 | self.head = Some(Box::new(SkipNode::new(key, it, new_level))); 165 | let p = Rawlink::from(&mut self.head); 166 | for i in 0..new_level { 167 | self.forward[i] = p; 168 | } 169 | self.size += 1; 170 | None 171 | } else if self.head.as_ref().map_or(false, |n| n.key > key) { 172 | // insert at head 173 | new_level = self.level; 174 | let mut new_node = Some(Box::new(SkipNode::new(key, it, new_level))); 175 | let new_link = Rawlink::from(&mut new_node); 176 | 177 | for i in 0..new_level { 178 | new_node.as_mut().map(|n| n.forward[i] = self.forward[i]); 179 | self.forward[i] = new_link 180 | } 181 | 182 | new_node.as_mut().map(|n| n.next = self.head.take()); 183 | self.head = new_node; 184 | self.size += 1; 185 | None 186 | } else if self.head.as_ref().map_or(false, |n| n.key == key) { 187 | // replace head 188 | self.head.as_mut().map(|n| mem::replace(&mut n.it, it)) 189 | } else { 190 | let mut x = Rawlink::from(&mut self.head); 191 | // insert normally 192 | let mut update: Vec>> = self.forward[..new_level].to_vec(); 193 | if new_level > 0 { 194 | // need to insert skip pointers 195 | x = update[new_level - 1]; 196 | for i in (0..new_level).rev() { 197 | while x 198 | .resolve() 199 | .map_or(false, |n| n.forward[i].resolve().map_or(false, |nx| nx.key < key)) 200 | { 201 | x = x.resolve().map(|n| n.forward[i]).unwrap(); 202 | } 203 | update[i] = x; 204 | } 205 | } 206 | 207 | let mut y = x; 208 | // When head node level is lower than current 209 | if y.is_none() { 210 | y = Rawlink::from(&mut self.head); 211 | } 212 | while y 213 | .resolve() 214 | .map_or(false, |n| n.next.as_ref().map_or(false, |nx| nx.key <= key)) 215 | { 216 | y = y.resolve_mut().map(|n| Rawlink::from(&mut n.next)).unwrap(); 217 | } 218 | assert!(y.is_some()); 219 | 220 | // if find equal key, then replace node's value 221 | if y.resolve().map_or(false, |n| n.key == key) { 222 | return y.resolve_mut().map(|n| mem::replace(&mut n.it, it)); 223 | } 224 | 225 | // create node and insert to list 226 | let mut new_node = Some(Box::new(SkipNode::new(key, it, new_level))); 227 | let new_link = Rawlink::from(&mut new_node); 228 | 229 | for (i, item) in update.iter_mut().enumerate().take(new_level) { 230 | new_node.as_mut().map(|n| { 231 | n.forward[i] = item.resolve_mut().map_or_else(Rawlink::none, |nx| nx.forward[i]); 232 | }); 233 | // if update is empty, then update head node's link 234 | item.resolve_mut().map_or_else( 235 | || { 236 | self.forward[i] = new_link; 237 | }, 238 | |prev| { 239 | prev.forward[i] = new_link; 240 | }, 241 | ); 242 | } 243 | 244 | // moves in 245 | y.resolve_mut().map(|n| { 246 | new_node.as_mut().map(|new| new.next = n.next.take()); 247 | n.next = new_node; 248 | }); 249 | self.size += 1; 250 | None 251 | } 252 | } 253 | 254 | pub fn remove(&mut self, key: &Key) -> Option { 255 | if self.head.is_none() { 256 | return None; 257 | } 258 | let level = self.level(); 259 | let mut x = self.forward[level - 1]; 260 | 261 | let mut update: Vec>> = self.forward[..level].to_vec(); 262 | 263 | for i in (0..level).rev() { 264 | while x.resolve().map_or(false, |n| { 265 | n.forward[i].is_some() && n.forward[i].resolve().unwrap().key < *key 266 | }) { 267 | x = x.resolve().map(|n| n.forward[i]).unwrap(); 268 | } 269 | update[i] = x; 270 | } 271 | 272 | while x 273 | .resolve() 274 | .map_or(false, |n| n.next.as_ref().map_or(false, |nx| nx.key < *key)) 275 | { 276 | x = x.resolve_mut().map(|n| Rawlink::from(&mut n.next)).unwrap(); 277 | } 278 | 279 | if x.resolve().map_or(false, |n| n.key == *key) { 280 | // key is head item, unwrap Box directly 281 | let head = *self.head.take().unwrap(); 282 | let SkipNode { 283 | it, mut next, forward, .. 284 | } = head; 285 | 286 | // calculate new level, means, only head nodes 287 | let mut new_level = forward.iter().take_while(|nx| nx.is_some()).count(); 288 | if new_level == 0 { 289 | new_level = 1; // level can't be lower than 1, or remove, find will fail 290 | } 291 | 292 | self.forward = vec![Rawlink::from(&mut next); new_level]; 293 | self.level = new_level; 294 | 295 | next.as_mut().map(|n| n.promote_level(new_level, forward)); 296 | self.head = next; 297 | self.size -= 1; 298 | Some(it) 299 | } else if x.is_some() { 300 | // to be deleted 301 | let current = x.resolve_mut().map_or(None, |n| n.next.take()); 302 | if current.as_ref().map_or(true, |n| n.key != *key) { 303 | return None; 304 | } 305 | let level = current.as_ref().unwrap().level(); 306 | // destruct 307 | let SkipNode { it, next, forward, .. } = *current.unwrap(); 308 | // move next in 309 | x.resolve_mut().map(|n| n.next = next); 310 | // chain prev node and next node 311 | for (i, prev) in update.iter_mut().take(level).enumerate() { 312 | prev.resolve_mut().map(|n| n.forward[i] = forward[i]); 313 | } 314 | self.size -= 1; 315 | Some(it) 316 | } else { 317 | // x is empty 318 | None 319 | } 320 | } 321 | 322 | pub fn len(&self) -> usize { 323 | self.size 324 | } 325 | 326 | pub fn is_empty(&self) -> bool { 327 | self.len() == 0 328 | } 329 | } 330 | 331 | impl fmt::Display for SkipList { 332 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 333 | if self.head.is_none() { 334 | return write!(f, ""); 335 | } 336 | write!(f, "\nlv0 ")?; 337 | 338 | // FIXME: can't have same key 339 | let mut offset_map = BTreeMap::new(); 340 | let mut offset = 5; 341 | let mut x = self.head.as_ref(); 342 | while x.is_some() { 343 | // FIXME: change to unwrap() at last format 344 | offset_map.insert(&x.as_ref().unwrap().key, offset); 345 | let nx = x.as_ref().map_or(None, |n| n.next.as_ref()); 346 | let label = x.as_ref().map_or_else(String::new, |n| format!("{}", n.key)); 347 | if nx.is_none() { 348 | writeln!(f, "{}", label)?; 349 | } else { 350 | write!(f, "{} --> ", label)?; 351 | } 352 | x = nx; 353 | offset += label.len() + 5; 354 | } 355 | for i in 0..self.level { 356 | write!(f, "lv{:<2} ", i + 1)?; 357 | offset = 5; 358 | let mut x = self.forward[i]; 359 | while x.is_some() { 360 | let label = x.resolve().map_or_else(String::new, |n| format!("{}", n.key)); 361 | let lv0_pos = offset_map.get(&x.resolve().unwrap().key).unwrap(); 362 | let padding = lv0_pos - offset; 363 | 364 | if offset == 5 { 365 | // fist item 366 | write!(f, "{} ", label)?; 367 | } else { 368 | write!(f, "{}> {} ", iter::repeat('.').take(padding).collect::(), label)?; 369 | } 370 | x = x.resolve().map_or_else(Rawlink::none, |n| n.forward[i]); 371 | offset = lv0_pos + label.len() + 3; 372 | } 373 | writeln!(f, "")?; 374 | } 375 | Ok(()) 376 | } 377 | } 378 | 379 | /// Rawlink is a type like Option but for holding a raw mutable pointer. 380 | impl Rawlink { 381 | /// Like `Option::None` for Rawlink. 382 | fn none() -> Rawlink { 383 | Rawlink { p: ptr::null_mut() } 384 | } 385 | 386 | /// Like `Option::Some` for Rawlink 387 | fn some(n: &mut T) -> Rawlink { 388 | Rawlink { p: n } 389 | } 390 | 391 | fn is_some(&self) -> bool { 392 | !self.is_none() 393 | } 394 | 395 | fn is_none(&self) -> bool { 396 | self.p.is_null() 397 | } 398 | 399 | // fn take(&mut self) -> Rawlink { 400 | // mem::replace(self, Rawlink::none()) 401 | // } 402 | 403 | /// Convert the `Rawlink` into an immutable Option value. 404 | fn resolve<'a>(&self) -> Option<&'a T> { 405 | if self.p.is_null() { 406 | None 407 | } else { 408 | Some(unsafe { &*self.p }) 409 | } 410 | } 411 | 412 | /// Convert the `Rawlink` into a mutable Option value. 413 | fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { 414 | if self.p.is_null() { 415 | None 416 | } else { 417 | Some(unsafe { &mut *self.p }) 418 | } 419 | } 420 | } 421 | 422 | impl<'a, Key, E> From<&'a mut Link>> for Rawlink> { 423 | fn from(node: &'a mut Link>) -> Self { 424 | match node.as_mut() { 425 | None => Rawlink::none(), 426 | Some(ptr) => Rawlink::some(&mut **ptr), 427 | } 428 | } 429 | } 430 | 431 | #[test] 432 | fn quicktest_skip_list() { 433 | fn prop(xs: Vec) -> bool { 434 | let mut list = SkipList::new(); 435 | for &i in xs.iter() { 436 | list.insert(i, i); 437 | } 438 | // test insert() len() contains_key() remove() 439 | let mut xy = xs; 440 | xy.sort(); 441 | xy.dedup(); 442 | list.len() == xy.len() && 443 | xy.iter().all(|k| list.contains_key(k)) && 444 | xy.iter().all(|k| list.remove(k).unwrap() == *k) && 445 | list.len() == 0 446 | } 447 | 448 | quickcheck(prop as fn(Vec) -> bool); 449 | } 450 | 451 | #[test] 452 | fn test_skip_list() { 453 | let mut list: SkipList = SkipList::new(); 454 | 455 | let mut rng = thread_rng(); 456 | 457 | println!("list => {}", list); 458 | 459 | println!("contains => {}", list.contains_key(&0)); 460 | 461 | //let vals = vec![ -18130, 16865, -1813, 1686, -181, 168, -18, 16]; 462 | for i in 0..13 { 463 | let val = rng.gen_range(-2000, 2000); 464 | // let val = vals[i]; 465 | println!("DEBUG {} insert => {}", i + 1, val); 466 | list.insert(val, ()); 467 | } 468 | 469 | println!("list => {}", list); 470 | println!("level => {}", list.level()); 471 | 472 | let v = 1000; 473 | list.insert(v, ()); 474 | println!("list => {}", list); 475 | assert!(list.contains_key(&1000)); 476 | assert!(!list.contains_key(&3000)); 477 | 478 | list.remove(&v); 479 | assert!(!list.contains_key(&1000)); 480 | println!("list => {}", list); 481 | } 482 | -------------------------------------------------------------------------------- /src/splay_tree.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::fmt; 3 | use std::iter; 4 | 5 | fn compare(a: &T, b: &T) -> i32 { 6 | match a.partial_cmp(b).unwrap() { 7 | cmp::Ordering::Greater => 1, 8 | cmp::Ordering::Less => -1, 9 | _ => 0, 10 | } 11 | } 12 | 13 | pub type NodeCell = Option>>; 14 | 15 | pub struct Node { 16 | left: NodeCell, 17 | right: NodeCell, 18 | key: K, 19 | val: V, 20 | } 21 | 22 | impl Node { 23 | fn dump(&self, depth: usize, f: &mut fmt::Formatter, symbol: char) { 24 | if depth == 0 { 25 | writeln!(f, "\n{:?}[{:?}]", self.key, self.val).unwrap(); 26 | } else { 27 | writeln!( 28 | f, 29 | "{}{}--{:?}[{:?}]", 30 | iter::repeat("| ").take(depth - 1).collect::>().concat(), 31 | symbol, 32 | self.key, 33 | self.val 34 | ) 35 | .unwrap(); 36 | } 37 | if self.left.is_some() { 38 | self.left.as_ref().unwrap().dump(depth + 1, f, '+'); 39 | } 40 | if self.right.is_some() { 41 | self.right.as_ref().unwrap().dump(depth + 1, f, '`'); 42 | } 43 | } 44 | } 45 | 46 | impl Node { 47 | fn new(key: K, val: V) -> Node { 48 | Node { 49 | left: None, 50 | right: None, 51 | key: key, 52 | val: val, 53 | } 54 | } 55 | 56 | fn height(x: Option<&Box>>) -> usize { 57 | if let Some(node) = x { 58 | let lh = Node::height(node.left.as_ref()); 59 | let rh = Node::height(node.left.as_ref()); 60 | if lh <= rh { 61 | rh + 1 62 | } else { 63 | lh + 1 64 | } 65 | } else { 66 | 0 67 | } 68 | } 69 | 70 | fn size(x: Option<&Box>>) -> usize { 71 | if let Some(node) = x { 72 | 1 + Node::size(node.left.as_ref()) + Node::size(node.right.as_ref()) 73 | } else { 74 | 0 75 | } 76 | } 77 | 78 | fn splay(mut h: NodeCell, key: &K) -> NodeCell { 79 | if h.is_none() { 80 | return None; 81 | } 82 | let cmp1 = h.as_ref().map(|n| compare(key, &n.key)).unwrap(); 83 | 84 | if cmp1 < 0 { 85 | // key not in tree, done 86 | if h.as_ref().unwrap().left.is_none() { 87 | return h; 88 | } 89 | let cmp2 = compare(key, &h.as_ref().unwrap().left.as_ref().unwrap().key); 90 | if cmp2 < 0 { 91 | h.as_mut().map(|n| { 92 | n.left.as_mut().map(|n| { 93 | n.left = Node::splay(n.left.take(), key); 94 | }) 95 | }); 96 | h = Node::rotate_right(h); 97 | } else if cmp2 > 0 { 98 | // if let Some(ref mut n) = h.as_mut() { 99 | // if let Some(ref mut left) = n.left.as_mut() { 100 | // left.right = Node::splay(left.right.take(), key); 101 | // if left.right.is_some() { 102 | // n.left = Node::rotate_left(n.left.take()) 103 | // } 104 | // } 105 | // } 106 | if let Some(ref mut n) = h.as_mut() { 107 | if n.left.as_mut().map_or(false, |n| { 108 | n.right = Node::splay(n.right.take(), key); 109 | n.right.is_some() 110 | }) { 111 | n.left = Node::rotate_left(n.left.take()); 112 | } 113 | } 114 | } 115 | // key not in tree 116 | if h.as_ref().unwrap().left.is_none() { 117 | return h; 118 | } else { 119 | return Node::rotate_right(h); 120 | } 121 | } else if cmp1 > 0 { 122 | // key not in tree, done 123 | if h.as_ref().unwrap().right.is_none() { 124 | return h; 125 | } 126 | let cmp2 = compare(key, &h.as_ref().unwrap().right.as_ref().unwrap().key); 127 | if cmp2 < 0 { 128 | h.as_mut().map(|n| { 129 | if n.right.as_mut().map_or(false, |n| { 130 | n.left = Node::splay(n.left.take(), key); 131 | n.left.is_some() 132 | }) { 133 | n.right = Node::rotate_right(n.right.take()); 134 | } 135 | }); 136 | } else if cmp2 > 0 { 137 | h.as_mut().map(|n| { 138 | n.right.as_mut().map(|n| { 139 | n.right = Node::splay(n.right.take(), key); 140 | }) 141 | }); 142 | h = Node::rotate_left(h); 143 | } 144 | // key not in tree 145 | if h.as_ref().unwrap().right.is_none() { 146 | return h; 147 | } else { 148 | return Node::rotate_left(h); 149 | } 150 | } 151 | h 152 | } 153 | 154 | fn rotate_right(mut h: NodeCell) -> NodeCell { 155 | let mut x = h.as_mut().map_or(None, |n| n.left.take()); 156 | h.as_mut().map(|n| n.left = x.as_mut().map_or(None, |n| n.right.take())); 157 | x.as_mut().map(|n| n.right = h); 158 | x 159 | } 160 | 161 | fn rotate_left(mut h: NodeCell) -> NodeCell { 162 | let mut x = h.as_mut().map_or(None, |n| n.right.take()); 163 | h.as_mut().map(|n| n.right = x.as_mut().map_or(None, |n| n.left.take())); 164 | x.as_mut().map(|n| n.left = h); 165 | x 166 | } 167 | } 168 | 169 | /// Splay tree. Supports splay-insert, -search, and -delete. 170 | pub struct SplayTree { 171 | root: NodeCell, 172 | // size: usize 173 | } 174 | 175 | impl fmt::Debug for SplayTree { 176 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 177 | if self.root.is_none() { 178 | write!(f, "") 179 | } else { 180 | self.root.as_ref().unwrap().dump(0, f, ' '); 181 | Ok(()) 182 | } 183 | } 184 | } 185 | 186 | impl SplayTree { 187 | pub fn new() -> SplayTree { 188 | SplayTree { 189 | root: None, 190 | // size: 0 191 | } 192 | } 193 | 194 | pub fn is_empty(&self) -> bool { 195 | self.root.is_none() 196 | } 197 | 198 | pub fn size(&self) -> usize { 199 | Node::size(self.root.as_ref()) 200 | } 201 | 202 | pub fn height(&self) -> usize { 203 | Node::height(self.root.as_ref()) 204 | } 205 | 206 | pub fn clear(&mut self) { 207 | self.root = None; 208 | } 209 | 210 | // get() needs to update tree structure 211 | pub fn get(&mut self, key: &K) -> Option<&V> { 212 | self.root = Node::splay(self.root.take(), key); 213 | self.root 214 | .as_ref() 215 | .map_or(None, |n| if n.key == *key { Some(&n.val) } else { None }) 216 | } 217 | 218 | pub fn contains_key(&mut self, key: &K) -> bool { 219 | self.get(key).is_some() 220 | } 221 | 222 | pub fn get_mut<'t>(&'t mut self, key: &K) -> Option<&'t mut V> { 223 | self.root = Node::splay(self.root.take(), key); 224 | self.root 225 | .as_mut() 226 | .map_or(None, |n| if n.key == *key { Some(&mut n.val) } else { None }) 227 | } 228 | 229 | /// Splay tree insertion. 230 | pub fn insert(&mut self, key: K, val: V) { 231 | if self.root.is_none() { 232 | self.root = Some(Box::new(Node::new(key, val))); 233 | return; 234 | } 235 | 236 | let mut root = Node::splay(self.root.take(), &key); 237 | 238 | let cmp = compare(&key, &root.as_ref().unwrap().key); 239 | if cmp < 0 { 240 | let mut n = Node::new(key, val); 241 | n.left = root.as_mut().unwrap().left.take(); 242 | n.right = root; 243 | self.root = Some(Box::new(n)); 244 | } else if cmp > 0 { 245 | let mut n = Node::new(key, val); 246 | n.right = root.as_mut().unwrap().right.take(); 247 | n.left = root; 248 | self.root = Some(Box::new(n)); 249 | } else if cmp == 0 { 250 | root.as_mut().map(|n| n.val = val); 251 | self.root = root; 252 | } else { 253 | unreachable!(); 254 | } 255 | } 256 | 257 | /// Splay tree deletion. 258 | // use Algs4 approach 259 | pub fn remove(&mut self, key: &K) -> Option { 260 | if self.root.is_none() { 261 | return None; 262 | } 263 | 264 | let mut root = Node::splay(self.root.take(), key); 265 | 266 | if *key == root.as_ref().unwrap().key { 267 | if root.as_ref().unwrap().left.is_none() { 268 | self.root = root.as_mut().unwrap().right.take(); 269 | } else { 270 | let x = root.as_mut().unwrap().right.take(); 271 | self.root = Node::splay(root.as_mut().unwrap().left.take(), key); 272 | self.root.as_mut().map(|n| n.right = x); 273 | } 274 | root.map(|n| n.val) 275 | } else { 276 | None 277 | } 278 | } 279 | } 280 | 281 | #[test] 282 | fn test_splay_tree() { 283 | let mut st1 = SplayTree::new(); 284 | assert!(st1.is_empty()); 285 | st1.insert(5, 5); 286 | st1.insert(9, 9); 287 | st1.insert(13, 13); 288 | st1.insert(11, 11); 289 | st1.insert(1, 1); 290 | 291 | assert_eq!(5, st1.size()); 292 | assert!(st1.height() < 5); 293 | for i in [5, 9, 13, 11, 1].iter() { 294 | assert_eq!(st1.get(i), Some(i)); 295 | } 296 | 297 | st1.get_mut(&1).map(|val| *val = 1000); 298 | assert_eq!(st1.get(&1), Some(&1000)); 299 | 300 | assert!(st1.remove(&9).is_some()); 301 | assert!(st1.remove(&9).is_none()); 302 | assert!(!st1.contains_key(&9)); 303 | } 304 | -------------------------------------------------------------------------------- /src/stack.rs: -------------------------------------------------------------------------------- 1 | pub struct Node { 2 | val: T, 3 | next: Option>>, 4 | } 5 | 6 | impl Clone for Node { 7 | fn clone(&self) -> Self { 8 | Node { 9 | val: self.val.clone(), 10 | next: self.next.clone(), 11 | } 12 | } 13 | } 14 | 15 | pub struct Stack { 16 | s: Option>>, 17 | } 18 | 19 | impl Clone for Stack { 20 | fn clone(&self) -> Self { 21 | Stack { s: self.s.clone() } 22 | } 23 | } 24 | 25 | impl Stack { 26 | pub fn new() -> Stack { 27 | Stack { s: None } 28 | } 29 | 30 | pub fn push(&mut self, val: T) { 31 | let next = self.s.take(); 32 | self.s = Some(Box::new(Node { val: val, next: next })) 33 | } 34 | 35 | pub fn pop(&mut self) -> Option { 36 | let mut top = self.s.take(); 37 | self.s = top.as_mut().map_or(None, |t| t.next.take()); 38 | top.map(|n| n.val) 39 | } 40 | 41 | pub fn len(&self) -> usize { 42 | let mut sz = 0; 43 | let mut p = self.s.as_ref(); 44 | while p.is_some() { 45 | p = p.map_or(None, |n| n.next.as_ref()); 46 | sz += 1; 47 | } 48 | sz 49 | } 50 | 51 | pub fn is_empty(&self) -> bool { 52 | self.peek().is_none() 53 | } 54 | 55 | pub fn peek(&self) -> Option<&T> { 56 | self.s.as_ref().map(|n| &n.val) 57 | } 58 | 59 | pub fn peek_mut(&mut self) -> Option<&mut T> { 60 | self.s.as_mut().map(|n| &mut n.val) 61 | } 62 | } 63 | 64 | pub struct IntoIter { 65 | stack: Stack, 66 | } 67 | 68 | impl Iterator for IntoIter { 69 | type Item = T; 70 | 71 | fn next(&mut self) -> Option { 72 | self.stack.pop() 73 | } 74 | 75 | fn size_hint(&self) -> (usize, Option) { 76 | let len = self.stack.len(); 77 | (len, Some(len)) 78 | } 79 | } 80 | 81 | impl ExactSizeIterator for IntoIter { 82 | fn len(&self) -> usize { 83 | self.stack.len() 84 | } 85 | } 86 | 87 | impl IntoIterator for Stack { 88 | type Item = T; 89 | type IntoIter = IntoIter; 90 | 91 | fn into_iter(self) -> Self::IntoIter { 92 | IntoIter { stack: self } 93 | } 94 | } 95 | 96 | pub struct Iter<'a, T> 97 | where 98 | T: 'a, 99 | { 100 | node: Option<&'a Box>>, 101 | } 102 | 103 | impl<'a, T> Iterator for Iter<'a, T> { 104 | type Item = &'a T; 105 | 106 | fn next(&mut self) -> Option<&'a T> { 107 | let ret = self.node.map(|n| &n.val); 108 | self.node = self.node.map_or(None, |n| n.next.as_ref()); 109 | ret 110 | } 111 | 112 | // Bad 113 | fn size_hint(&self) -> (usize, Option) { 114 | let mut sz = 0; 115 | let mut p = self.node; 116 | while p.is_some() { 117 | p = p.map_or(None, |n| n.next.as_ref()); 118 | sz += 1; 119 | } 120 | (sz, Some(sz)) 121 | } 122 | } 123 | 124 | impl<'a, T> ExactSizeIterator for Iter<'a, T> { 125 | fn len(&self) -> usize { 126 | self.size_hint().0 127 | } 128 | } 129 | 130 | impl Stack { 131 | pub fn iter(&self) -> Iter { 132 | Iter { node: self.s.as_ref() } 133 | } 134 | } 135 | 136 | #[test] 137 | fn test_stack() { 138 | let mut s = Stack::new(); 139 | assert_eq!(s.len(), 0); 140 | s.push(1000); 141 | assert_eq!(s.len(), 1); 142 | s.push(2000); 143 | assert_eq!(s.len(), 2); 144 | assert_eq!(s.peek(), Some(&2000)); 145 | assert_eq!(s.pop(), Some(2000)); 146 | assert_eq!(s.len(), 1); 147 | assert_eq!(s.pop(), Some(1000)); 148 | assert_eq!(s.len(), 0); 149 | assert_eq!(s.pop(), None); 150 | assert_eq!(s.len(), 0); 151 | 152 | s.push(250); 153 | s.peek_mut().map(|val| *val = 100); 154 | assert_eq!(s.pop(), Some(100)); 155 | } 156 | 157 | #[test] 158 | fn test_stack_into_iter() { 159 | let mut s = Stack::new(); 160 | s.push(100); 161 | s.push(200); 162 | s.push(300); 163 | 164 | let mut result = vec![300, 200, 100].into_iter(); 165 | for i in s { 166 | assert_eq!(i, result.next().unwrap()); 167 | } 168 | } 169 | 170 | #[test] 171 | fn test_stack_iter() { 172 | let mut s = Stack::new(); 173 | s.push(100); 174 | s.push(200); 175 | s.push(300); 176 | 177 | let mut result = vec![300, 200, 100].into_iter(); 178 | for i in s.iter() { 179 | assert_eq!(*i, result.next().unwrap()); 180 | } 181 | 182 | assert_eq!(s.len(), 3); 183 | } 184 | 185 | #[test] 186 | fn test_stack_clone() { 187 | let mut s = Stack::new(); 188 | s.push(100); 189 | s.push(200); 190 | s.push(300); 191 | 192 | let t = s.clone(); 193 | 194 | s.pop(); 195 | assert_eq!(s.len(), 2); 196 | assert_eq!(t.len(), 3); 197 | } 198 | -------------------------------------------------------------------------------- /src/suffix_tree.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::iter; 3 | use std::iter::FromIterator; 4 | use std::mem; 5 | use std::ptr; 6 | 7 | use std::collections::BTreeMap; 8 | 9 | use vec_map::VecMap; 10 | 11 | use super::{Queue, Stack}; 12 | 13 | pub use self::Node::*; 14 | 15 | fn min(x: T, y: T) -> T { 16 | if x >= y { 17 | y 18 | } else { 19 | x 20 | } 21 | } 22 | 23 | #[derive(Debug)] 24 | pub struct Rawlink { 25 | p: *mut T, 26 | } 27 | 28 | impl Copy for Rawlink {} 29 | 30 | impl Clone for Rawlink { 31 | fn clone(&self) -> Rawlink { 32 | *self 33 | } 34 | } 35 | 36 | /// Rawlink is a type like Option but for holding a raw mutable pointer. 37 | impl Rawlink { 38 | /// Like `Option::None` for Rawlink. 39 | fn none() -> Rawlink { 40 | Rawlink { p: ptr::null_mut() } 41 | } 42 | 43 | /// Like `Option::Some` for Rawlink 44 | fn some(n: &mut T) -> Rawlink { 45 | Rawlink { p: n } 46 | } 47 | 48 | fn is_null(&self) -> bool { 49 | self.p.is_null() 50 | } 51 | 52 | fn take(&mut self) -> Rawlink { 53 | mem::replace(self, Rawlink::none()) 54 | } 55 | 56 | /// Convert the `Rawlink` into an immutable Option value. 57 | fn resolve<'a>(&self) -> Option<&'a T> { 58 | if self.p.is_null() { 59 | None 60 | } else { 61 | Some(unsafe { &*self.p }) 62 | } 63 | } 64 | 65 | /// Convert the `Rawlink` into a mutable Option value. 66 | fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { 67 | if self.p.is_null() { 68 | None 69 | } else { 70 | Some(unsafe { &mut *self.p }) 71 | } 72 | } 73 | } 74 | 75 | /// A node in `SuffixTree` 76 | #[derive(Debug, Clone)] 77 | pub enum Node<'a, T: 'a> { 78 | Internal { 79 | /// the edge label 80 | data: &'a [T], 81 | /// { text index in root: start position of offset} 82 | offsets: VecMap, 83 | /// text terminates at this node, suffix offset: { text index in root: suffix offset} 84 | // TODO: use bit vec 85 | terminates: VecMap, 86 | children: BTreeMap>, 87 | suffix_link: Rawlink>, 88 | }, 89 | Root { 90 | children: BTreeMap>, 91 | }, 92 | } 93 | 94 | impl<'a, T: Ord + Copy + fmt::Debug> Node<'a, T> { 95 | pub fn root() -> Node<'a, T> { 96 | Root { 97 | children: BTreeMap::new(), 98 | } 99 | } 100 | 101 | pub fn leaf(data: &'a [T], txt_idx: usize, start_pos: usize, rank: usize) -> Node<'a, T> { 102 | Internal { 103 | data: data, 104 | offsets: VecMap::from_iter(vec![(txt_idx, start_pos)]), 105 | terminates: VecMap::from_iter(vec![(txt_idx, rank)]), 106 | children: BTreeMap::new(), 107 | suffix_link: Rawlink::none(), 108 | } 109 | } 110 | 111 | // pub fn internal(data: &'a [T], txt_idx: usize, start_pos: usize) -> Node { 112 | // Internal { 113 | // data: data, 114 | // offsets: VecMap::from_iter(vec![(txt_idx, start_pos)]), 115 | // terminates: VecMap::new(), 116 | // children: BTreeMap::new(), 117 | // suffix_link: Rawlink::none() 118 | // } 119 | // } 120 | 121 | pub fn add_child(&mut self, x: Node<'a, T>) { 122 | match *self { 123 | Root { ref mut children } | Internal { ref mut children, .. } => { 124 | children.insert(x.head(), x); 125 | } 126 | } 127 | } 128 | 129 | fn truncated_internal(&mut self, txt_idx: usize, offset: usize) -> Node<'a, T> { 130 | match *self { 131 | Internal { 132 | ref mut data, 133 | ref mut offsets, 134 | ref mut suffix_link, 135 | .. 136 | } => { 137 | let new_data = &data[..offset]; 138 | *data = &data[offset..]; 139 | let mut new_offsets = offsets.clone(); 140 | // update offset info 141 | new_offsets.insert(txt_idx, offset); 142 | for (_key, value) in offsets.iter_mut() { 143 | *value += offset; 144 | } 145 | 146 | Internal { 147 | data: new_data, 148 | offsets: new_offsets, 149 | terminates: VecMap::new(), 150 | children: BTreeMap::new(), 151 | suffix_link: suffix_link.take(), 152 | } 153 | } 154 | Root { .. } => panic!("can't truncate a root node"), 155 | } 156 | } 157 | 158 | pub fn split_at(&mut self, txt_idx: usize, offset: usize) { 159 | assert!(offset < self.data().len()); 160 | // let new = Node::internal(&self.data()[0..offset], txt_idx); 161 | let new = self.truncated_internal(txt_idx, offset); 162 | let old = mem::replace(self, new); 163 | self.add_child(old); 164 | } 165 | 166 | #[allow(dead_code)] 167 | pub fn add_terminate(&mut self, txt_idx: usize, position: usize) { 168 | match *self { 169 | Internal { ref mut terminates, .. } => { 170 | terminates.insert(txt_idx, position); 171 | } 172 | _ => panic!("add terminate error "), 173 | } 174 | } 175 | 176 | pub fn terminates_any(&self) -> bool { 177 | match *self { 178 | Internal { ref terminates, .. } => !terminates.is_empty(), 179 | _ => panic!("calling terminates_any() on wrong node"), 180 | } 181 | } 182 | 183 | // pub fn terminates(&self, txt_idx: usize) -> Option { 184 | // match *self { 185 | // Internal { ref terminates, .. } => { 186 | // terminates.get(&txt_idx).map(|&pos| pos) 187 | // }, 188 | // _ => panic!("terminates error ") 189 | // } 190 | // } 191 | 192 | #[inline] 193 | pub fn data(&self) -> &'a [T] { 194 | match *self { 195 | Internal { data, .. } => data, 196 | _ => panic!("root hava no data label"), 197 | } 198 | } 199 | 200 | pub fn head(&self) -> T { 201 | match *self { 202 | Internal { data, .. } => data[0], 203 | _ => panic!("root have no head"), 204 | } 205 | } 206 | 207 | pub fn iter_children<'t>(&'t self) -> ::std::collections::btree_map::Values<'t, T, Node<'a, T>> { 208 | match *self { 209 | Root { ref children } | Internal { ref children, .. } => children.values(), 210 | } 211 | } 212 | 213 | pub fn is_root(&self) -> bool { 214 | if let Root { .. } = *self { 215 | true 216 | } else { 217 | false 218 | } 219 | } 220 | 221 | pub fn is_internal(&self) -> bool { 222 | if let Internal { .. } = *self { 223 | true 224 | } else { 225 | false 226 | } 227 | } 228 | 229 | pub fn clean_suffix_links(&mut self) { 230 | match *self { 231 | Internal { 232 | ref mut suffix_link, 233 | ref mut children, 234 | .. 235 | } => { 236 | suffix_link.take(); 237 | for (_, child) in children.iter_mut() { 238 | child.clean_suffix_links(); 239 | } 240 | } 241 | Root { ref mut children } => { 242 | for (_, child) in children.iter_mut() { 243 | child.clean_suffix_links(); 244 | } 245 | } 246 | } 247 | } 248 | 249 | fn length(&self, txt_idx: usize, pos: usize) -> usize { 250 | if let Internal { data, ref offsets, .. } = *self { 251 | let offset = *offsets.get(txt_idx).unwrap(); 252 | min(pos - offset + 1, data.len()) 253 | } else { 254 | 0 255 | } 256 | } 257 | 258 | fn add_suffix_link(&mut self, slink: Rawlink>) { 259 | if let Internal { 260 | ref mut suffix_link, .. 261 | } = *self 262 | { 263 | *suffix_link = slink; 264 | } 265 | } 266 | 267 | fn suffix_link(&self) -> Rawlink> { 268 | if let Internal { suffix_link, .. } = *self { 269 | suffix_link 270 | } else { 271 | Rawlink::none() 272 | } 273 | } 274 | 275 | pub fn mut_child_starts_with<'t>(&'t mut self, c: &T) -> Option<&'t mut Node<'a, T>> { 276 | match *self { 277 | Root { ref mut children } | Internal { ref mut children, .. } => children.get_mut(c), 278 | } 279 | } 280 | pub fn child_starts_with(&self, c: &T) -> Option<&Node<'a, T>> { 281 | match *self { 282 | Root { ref children } | Internal { ref children, .. } => children.get(c), 283 | } 284 | } 285 | } 286 | 287 | #[derive(Debug)] 288 | pub struct SuffixTree<'a, T: Sized + 'a> { 289 | txts: Vec<&'a [T]>, 290 | root: Node<'a, T>, 291 | } 292 | 293 | impl<'a, T: Ord + Copy + fmt::Debug> SuffixTree<'a, T> { 294 | pub fn new(txt: &'a [T]) -> SuffixTree<'a, T> { 295 | let mut st = SuffixTree { 296 | txts: vec![], 297 | root: Node::root(), 298 | }; 299 | st.add(txt); 300 | st 301 | } 302 | 303 | /// check if a string query is a substring 304 | // pub fn contains(&self, query: &[T]) -> bool { 305 | // let text = self.txts; 306 | // let mut x = Some(&self.root); 307 | // let nquery = query.len(); 308 | // let mut pos = 0; 309 | // while !x.map_or(true, |n| n.is_leaf()) && pos < nquery { 310 | // x = x.unwrap().child_starts_with(&query[pos]); 311 | // if let Some(ref node) = x { 312 | // let label = node.slice(); 313 | // let nlabel = label.len(); 314 | // if nlabel <= query[pos..].len() { 315 | // if label == &query[pos.. pos + nlabel] { 316 | // pos += nlabel; 317 | // } else { 318 | // return false; 319 | // } 320 | // } else { 321 | // return label.starts_with(&query[pos..]); 322 | // } 323 | // } 324 | // } 325 | // pos == nquery 326 | // } 327 | 328 | pub fn add(&mut self, txt: &'a [T]) { 329 | self.root.clean_suffix_links(); 330 | self.ukkonen95(txt); 331 | } 332 | 333 | // http://stackoverflow.com/questions/9452701/ukkonens-suffix-tree-algorithm-in-plain-english 334 | // http://pastie.org/5925812 335 | // Ukkonen (1995) 336 | fn ukkonen95(&mut self, txt: &'a [T]) { 337 | let root_link = Rawlink::some(&mut self.root); 338 | let txt_idx = self.txts.len(); 339 | self.txts.push(txt); 340 | // active point 341 | let mut active_node = root_link; 342 | let mut active_edge: usize = 0; 343 | let mut active_length = 0; 344 | // remaining suffix count 345 | let mut remainder = 0; 346 | // last item repeated twice 347 | //for (pos, &c) in txt.iter().chain(iter::once(&txt[tlen-1])).enumerate() { 348 | for (pos, &c) in txt.iter().enumerate() { 349 | remainder += 1; 350 | 351 | let mut last_new_node: Rawlink> = Rawlink::none(); 352 | println!("** Phase {}, read {:?}", pos + 1, c); 353 | while remainder > 0 { 354 | if active_length == 0 { 355 | active_edge = pos 356 | } // APCFALZ 357 | // should create new terminal node here 358 | if active_node 359 | .resolve() 360 | .map_or(false, |n| n.child_starts_with(&txt[active_edge]).is_none()) 361 | { 362 | // Extension Rule 2 (A new leaf edge gets created) 363 | active_node 364 | .resolve_mut() 365 | .map(|n| n.add_child(Node::leaf(&txt[pos..], txt_idx, pos, pos))); 366 | last_new_node.resolve_mut().map(|n| n.add_suffix_link(active_node)); 367 | last_new_node = Rawlink::none(); 368 | } else if let Some(ref mut next) = active_node 369 | .resolve_mut() 370 | .unwrap() 371 | .mut_child_starts_with(&txt[active_edge]) 372 | { 373 | // if let Internal { ref mut offsets, .. } = **next { 374 | // if offsets.get(&txt_idx).is_none() { 375 | // offsets.insert(txt_idx, active_edge); 376 | // } 377 | // } 378 | 379 | // activePoint change for walk down 380 | let nlen = next.length(txt_idx, pos); 381 | if active_length >= nlen { 382 | active_edge += nlen; 383 | active_length -= nlen; 384 | active_node = Rawlink::some(next); 385 | // start from next node 386 | continue; 387 | } 388 | 389 | // Extension Rule 3 (current character being processed is already on the edge) 390 | if next.data()[active_length] == c { 391 | // If a newly created node waiting for it's 392 | // suffix link to be set, then set suffix link 393 | // of that waiting node to curent active node 394 | if !last_new_node.is_null() && !active_node.resolve().unwrap().is_root() { 395 | last_new_node.resolve_mut().map(|n| n.add_suffix_link(active_node)); 396 | // last_new_node = Rawlink::none(); 397 | } 398 | // APCFER3 399 | active_length += 1; 400 | break; 401 | } 402 | 403 | next.split_at(txt_idx, active_length); 404 | next.add_child(Node::leaf(&txt[pos..], txt_idx, pos, pos)); 405 | 406 | last_new_node 407 | .resolve_mut() 408 | .map(|n| n.add_suffix_link(Rawlink::some(next))); 409 | last_new_node = Rawlink::some(next); 410 | } else { 411 | unreachable!(); 412 | } 413 | 414 | remainder -= 1; 415 | 416 | if active_node.resolve().unwrap().is_root() && active_length > 0 { 417 | // APCFER2C1 418 | active_length -= 1; 419 | active_edge = pos - remainder + 1; 420 | } else if !active_node.resolve().unwrap().is_root() { 421 | active_node = active_node.resolve().unwrap().suffix_link(); 422 | } 423 | } 424 | } 425 | 426 | if remainder > 0 { 427 | println!(":( remainder = {}", remainder); 428 | } 429 | } 430 | } 431 | 432 | fn dot_id(x: &T) -> u64 { 433 | unsafe { mem::transmute::<_, u64>(x) } 434 | } 435 | 436 | impl<'a, T: Ord + Copy + fmt::Display + fmt::Debug> SuffixTree<'a, T> { 437 | pub fn to_dot(&self) -> String { 438 | let mut dot = String::new(); 439 | dot.push_str("digraph G {\n"); 440 | dot.push_str(" node [shape=point];\n"); 441 | let mut queue = Queue::new(); 442 | queue.enqueue(&self.root); 443 | while !queue.is_empty() { 444 | let x = queue.dequeue().unwrap(); 445 | let pid = dot_id(x); 446 | for node in x.iter_children() { 447 | let nid = dot_id(node); 448 | if node.terminates_any() { 449 | dot.push_str(&format!(" {} [ color = \"red\", ];\n", nid)); 450 | } 451 | dot.push_str(&format!( 452 | " {} -> {} [ label = \"{}\"];\n", 453 | pid, 454 | nid, 455 | node.data() 456 | .iter() 457 | .map(|c| c.to_string()) 458 | .collect::>() 459 | .concat() 460 | )); 461 | // x.suffix_link().resolve().map(|n| dot.push_str(&format!(" {} -> {} [ style=dashed ];\n", pid, dot_id(n)))); 462 | if node.is_internal() { 463 | queue.enqueue(node); 464 | } 465 | } 466 | } 467 | dot.push_str("}\n"); 468 | dot 469 | } 470 | } 471 | 472 | impl<'a, T: Ord + Copy + fmt::Display + fmt::Debug> fmt::Display for SuffixTree<'a, T> { 473 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 474 | write!(f, "SuffixTree(txts: {:?})\n", self.txts)?; 475 | let mut stack = Stack::new(); 476 | let mut ident_stack = Stack::new(); 477 | stack.push(&self.root); 478 | ident_stack.push(0); 479 | while !stack.is_empty() { 480 | let x = stack.pop().unwrap(); 481 | let ident = ident_stack.pop().unwrap(); 482 | if !x.is_root() { 483 | let spaces = String::from_iter(iter::repeat(' ').take(ident).collect::>()); 484 | write!( 485 | f, 486 | "{}|<{}>", 487 | spaces, 488 | x.data().iter().map(|c| c.to_string()).collect::>().concat() 489 | )?; 490 | if x.terminates_any() { 491 | writeln!(f, "*")?; 492 | } else { 493 | writeln!(f, "")?; 494 | } 495 | } 496 | for node in x.iter_children() { 497 | stack.push(node); 498 | ident_stack.push(ident + 2); 499 | } 500 | } 501 | Ok(()) 502 | } 503 | } 504 | 505 | #[test] 506 | fn test_suffix_tree() { 507 | let s1 = "abcabxabcd#".chars().collect::>(); 508 | println!("s1 => {:?}", s1); 509 | let st = SuffixTree::new(&s1); 510 | println!("got => {}", st); 511 | println!("dot =>\n{}", st.to_dot()); 512 | } 513 | 514 | // #[test] 515 | // fn test_suffix_tree_contains() { 516 | // let s = b"abcabxabcdaabab"; 517 | // let st = SuffixTree::new(s); 518 | 519 | // assert!(st.contains(b"abc")); 520 | // assert!(st.contains(b"")); 521 | // assert!(st.contains(b"b")); 522 | // assert!(!st.contains(b"y")); 523 | // assert!(st.contains(b"abcabxabcdaabab")); 524 | // assert!( st.contains(b"bxabcdaa")); 525 | // assert!(!st.contains(b"bxabadaa")); 526 | // } 527 | -------------------------------------------------------------------------------- /src/tries.rs: -------------------------------------------------------------------------------- 1 | use super::Queue; 2 | 3 | pub struct Node { 4 | c: K, 5 | left: Option>>, 6 | mid: Option>>, 7 | right: Option>>, 8 | val: Option, 9 | } 10 | 11 | impl Node { 12 | fn new(c: K) -> Node { 13 | Node { 14 | c: c, 15 | left: None, 16 | mid: None, 17 | right: None, 18 | val: None, 19 | } 20 | } 21 | 22 | fn put( 23 | mut x: Option>>, 24 | key: &[K], 25 | val: Option, 26 | d: usize, 27 | ) -> (Option>>, Option) { 28 | let replaced; 29 | let c = key[d]; 30 | if x.is_none() { 31 | if val.is_none() { 32 | // no need to call put further 33 | return (x, None); 34 | } 35 | x = Some(Box::new(Node::new(c))); 36 | } 37 | let xc = x.as_ref().unwrap().c; 38 | if c < xc { 39 | let (left, repl) = Node::put(x.as_mut().unwrap().left.take(), key, val, d); 40 | x.as_mut().map(|n| n.left = left); 41 | replaced = repl; 42 | } else if c > xc { 43 | let (right, repl) = Node::put(x.as_mut().unwrap().right.take(), key, val, d); 44 | x.as_mut().map(|n| n.right = right); 45 | replaced = repl; 46 | } else if d < key.len() - 1 { 47 | let (mid, repl) = Node::put(x.as_mut().unwrap().mid.take(), key, val, d + 1); 48 | x.as_mut().map(|n| n.mid = mid); 49 | replaced = repl; 50 | } else { 51 | replaced = x.as_mut().unwrap().val.take(); 52 | x.as_mut().map(|n| n.val = val); 53 | } 54 | (x, replaced) 55 | } 56 | 57 | fn get<'a>(x: Option<&'a Box>>, key: &[K], d: usize) -> Option<&'a Box>> { 58 | if x.is_none() { 59 | return None; 60 | } 61 | let c = key[d]; 62 | let xc = x.unwrap().c; 63 | if c < xc { 64 | Node::get(x.unwrap().left.as_ref(), key, d) 65 | } else if c > xc { 66 | Node::get(x.unwrap().right.as_ref(), key, d) 67 | } else if d < key.len() - 1 { 68 | Node::get(x.unwrap().mid.as_ref(), key, d + 1) 69 | } else { 70 | x 71 | } 72 | } 73 | 74 | fn get_mut<'a>(x: Option<&'a mut Box>>, key: &[K], d: usize) -> Option<&'a mut Box>> { 75 | if x.is_none() { 76 | return None; 77 | } 78 | let c = key[d]; 79 | let xc = x.as_ref().unwrap().c; 80 | if c < xc { 81 | Node::get_mut(x.unwrap().left.as_mut(), key, d) 82 | } else if c > xc { 83 | Node::get_mut(x.unwrap().right.as_mut(), key, d) 84 | } else if d < key.len() - 1 { 85 | Node::get_mut(x.unwrap().mid.as_mut(), key, d + 1) 86 | } else { 87 | x 88 | } 89 | } 90 | 91 | fn collect(x: Option<&Box>>, mut prefix: Vec, queue: &mut Queue>) { 92 | if x.is_none() { 93 | return; 94 | } 95 | Node::collect(x.unwrap().left.as_ref(), prefix.clone(), queue); 96 | let xc = x.unwrap().c; 97 | prefix.push(xc); 98 | if x.unwrap().val.is_some() { 99 | queue.enqueue(prefix.clone()); 100 | } 101 | Node::collect(x.unwrap().mid.as_ref(), prefix.clone(), queue); 102 | prefix.pop(); 103 | Node::collect(x.unwrap().right.as_ref(), prefix, queue); 104 | } 105 | 106 | fn longest_prefix_of<'a>(mut x: Option<&Box>>, query: &'a [K]) -> Option<&'a [K]> { 107 | let mut length = 0; 108 | let mut i = 0; 109 | while x.is_some() && i < query.len() { 110 | let c = query[i]; 111 | let xc = x.unwrap().c; 112 | if c < xc { 113 | x = x.unwrap().left.as_ref(); 114 | } else if c > xc { 115 | x = x.unwrap().right.as_ref(); 116 | } else { 117 | i += 1; 118 | if x.unwrap().val.is_some() { 119 | length = i; 120 | } 121 | x = x.unwrap().mid.as_ref(); 122 | } 123 | } 124 | if length == 0 { 125 | None 126 | } else { 127 | Some(&query[..length]) 128 | } 129 | } 130 | } 131 | 132 | /// Symbol table with string keys, implemented using a ternary search trie (TST). 133 | pub struct TernarySearchTrie { 134 | root: Option>>, 135 | n: usize, 136 | } 137 | 138 | impl TernarySearchTrie { 139 | pub fn new() -> TernarySearchTrie { 140 | TernarySearchTrie { root: None, n: 0 } 141 | } 142 | 143 | pub fn put(&mut self, key: &[K], val: V) { 144 | let (root, replaced) = Node::put(self.root.take(), key, Some(val), 0); 145 | self.root = root; 146 | // replace old val? or insert new? 147 | if replaced.is_none() { 148 | self.n += 1; 149 | } 150 | } 151 | 152 | pub fn get(&self, key: &[K]) -> Option<&V> { 153 | assert!(key.len() > 0, "key must have length >= 1"); 154 | Node::get(self.root.as_ref(), key, 0).map_or(None, |n| n.val.as_ref()) 155 | } 156 | 157 | pub fn get_mut(&mut self, key: &[K]) -> Option<&mut V> { 158 | assert!(key.len() > 0, "key must have length >= 1"); 159 | Node::get_mut(self.root.as_mut(), key, 0).map_or(None, |n| n.val.as_mut()) 160 | } 161 | 162 | pub fn delete(&mut self, key: &[K]) { 163 | let (root, replaced) = Node::put(self.root.take(), key, None, 0); 164 | self.root = root; 165 | // deleted? 166 | if replaced.is_some() { 167 | self.n -= 1; 168 | } 169 | } 170 | 171 | pub fn size(&self) -> usize { 172 | self.n 173 | } 174 | 175 | pub fn is_empty(&self) -> bool { 176 | self.n == 0 177 | } 178 | 179 | pub fn contains(&self, key: &[K]) -> bool { 180 | self.get(key).is_some() 181 | } 182 | 183 | pub fn longest_prefix_of<'a>(&self, query: &'a [K]) -> Option<&'a [K]> { 184 | Node::longest_prefix_of(self.root.as_ref(), query) 185 | } 186 | 187 | pub fn keys_with_prefix(&self, prefix: &[K]) -> Vec> { 188 | let mut queue = Queue::new(); 189 | let x = Node::get(self.root.as_ref(), prefix, 0); 190 | if x.is_some() { 191 | if x.unwrap().val.is_some() { 192 | queue.enqueue(prefix.into()); 193 | } 194 | Node::collect(x.unwrap().mid.as_ref(), prefix.into(), &mut queue); 195 | } 196 | queue.into_iter().collect() 197 | } 198 | 199 | pub fn keys(&self) -> Vec> { 200 | let mut queue = Queue::new(); 201 | Node::collect(self.root.as_ref(), vec![], &mut queue); 202 | queue.into_iter().collect() 203 | } 204 | } 205 | 206 | #[test] 207 | fn test_tst() { 208 | let mut t = TernarySearchTrie::new(); 209 | assert_eq!(t.size(), 0); 210 | t.put(b"name", "Andelf"); 211 | assert_eq!(t.size(), 1); 212 | assert!(t.contains(b"name")); 213 | t.put(b"name", "Fledna"); 214 | assert_eq!(t.size(), 1); 215 | t.put(b"language", "Rust"); 216 | assert_eq!(t.size(), 2); 217 | 218 | assert_eq!(t.get(b"name"), Some(&"Fledna")); 219 | assert_eq!(t.get(b"whatever"), None); 220 | 221 | t.delete(b"name"); 222 | assert_eq!(t.size(), 1); 223 | assert_eq!(t.get(b"name"), None); 224 | 225 | t.put(b"name", "Lednaf"); 226 | assert!(t.keys().contains(&"name".into())); 227 | assert!(t.keys().contains(&"language".into())); 228 | assert!(t.keys_with_prefix(b"lang").contains(&"language".into())); 229 | 230 | t.put(b"ban", "2333"); 231 | t.put(b"banana", "2333"); 232 | assert_eq!(t.longest_prefix_of(b"bananananana").unwrap(), b"banana"); 233 | 234 | t.get_mut(b"banana").map(|v| *v = "46666"); 235 | assert_eq!(t.get(b"banana").unwrap(), &"46666"); 236 | } 237 | -------------------------------------------------------------------------------- /src/union_find.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | pub struct UnionFind { 4 | id: Vec, 5 | /// number of objects in the tree rooted at i. 6 | rank: Vec, 7 | count: usize, 8 | } 9 | 10 | impl UnionFind { 11 | pub fn new(n: usize) -> UnionFind { 12 | UnionFind { 13 | id: (0..n).collect(), 14 | rank: vec![0; n], 15 | count: n, 16 | } 17 | } 18 | 19 | // root_of 20 | pub fn find(&mut self, mut p: usize) -> usize { 21 | assert!(p < self.id.len()); 22 | while p != self.id[p] { 23 | self.id[p] = self.id[self.id[p]]; // path compression by halving 24 | p = self.id[p]; 25 | } 26 | p 27 | } 28 | 29 | pub fn count(&self) -> usize { 30 | self.count 31 | } 32 | 33 | /// Are the two sites p and q in the same component? 34 | pub fn connected(&mut self, p: usize, q: usize) -> bool { 35 | self.find(p) == self.find(q) 36 | } 37 | 38 | pub fn union(&mut self, p: usize, q: usize) { 39 | let i = self.find(p); 40 | let j = self.find(q); 41 | 42 | if i == j { 43 | return; 44 | } 45 | if self.rank[i] < self.rank[j] { 46 | self.id[i] = j; 47 | } else if self.rank[i] > self.rank[j] { 48 | self.id[j] = i; 49 | } else { 50 | self.id[j] = i; 51 | self.rank[i] += 1; 52 | } 53 | self.count -= 1; 54 | } 55 | } 56 | 57 | impl fmt::Display for UnionFind { 58 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 59 | for i in &self.id { 60 | write!(f, "{} ", i)?; 61 | } 62 | Ok(()) 63 | } 64 | } 65 | 66 | #[test] 67 | fn test_uf() { 68 | let mut uf = UnionFind::new(10); 69 | uf.union(4, 3); 70 | uf.union(3, 8); 71 | uf.union(6, 5); 72 | uf.union(9, 4); 73 | uf.union(2, 1); 74 | uf.union(5, 0); 75 | uf.union(7, 2); 76 | uf.union(6, 1); 77 | assert!(uf.count() == 2); 78 | } 79 | --------------------------------------------------------------------------------