├── .gitignore ├── LICENSE ├── README.md ├── algorithm ├── binary-search │ ├── binary_search │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_153_find-minimum-in-rotated-sorted-array │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_33_search-in-rotated-sorted-array │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_367_valid-perfect-square │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── dfs-and-bfs │ ├── leetcode_104_maximum-depth-of-binary-tree_bfs │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── main.rs │ │ │ └── tree.rs │ ├── leetcode_104_maximum-depth-of-binary-tree_dfs │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── main.rs │ │ │ └── tree.rs │ ├── leetcode_111_minimum-depth-of-binary-tree │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── main.rs │ │ │ └── tree.rs │ └── leetcode_700_search-in-a-binary-search-tree │ │ ├── Cargo.toml │ │ └── src │ │ ├── main.rs │ │ └── tree.rs ├── divide-conquer-backtracking │ ├── leetcode_22_generate-parentheses │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_50_powx-n │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_51_n-queens │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_70_climbing-stairs │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_77_combinations │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_78_subsets │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── dynamic_programming │ ├── leetcode_120_triangle │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_300_longest-increasing-subsequence │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_322_coin-change │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_64_minimum-path-sum │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_70_climbing-stairs │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_72_edit-distance │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs └── sort │ ├── bubble_sort │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── heap_sort │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── insertion_sort │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── leetcode_215_kth-largest-element-in-an-array │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── leetcode_493_reverse-pairs │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── leetcode_56_merge-intervals │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── merge_sort │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── quick_sort │ ├── Cargo.toml │ └── src │ │ └── main.rs │ └── selection_sort │ ├── Cargo.toml │ └── src │ └── main.rs ├── chapter ├── chapter_10 │ └── phrases │ │ ├── phrases_lib │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── chinese.rs │ │ │ ├── chinese │ │ │ ├── farewells.rs │ │ │ └── greetings.rs │ │ │ ├── english │ │ │ ├── farewells.rs │ │ │ ├── greetings.rs │ │ │ └── mod.rs │ │ │ ├── lib.rs │ │ │ └── main.rs │ │ └── phrases_use │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_11 │ └── arithmetic │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs ├── chapter_2 │ ├── array_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── data_type_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── enum_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── hashmap_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── mutable_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── shadow_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── string_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── struct_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── tuple_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── vec_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── vecdeque_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_3 │ ├── if_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── iflet_whilelet_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── loop_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── match_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_4 │ ├── adapter_filter_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── adapter_map_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── adapter_rev_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── adapter_take_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── adapter_zip_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── closure_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── consumer_any_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── consumer_collect_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── consumer_sum_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── function_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── function_pointer_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── higher_order_function_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── iterator_next_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── struct_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_5 │ ├── collection_generic_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── debug_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── default_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── enum_generic_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── ord_partialord_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── partialeq_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── struct_generic_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── trait_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── type_cast_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_6 │ ├── iterator_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── lifetime_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── ownership_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── reference_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── slice_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_7 │ ├── box_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── deref_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── drop_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── rc_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── refcell_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── chapter_8 │ ├── async_std_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── thread_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── thread_move_example │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── threadpool_example │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs └── chapter_9 │ ├── panic_example │ ├── Cargo.toml │ └── src │ │ └── main.rs │ └── result_example │ ├── Cargo.toml │ ├── hello.txt │ └── src │ └── main.rs ├── data-structure ├── array │ ├── leetcode_11_container-with-most-water │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_26_remove-duplicates-from-sorted-array │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_283_move-zeroes_bug │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_283_move-zeroes_bugfix │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_283_move-zeroes_upgrade │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_66_plus-one │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── hashtable │ ├── leetcode_1_two-sum │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_1_two-sum_upgrade │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_242_valid-anagram │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_49_group-anagrams │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_49_group-anagrams_addition │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_49_group-anagrams_upgrade │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs ├── linked_list │ ├── leetcode_19_remove-nth-node-from-end-of-list │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── linked_list.rs │ │ │ └── main.rs │ ├── leetcode_206_reverse-linked-list │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── linked_list.rs │ │ │ └── main.rs │ ├── leetcode_21_merge-two-sorted-lists │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── linked_list.rs │ │ │ └── main.rs │ └── leetcode_876_middle-of-the-linked-list │ │ ├── Cargo.toml │ │ └── src │ │ ├── linked_list.rs │ │ └── main.rs ├── stack-queue │ ├── leetcode_155_min-stack │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── leetcode_20_valid-parentheses │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ └── leetcode_239_sliding-window-maximum │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs └── tree │ ├── binary_tree │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── heap │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── leetcode_102_binary-tree-level-order-traversal │ ├── Cargo.toml │ └── src │ │ ├── main.rs │ │ └── tree.rs │ ├── leetcode_144_binary-tree-preorder-traversal │ ├── Cargo.toml │ └── src │ │ ├── main.rs │ │ ├── preorder_func.rs │ │ └── preorder_func │ │ └── tree.rs │ ├── leetcode_145_binary-tree-postorder-traversal │ ├── Cargo.toml │ └── src │ │ ├── main.rs │ │ ├── postorder_func.rs │ │ └── postorder_func │ │ └── tree.rs │ ├── leetcode_701_insert-into-a-binary-search-tree │ ├── Cargo.toml │ └── src │ │ ├── main.rs │ │ └── tree.rs │ └── leetcode_94_binary-tree-inorder-traversal │ ├── Cargo.toml │ └── src │ ├── inorder_func.rs │ ├── inorder_func │ └── tree.rs │ └── main.rs └── project ├── async_run ├── Cargo.toml └── src │ └── main.rs ├── generic ├── Cargo.toml └── src │ ├── data_source.rs │ ├── data_source │ └── student.rs │ └── main.rs ├── random_data_lib ├── Cargo.toml └── src │ ├── lib.rs │ └── main.rs ├── sort_lib ├── Cargo.toml └── src │ ├── async_lib.rs │ ├── lib.rs │ └── sync_lib.rs ├── sort_middleware_lib ├── Cargo.toml └── src │ ├── async_lib.rs │ ├── lib.rs │ ├── main.rs │ └── sync_lib.rs └── thread_run ├── Cargo.toml └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | **/Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | ########################## 13 | # Jetbrains Ignore files # 14 | ########################## 15 | *.iml 16 | .idea/ 17 | 18 | ###################### 19 | # OS generated files # 20 | ###################### 21 | .DS_Store 22 | .DS_Store? 23 | ._* 24 | .Trashes 25 | ehthumbs.db 26 | Thumbs.db 27 | -------------------------------------------------------------------------------- /algorithm/binary-search/binary_search/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "binary_search" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/binary-search/binary_search/src/main.rs: -------------------------------------------------------------------------------- 1 | pub fn search(nums: Vec, target: i32) -> i32 { 2 | if nums.len() == 0 { 3 | return -1; 4 | } 5 | 6 | let mut left = 0; 7 | let mut right = nums.len() - 1; 8 | 9 | while left <= right { 10 | let mid = left + (right - left) / 2; 11 | if nums[mid] == target { 12 | return mid as i32; 13 | } else if nums[mid] < target { 14 | left = mid + 1; 15 | } else { 16 | right = mid - 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | 23 | fn main() { 24 | let nums = vec![0, 1, 2, 4, 5, 6, 7]; 25 | let target = 6; 26 | 27 | println!("{}", search(nums, target)); 28 | } 29 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_153_find-minimum-in-rotated-sorted-array/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_153_find-minimum-in-rotated-sorted-array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_153_find-minimum-in-rotated-sorted-array" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_153_find-minimum-in-rotated-sorted-array/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn find_min(nums: Vec) -> i32 { 5 | if nums.len() == 1 { 6 | return nums[0]; 7 | } 8 | 9 | let mut left = 0; 10 | let mut right = nums.len() - 1; 11 | 12 | if nums[right] > nums[0] { 13 | return nums[0]; 14 | } 15 | 16 | while left <= right { 17 | let mid = left + (right - left) / 2; 18 | 19 | if nums[mid] > nums[mid + 1] { 20 | return nums[mid + 1]; 21 | } 22 | 23 | if nums[mid - 1] > nums[mid] { 24 | return nums[mid]; 25 | } 26 | 27 | if nums[mid] > nums[0] { 28 | left = mid + 1; 29 | } else { 30 | right = mid - 1; 31 | } 32 | } 33 | 34 | return -1; 35 | } 36 | } 37 | 38 | fn main() { 39 | let nums = vec![4, 5, 6, 7, 0, 1, 2]; 40 | println!("{}", Solution::find_min(nums)); 41 | } 42 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_33_search-in-rotated-sorted-array/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_33_search-in-rotated-sorted-array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_33_search-in-rotated-sorted-array" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_33_search-in-rotated-sorted-array/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn search(nums: Vec, target: i32) -> i32 { 5 | if nums.len() == 0 { 6 | return -1; 7 | } 8 | 9 | let mut left = 0; 10 | let mut right = nums.len() - 1; 11 | 12 | while left <= right { 13 | let mid = left + (right - left) / 2; 14 | if nums[mid] == target { 15 | return mid as i32; 16 | } else if nums[left] <= nums[mid] { 17 | if target >= nums[left] && target < nums[mid] { 18 | right = mid - 1; 19 | } else { 20 | left = mid + 1; 21 | } 22 | } else { 23 | if target > nums[mid] && target <= nums[right] { 24 | left = mid + 1; 25 | } else { 26 | right = mid - 1; 27 | } 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | } 34 | 35 | fn main() { 36 | let nums = vec![4, 5, 6, 7, 0, 1, 2]; 37 | let target = 1; 38 | 39 | println!("{}", Solution::search(nums, target)); 40 | } 41 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_367_valid-perfect-square/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_367_valid-perfect-square/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_367_valid-perfect-square" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/binary-search/leetcode_367_valid-perfect-square/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn is_perfect_square(num: i32) -> bool { 5 | if num == 0 || num == 1 { 6 | return true; 7 | } 8 | 9 | let mut left = 2; 10 | let mut right = num / 2; 11 | while left <= right { 12 | let mid = left + (right - left) / 2; 13 | let guess_squared = mid as i64 * mid as i64; 14 | if guess_squared == num as i64 { 15 | return true; 16 | } else if guess_squared > num as i64 { 17 | right = mid - 1; 18 | } else { 19 | left = mid + 1; 20 | } 21 | } 22 | 23 | return false; 24 | } 25 | } 26 | 27 | fn main() { 28 | let num = 808201; 29 | println!("{}", Solution::is_perfect_square(num)); 30 | } 31 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_bfs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_104_maximum-depth-of-binary-tree_bfs" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_bfs/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | use std::collections::VecDeque; 8 | 9 | struct Solution; 10 | 11 | impl Solution { 12 | pub fn max_depth(root: Option>>) -> i32 { 13 | if root.is_none() { return 0; } 14 | 15 | let mut depth = 0; 16 | let mut deque: VecDeque>>> = VecDeque::new(); 17 | deque.push_back(root); 18 | 19 | while !deque.is_empty() { 20 | let level_size = deque.len(); 21 | depth += 1; 22 | for _i in 0..level_size { 23 | if let Some(Some(node)) = deque.pop_front() { 24 | if node.borrow().left.is_some() { deque.push_back(node.borrow().left.clone()); } 25 | if node.borrow().right.is_some() { deque.push_back(node.borrow().right.clone()); } 26 | } 27 | } 28 | } 29 | depth 30 | } 31 | } 32 | 33 | fn main() { 34 | let vec = vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]; 35 | println!("{}", Solution::max_depth(to_tree(vec))); 36 | } 37 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_bfs/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_dfs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_104_maximum-depth-of-binary-tree_dfs" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_dfs/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | struct Solution; 9 | 10 | impl Solution { 11 | pub fn max_depth(root: Option>>) -> i32 { 12 | match root { 13 | Some(node) => { 14 | let left = Self::max_depth(node.borrow().left.clone()); 15 | let right = Self::max_depth(node.borrow().right.clone()); 16 | 1 + left.max(right) 17 | } 18 | _ => 0, 19 | } 20 | } 21 | } 22 | 23 | fn main() { 24 | let vec = vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]; 25 | println!("{}", Solution::max_depth(to_tree(vec))); 26 | } 27 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_104_maximum-depth-of-binary-tree_dfs/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_111_minimum-depth-of-binary-tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_111_minimum-depth-of-binary-tree" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_111_minimum-depth-of-binary-tree/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | struct Solution; 9 | 10 | impl Solution { 11 | pub fn min_depth(root: Option>>) -> i32 { 12 | match root { 13 | Some(node) => { 14 | if node.borrow().left.is_none() { 15 | return Self::min_depth(node.borrow().right.clone()) + 1; 16 | } 17 | if node.borrow().right.is_none() { 18 | return Self::min_depth(node.borrow().left.clone()) + 1; 19 | } 20 | 21 | let left = Self::min_depth(node.borrow().left.clone()); 22 | let right = Self::min_depth(node.borrow().right.clone()); 23 | left.min(right) + 1 24 | } 25 | None => 0, 26 | } 27 | } 28 | } 29 | 30 | fn main() { 31 | let vec = vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]; 32 | println!("{}", Solution::min_depth(to_tree(vec))); 33 | } 34 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_111_minimum-depth-of-binary-tree/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_700_search-in-a-binary-search-tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_700_search-in-a-binary-search-tree" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_700_search-in-a-binary-search-tree/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | struct Solution; 9 | 10 | impl Solution { 11 | pub fn search_bst(root: Option>>, val: i32) -> Option>> { 12 | let mut r = root.clone(); 13 | while let Some(node) = r { 14 | if node.borrow().val == val { return Some(node); } 15 | if node.borrow().val > val { 16 | r = node.borrow().left.clone(); 17 | } else { 18 | r = node.borrow().right.clone(); 19 | } 20 | } 21 | None 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /algorithm/dfs-and-bfs/leetcode_700_search-in-a-binary-search-tree/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_22_generate-parentheses/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_22_generate-parentheses/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_22_generate-parentheses" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_22_generate-parentheses/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn generate_parenthesis(n: i32) -> Vec { 5 | let mut vec: Vec = Vec::new(); 6 | recursion(&mut vec, 0, 0, n, String::from("")); 7 | return vec; 8 | } 9 | } 10 | 11 | fn recursion(vec: &mut Vec, left: i32, right: i32, n: i32, s: String) { 12 | if left == n && right == n { 13 | vec.push(s.clone()); 14 | } 15 | 16 | if left < n { 17 | recursion(vec, left + 1, right, n, format!("{}{}", &s, "(")); 18 | } 19 | if right < left { 20 | recursion(vec, left, right + 1, n, format!("{}{}", &s, ")")); 21 | } 22 | } 23 | 24 | fn main() { 25 | println!("{:?}", Solution::generate_parenthesis(3)); 26 | } 27 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_50_powx-n/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_50_powx-n/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_50_powx-n" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_50_powx-n/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn my_pow(x: f64, n: i32) -> f64 { 5 | let mut x = x; 6 | let mut n = n; 7 | if n < 0 { 8 | x = 1.0 / x; 9 | n = -n; 10 | } 11 | 12 | return fast_pow(x, n); 13 | } 14 | } 15 | 16 | fn fast_pow(x: f64, n: i32) -> f64 { 17 | if n == 0 { 18 | return 1.0; 19 | } 20 | 21 | let half = fast_pow(x, n / 2); 22 | return if n % 2 == 0 { 23 | half * half 24 | } else { 25 | half * half * x 26 | } 27 | } 28 | 29 | fn main() { 30 | let x = 2.0; 31 | let n = -2; 32 | 33 | println!("{}", Solution::my_pow(x, n)); 34 | } 35 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_51_n-queens/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_51_n-queens/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_51_n-queens" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_51_n-queens/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn solve_n_queens(n: i32) -> Vec> { 5 | let mut board = vec![vec!['.'; n as usize]; n as usize]; 6 | let mut solution = vec![]; 7 | backtrack(&mut board, &mut solution, n, 0); 8 | solution 9 | } 10 | } 11 | 12 | fn backtrack(board: &mut Vec>, solution: &mut Vec>, n: i32, row: i32) { 13 | for column in 0..n { 14 | if !collision(&board, n, row, column) { 15 | board[row as usize][column as usize] = 'Q'; 16 | if row == n - 1 { 17 | solution.push(board.iter().map(|vec| vec.iter().collect()).collect()); 18 | } else { 19 | backtrack(board, solution, n, row + 1); 20 | } 21 | board[row as usize][column as usize] = '.'; 22 | } 23 | } 24 | } 25 | 26 | fn collision(board: &Vec>, n: i32, row: i32, column: i32) -> bool { 27 | let mut up_row = row - 1; 28 | let mut left_column = column - 1; 29 | let mut right_column = column + 1; 30 | 31 | while up_row >= 0 { 32 | if board[up_row as usize][column as usize] == 'Q' { 33 | return true; 34 | } 35 | 36 | if left_column >= 0 && board[up_row as usize][left_column as usize] == 'Q' { 37 | return true; 38 | } 39 | 40 | if right_column < n && board[up_row as usize][right_column as usize] == 'Q' { 41 | return true; 42 | } 43 | 44 | up_row -= 1; 45 | left_column -= 1; 46 | right_column += 1; 47 | } 48 | 49 | false 50 | } 51 | 52 | fn main() { 53 | println!("{:?}", Solution::solve_n_queens(4)); 54 | } 55 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_70_climbing-stairs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_70_climbing-stairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_70_climbing-stairs" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_70_climbing-stairs/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn climb_stairs(n: i32) -> i32 { 5 | let mut memo: Vec = vec![0; n as usize]; 6 | return recursion(n as usize, &mut memo); 7 | } 8 | } 9 | 10 | fn recursion(n: usize, memo: &mut Vec) -> i32 { 11 | if n <= 2 { 12 | return n as i32; 13 | } 14 | 15 | if memo[n-1] == 0 { 16 | memo[n-1] = recursion(n - 1, memo); 17 | } 18 | if memo[n-2] == 0 { 19 | memo[n-2] = recursion(n - 2, memo); 20 | } 21 | 22 | return memo[n-1] + memo[n-2]; 23 | } 24 | 25 | fn main() { 26 | println!("{}", Solution::climb_stairs(10)); 27 | } 28 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_77_combinations/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_77_combinations/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_77_combinations" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_77_combinations/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn combine(n: i32, k: i32) -> Vec> { 5 | if n < k { 6 | return Vec::new(); 7 | } 8 | 9 | let mut vecs: Vec> = Vec::new(); 10 | let mut vec: Vec = Vec::new(); 11 | backtrack(&mut vecs, &mut vec, n, k, 1); 12 | return vecs; 13 | } 14 | } 15 | 16 | fn backtrack(vecs: &mut Vec>, vec: &mut Vec, n: i32, k: i32, start: usize) { 17 | if vec.len() == k as usize { 18 | vecs.push(vec.clone()); 19 | return; 20 | } 21 | 22 | let mut i = start; 23 | while i <= (n - (k - vec.len() as i32) + 1) as usize { 24 | vec.push(i as i32); 25 | backtrack(vecs, vec, n, k, i + 1); 26 | vec.remove(vec.len() - 1); 27 | 28 | i += 1; 29 | } 30 | } 31 | 32 | fn main() { 33 | println!("{:?}", Solution::combine(4, 2)); 34 | } 35 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_78_subsets/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_78_subsets/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_78_subsets" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/divide-conquer-backtracking/leetcode_78_subsets/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn subsets(nums: Vec) -> Vec> { 5 | if nums.len() == 0 { 6 | return Vec::new(); 7 | } 8 | 9 | let mut vecs: Vec> = Vec::new(); 10 | let mut vec: Vec = Vec::new(); 11 | backtrack(&mut vecs, &mut vec, &nums, 0); 12 | return vecs; 13 | } 14 | } 15 | 16 | fn backtrack(vecs: &mut Vec>, vec: &mut Vec, nums: &Vec, start: usize) { 17 | vecs.push(vec.clone()); 18 | for i in start..nums.len() { 19 | vec.push(nums[i]); 20 | backtrack(vecs, vec, &nums, i + 1); 21 | vec.remove(vec.len() - 1); 22 | } 23 | } 24 | 25 | fn main() { 26 | let nums = vec![1, 2, 3]; 27 | println!("{:?}", Solution::subsets(nums)); 28 | } 29 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_120_triangle/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_120_triangle" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_120_triangle/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn minimum_total(mut triangle: Vec>) -> i32 { 5 | if triangle.len() == 0 { return 0; } 6 | 7 | for i in (0..triangle.len() - 1).rev() { 8 | for j in 0..triangle[i].len() { 9 | triangle[i][j] = triangle[i+1][j].min(triangle[i+1][j+1]) + triangle[i][j]; 10 | } 11 | } 12 | triangle[0][0] 13 | } 14 | } 15 | 16 | fn main() { 17 | let triangle = vec![ 18 | vec![2], 19 | vec![3, 4], 20 | vec![6, 5, 7], 21 | vec![4, 1, 8, 3], 22 | ]; 23 | 24 | println!("{}", Solution::minimum_total(triangle)); 25 | } 26 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_300_longest-increasing-subsequence/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_300_longest-increasing-subsequence" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_300_longest-increasing-subsequence/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn length_of_lis(nums: Vec) -> i32 { 5 | if nums.len() <= 1 { 6 | return nums.len() as i32; 7 | } 8 | 9 | let mut dp = vec![1; nums.len()]; 10 | let mut res = 1; 11 | 12 | for i in 0..nums.len() { 13 | for j in 0..i { 14 | if nums[i] > nums[j] { 15 | dp[i] = dp[i].max(dp[j] + 1); 16 | } 17 | } 18 | res = res.max(dp[i]); 19 | } 20 | res 21 | } 22 | } 23 | 24 | fn main() { 25 | let nums = vec![2, 9, 3, 6, 5, 1, 7]; 26 | println!("{}", Solution::length_of_lis(nums)); 27 | } 28 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_322_coin-change/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_322_coin-change" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_322_coin-change/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn coin_change(coins: Vec, amount: i32) -> i32 { 5 | let mut dp = vec![amount + 1; (amount + 1) as usize]; 6 | dp[0] = 0; 7 | for i in 1..=amount { 8 | for &coin in coins.iter() { 9 | if i >= coin { 10 | let i = i as usize; 11 | let coin = coin as usize; 12 | dp[i] = dp[i].min(dp[i - coin] + 1); 13 | } 14 | } 15 | } 16 | 17 | let last = *dp.last().unwrap(); 18 | if last > amount { -1 } else { last } 19 | } 20 | } 21 | 22 | fn main() { 23 | let coins = vec![1, 3, 5]; 24 | println!("{}", Solution::coin_change(coins, 11)); 25 | } 26 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_64_minimum-path-sum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_64_minimum-path-sum" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_64_minimum-path-sum/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn min_path_sum(matrix: Vec>) -> i32 { 5 | let m = matrix.len(); 6 | if m == 0 { return 0; } 7 | let n = matrix[0].len(); 8 | if n == 0 { return 0; } 9 | 10 | let mut states = vec![vec![0; n]; m]; 11 | let mut sum = 0; 12 | for j in 0..n { 13 | sum += matrix[0][j]; 14 | states[0][j] = sum; 15 | } 16 | 17 | sum = 0; 18 | for i in 0..m { 19 | sum += matrix[i][0]; 20 | states[i][0] = sum; 21 | } 22 | 23 | for i in 1..m { 24 | for j in 1..n { 25 | states[i][j] = matrix[i][j] + states[i - 1][j].min(states[i][j - 1]); 26 | } 27 | } 28 | 29 | states[m - 1][n - 1] 30 | } 31 | } 32 | 33 | fn main() { 34 | let matrix = vec![ 35 | vec![1, 3, 1], 36 | vec![1, 5, 1], 37 | vec![4, 2, 1], 38 | ]; 39 | 40 | println!("{}", Solution::min_path_sum(matrix)); 41 | } 42 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_70_climbing-stairs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_70_climbing-stairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_70_climbing-stairs" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_70_climbing-stairs/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn climb_stairs(n: i32) -> i32 { 5 | if n == 1 { 6 | return 1; 7 | } 8 | 9 | let mut dp: Vec = vec![0; (n + 1) as usize]; 10 | dp[1] = 1; 11 | dp[2] = 2; 12 | for i in 3..(n + 1) as usize { 13 | dp[i] = dp[i - 1] + dp[i - 2]; 14 | } 15 | 16 | return dp[n as usize]; 17 | } 18 | } 19 | 20 | fn main() { 21 | println!("{}", Solution::climb_stairs(10)); 22 | } 23 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_72_edit-distance/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_72_edit-distance" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/dynamic_programming/leetcode_72_edit-distance/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn min_distance(word1: String, word2: String) -> i32 { 5 | let word1_chars: Vec = word1.chars().collect(); 6 | let word2_chars: Vec = word2.chars().collect(); 7 | let n1 = word1.len(); 8 | let n2 = word2.len(); 9 | let mut dp = vec![vec![0; n2 + 1]; n1 + 1]; 10 | 11 | for j in 1..=n2 { 12 | dp[0][j] = dp[0][j - 1] + 1; 13 | } 14 | 15 | for i in 1..=n1 { 16 | dp[i][0] = dp[i - 1][0] + 1; 17 | } 18 | 19 | for i in 1..=n1 { 20 | for j in 1..=n2 { 21 | if word1_chars[i - 1] == word2_chars[j - 1] { 22 | dp[i][j] = dp[i - 1][j - 1]; 23 | } else { 24 | dp[i][j] = dp[i][j - 1].min(dp[i - 1][j]).min(dp[i - 1][j - 1]) + 1; 25 | } 26 | } 27 | } 28 | 29 | dp[n1][n2] 30 | } 31 | } 32 | 33 | fn main() { 34 | let word1 = String::from("horse"); 35 | let word2 = String::from("ros"); 36 | 37 | println!("{}", Solution::min_distance(word1, word2)); 38 | } 39 | -------------------------------------------------------------------------------- /algorithm/sort/bubble_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bubble_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/bubble_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | fn bubble_sort(mut nums: Vec) -> Vec { 2 | if nums.is_empty() { return vec![]; } 3 | 4 | for i in 0..nums.len() - 1 { 5 | let mut flag = false; 6 | for j in 0..nums.len() - i - 1 { 7 | if nums[j] > nums[j + 1] { 8 | let tmp = nums[j]; 9 | nums[j] = nums[j + 1]; 10 | nums[j + 1] = tmp; 11 | 12 | flag = true; 13 | } 14 | } 15 | 16 | println!("{:?}", nums); 17 | if !flag { break; } 18 | } 19 | nums 20 | } 21 | 22 | fn main() { 23 | let nums = vec![7, 9, 12, 11, 6, 3]; 24 | bubble_sort(nums); 25 | } -------------------------------------------------------------------------------- /algorithm/sort/heap_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "heap_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/heap_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | pub fn heap_sort(nums: &mut Vec) { 2 | build_heap(nums); 3 | 4 | for i in (0..nums.len()).rev() { 5 | nums.swap(0, i); 6 | heapify(nums, 0, i); 7 | println!("{:?}", nums); 8 | } 9 | } 10 | 11 | 12 | fn build_heap(nums: &mut Vec) { 13 | let len = nums.len(); 14 | for i in (0..len / 2).rev() { 15 | heapify(nums, i, len); 16 | } 17 | } 18 | 19 | fn heapify(nums: &mut Vec, idx: usize, len: usize) { 20 | let mut idx = idx; 21 | loop { 22 | let mut max_pos = idx; 23 | if 2 * idx + 1 < len && nums[idx] < nums[2 * idx + 1] { max_pos = 2 * idx + 1; } 24 | if 2 * idx + 2 < len && nums[max_pos] < nums[2 * idx + 2] { max_pos = 2 * idx + 2; } 25 | 26 | if max_pos == idx { break; } 27 | nums.swap(idx, max_pos); 28 | idx = max_pos; 29 | } 30 | } 31 | 32 | fn main() { 33 | let mut nums = vec![7, 9, 12, 11, 6, 3]; 34 | heap_sort(&mut nums); 35 | } 36 | -------------------------------------------------------------------------------- /algorithm/sort/insertion_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "insertion_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/insertion_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | fn insertion_sort(mut nums: Vec) -> Vec { 2 | if nums.is_empty() { return vec![]; } 3 | 4 | for i in 1..nums.len() { 5 | let current = nums[i]; 6 | 7 | let mut j = (i - 1) as i32; 8 | while j >= 0 { 9 | if nums[j as usize] > current { 10 | nums[(j + 1) as usize] = nums[j as usize]; 11 | } else { 12 | break; 13 | } 14 | j -= 1; 15 | } 16 | 17 | 18 | nums[(j + 1) as usize] = current; 19 | println!("{:?}", nums); 20 | } 21 | 22 | nums 23 | } 24 | 25 | fn main() { 26 | let nums = vec![7, 9, 12, 11, 6, 3]; 27 | insertion_sort(nums); 28 | } 29 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_215_kth-largest-element-in-an-array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_215_kth-largest-element-in-an-array" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | rand = "0.7.3" 11 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_215_kth-largest-element-in-an-array/src/main.rs: -------------------------------------------------------------------------------- 1 | use rand::Rng; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn find_kth_largest(mut nums: Vec, k: i32) -> i32 { 7 | if nums.is_empty() || k > nums.len() as i32 { return -1; } 8 | let len = nums.len(); 9 | return quick_select(&mut nums, 0, len - 1, len - k as usize); 10 | } 11 | } 12 | 13 | fn quick_select(nums: &mut Vec, left: usize, right: usize, k_smallest: usize) -> i32 { 14 | if left == right { return nums[left]; } 15 | 16 | let mut rng = rand::thread_rng(); 17 | let mut pivot_index = left + rng.gen_range(0, right - left); 18 | pivot_index = partition(nums, left, right, pivot_index); 19 | 20 | return if k_smallest == pivot_index { 21 | nums[k_smallest] 22 | } else if k_smallest < pivot_index { 23 | quick_select(nums, left, pivot_index - 1, k_smallest) 24 | } else { 25 | quick_select(nums, pivot_index + 1, right, k_smallest) 26 | }; 27 | } 28 | 29 | fn partition(nums: &mut Vec, left: usize, right: usize, pivot_index: usize) -> usize { 30 | let pivot = nums[pivot_index]; 31 | nums.swap(pivot_index, right); 32 | let mut store_index = left; 33 | 34 | for i in left..right { 35 | if nums[i] < pivot { 36 | nums.swap(store_index, i); 37 | store_index += 1; 38 | } 39 | } 40 | 41 | nums.swap(store_index, right); 42 | store_index 43 | } 44 | 45 | fn main() { 46 | let nums = vec![3, 2, 1, 5, 6, 4]; 47 | println!("{}", Solution::find_kth_largest(nums, 2)); 48 | } 49 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_493_reverse-pairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_493_reverse-pairs" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_493_reverse-pairs/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn reverse_pairs(mut nums: Vec) -> i32 { 5 | if nums.is_empty() { return 0; } 6 | 7 | let len = nums.len(); 8 | let mut tmp = vec![0; len]; 9 | return sort_count(&mut nums, &mut tmp, 0, len - 1) as i32; 10 | } 11 | } 12 | 13 | fn sort_count(nums: &mut Vec, tmp: &mut Vec, left: usize, right: usize) -> usize { 14 | if left >= right { return 0; } 15 | let middle = left + (right - left) / 2; 16 | 17 | let mut count = sort_count(nums, tmp, left, middle) + sort_count(nums, tmp, middle + 1, right); 18 | 19 | let mut point_left = left; 20 | let mut point_right = middle + 1; 21 | while point_left <= middle && point_right <= right { 22 | if nums[point_left] as i64 > 2 * nums[point_right] as i64 { 23 | count += middle - point_left + 1; 24 | point_right += 1; 25 | } else { 26 | point_left += 1; 27 | } 28 | } 29 | 30 | merge(nums, tmp, left, middle, right); 31 | count 32 | } 33 | 34 | fn merge(nums: &mut Vec, tmp: &mut Vec, left: usize, middle: usize, right: usize) { 35 | let mut index = 0; 36 | let mut point_left = left; 37 | let mut point_right = middle + 1; 38 | while point_left <= middle && point_right <= right { 39 | if nums[point_left] <= nums[point_right] { 40 | tmp[index] = nums[point_left]; 41 | index += 1; 42 | point_left += 1; 43 | } else { 44 | tmp[index] = nums[point_right]; 45 | index += 1; 46 | point_right += 1 47 | } 48 | } 49 | 50 | while point_left <= middle { 51 | tmp[index] = nums[point_left]; 52 | index += 1; 53 | point_left += 1; 54 | } 55 | 56 | while point_right <= right { 57 | tmp[index] = nums[point_right]; 58 | index += 1; 59 | point_right += 1 60 | } 61 | 62 | for i in left..=right { 63 | nums[i] = tmp[i - left]; 64 | } 65 | } 66 | 67 | fn main() { 68 | let nums = vec![2, 4, 3, 5, 1]; 69 | println!("{}", Solution::reverse_pairs(nums)); 70 | } 71 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_56_merge-intervals/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_56_merge-intervals" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/leetcode_56_merge-intervals/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn merge(mut intervals: Vec>) -> Vec> { 5 | let mut merged: Vec> = Vec::new(); 6 | if intervals.len() == 0 { return merged; } 7 | 8 | intervals.sort(); 9 | 10 | for i in 0..intervals.len() { 11 | let len = merged.len(); 12 | if merged.is_empty() || merged[len-1][1] < intervals[i][0] { 13 | merged.push(intervals[i].clone()); 14 | } else { 15 | merged[len-1][1] = merged[len-1][1].max(intervals[i][1]); 16 | } 17 | } 18 | 19 | return merged; 20 | } 21 | } 22 | 23 | fn main() { 24 | let mut intervals = Vec::new(); 25 | intervals.push(vec![15, 18]); 26 | intervals.push(vec![2, 6]); 27 | intervals.push(vec![8, 10]); 28 | intervals.push(vec![1, 3]); 29 | 30 | println!("{:?}", Solution::merge(intervals)); 31 | } 32 | -------------------------------------------------------------------------------- /algorithm/sort/merge_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "merge_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/merge_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | pub fn merge_sort(mut nums: Vec) -> Vec { 2 | if nums.is_empty() { return nums; } 3 | 4 | let n = nums.len() - 1; 5 | merge_sort_recursion(&mut nums, 0, n); 6 | nums 7 | } 8 | 9 | fn merge_sort_recursion(nums: &mut Vec, left: usize, right: usize) { 10 | if left >= right { return; } 11 | let middle = left + (right - left) / 2; 12 | 13 | merge_sort_recursion(nums, left, middle); 14 | merge_sort_recursion(nums, middle + 1, right); 15 | 16 | merge(nums, left, middle, right); 17 | } 18 | 19 | fn merge(nums: &mut Vec, left: usize, middle: usize, right: usize) { 20 | let mut i = left; 21 | let mut j = middle + 1; 22 | let mut k = left; 23 | let mut tmp = vec![]; 24 | 25 | while k <= right { 26 | if i > middle { 27 | tmp.push(nums[j]); 28 | j += 1; 29 | k += 1; 30 | } else if j > right { 31 | tmp.push(nums[i]); 32 | i += 1; 33 | k += 1; 34 | } else if nums[i] < nums[j] { 35 | tmp.push(nums[i]); 36 | i += 1; 37 | k += 1; 38 | } else { 39 | tmp.push(nums[j]); 40 | j += 1; 41 | k += 1; 42 | } 43 | } 44 | 45 | for i in 0..=(right - left) { 46 | nums[left + i] = tmp[i]; 47 | } 48 | 49 | println!("{:?}", nums); 50 | } 51 | 52 | fn main() { 53 | let nums = vec![7, 9, 12, 11, 6, 3]; 54 | merge_sort(nums); 55 | } 56 | -------------------------------------------------------------------------------- /algorithm/sort/quick_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "quick_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/quick_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | pub fn quick_sort(mut nums: Vec) -> Vec { 2 | if nums.is_empty() { return nums; } 3 | 4 | let len = nums.len(); 5 | quick_sort_recursion(&mut nums, 0, len - 1); 6 | nums 7 | } 8 | 9 | fn quick_sort_recursion(nums: &mut Vec, left: usize, right: usize) { 10 | if left >= right { return; } 11 | 12 | let pivot = partition(nums, left, right); 13 | if pivot != 0 { 14 | quick_sort_recursion(nums, left, pivot - 1); 15 | } 16 | quick_sort_recursion(nums, pivot + 1, right); 17 | } 18 | 19 | fn partition(nums: &mut Vec, left: usize, right: usize) -> usize { 20 | let pivot = right; 21 | let mut i = left; 22 | 23 | for j in left..right { 24 | if nums[j] < nums[pivot] { 25 | nums.swap(i, j); 26 | i += 1; 27 | } 28 | } 29 | 30 | nums.swap(i, right); 31 | println!("{:?}", nums); 32 | i 33 | } 34 | 35 | fn main() { 36 | let nums = vec![7, 9, 12, 11, 6, 3]; 37 | quick_sort(nums); 38 | } 39 | -------------------------------------------------------------------------------- /algorithm/sort/selection_sort/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "selection_sort" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /algorithm/sort/selection_sort/src/main.rs: -------------------------------------------------------------------------------- 1 | fn selection_sort(mut nums: Vec) -> Vec { 2 | if nums.is_empty() { return vec![]; } 3 | 4 | for i in 0..nums.len() - 1 { 5 | let mut min_index = i; 6 | 7 | for j in i + 1..nums.len() { 8 | if nums[j] < nums[min_index] { 9 | min_index = j; 10 | } 11 | } 12 | 13 | if i != min_index { 14 | nums.swap(i, min_index); 15 | } 16 | 17 | println!("{:?}", nums); 18 | } 19 | 20 | nums 21 | } 22 | 23 | fn main() { 24 | let nums = vec![7, 9, 12, 11, 6, 3]; 25 | selection_sort(nums); 26 | } 27 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "phrases_lib" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/chinese.rs: -------------------------------------------------------------------------------- 1 | mod greetings; 2 | mod farewells; 3 | 4 | pub use self::greetings::hello; 5 | pub use self::farewells::goodbye; 6 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/chinese/farewells.rs: -------------------------------------------------------------------------------- 1 | pub fn goodbye() -> String { 2 | "再见。".to_string() 3 | } 4 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/chinese/greetings.rs: -------------------------------------------------------------------------------- 1 | pub fn hello() -> String { 2 | "你好!".to_string() 3 | } 4 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/english/farewells.rs: -------------------------------------------------------------------------------- 1 | pub fn goodbye() -> String { 2 | "Goodbye.".to_string() 3 | } 4 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/english/greetings.rs: -------------------------------------------------------------------------------- 1 | pub fn hello() -> String { 2 | "Hello!".to_string() 3 | } 4 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/english/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod greetings; 2 | pub mod farewells; 3 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod chinese; 2 | pub mod english; 3 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_lib/src/main.rs: -------------------------------------------------------------------------------- 1 | use phrases_lib::chinese; 2 | use phrases_lib::english::{greetings, farewells}; 3 | 4 | fn main() { 5 | println!("Hello in chinese: {}", chinese::hello()); 6 | println!("Goodbye in chinese: {}", chinese::goodbye()); 7 | 8 | println!("Hello in English: {}", greetings::hello()); 9 | println!("Goodbye in English: {}", farewells::goodbye()); 10 | } -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_use/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "phrases_use" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | phrases_lib = { path = "../phrases_lib" } 11 | -------------------------------------------------------------------------------- /chapter/chapter_10/phrases/phrases_use/src/main.rs: -------------------------------------------------------------------------------- 1 | use phrases_lib::chinese; 2 | use phrases_lib::english::{greetings, farewells}; 3 | 4 | fn main() { 5 | println!("Hello in chinese: {}", chinese::hello()); 6 | println!("Goodbye in chinese: {}", chinese::goodbye()); 7 | 8 | println!("Hello in English: {}", greetings::hello()); 9 | println!("Goodbye in English: {}", farewells::goodbye()); 10 | } -------------------------------------------------------------------------------- /chapter/chapter_11/arithmetic/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "arithmetic" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_11/arithmetic/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn is_positive(x: i32) -> bool { 2 | x > 0 3 | } 4 | 5 | pub fn add(x: i32, y: i32) -> i32 { 6 | x + y 7 | } 8 | 9 | pub fn subtract(x: i32, y: i32) -> i32 { 10 | x - y 11 | } 12 | 13 | pub fn multiply(x: i32, y: i32) -> i32 { 14 | x * y 15 | } 16 | 17 | pub fn divide(x: i32, y: i32) -> i32 { 18 | x / y 19 | } 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use super::*; 24 | 25 | #[test] 26 | fn is_positive_test() { 27 | assert!(is_positive(5)); 28 | } 29 | 30 | #[test] 31 | fn add_test() { 32 | assert_eq!(add(5, 3), 8); 33 | } 34 | 35 | #[test] 36 | fn subtract_test() { 37 | assert_ne!(subtract(5, 3), 3); 38 | } 39 | 40 | #[test] 41 | fn multiply_test() { 42 | assert_ne!(multiply(5, 3), 10); 43 | } 44 | 45 | #[test] 46 | #[ignore] 47 | fn divide_test() { 48 | let result = divide(8, 3); 49 | assert_eq!(result, 3, "{} 需要四舍五入成整数 3", result); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /chapter/chapter_2/array_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "array_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/array_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let arr1: [i32; 5] = [1, 2, 3, 4, 5]; 3 | let arr2 = [1, 2, 3, 4, 5]; 4 | let arr3: [i32; 5] = [1; 5]; 5 | let arr4 = [1; 5]; 6 | 7 | println!("{:?}", arr1); 8 | println!("{:?}", arr2); 9 | println!("{:?}", arr3); 10 | println!("{:?}", arr4); 11 | println!("arr1[0]: {}, arr3[2]: {}", arr1[0], arr3[2]); 12 | } 13 | -------------------------------------------------------------------------------- /chapter/chapter_2/data_type_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "data_type_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/data_type_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let integer1: u32 = 17; 3 | let integer2 = 17u32; 4 | let integer3 = 17; 5 | let integer4: u32 = 0b10001; 6 | let integer5: u32 = 0o21; 7 | let integer6: u32 = 0x11; 8 | let integer7 = 50_000; 9 | 10 | println!("{}", integer1); 11 | println!("{}", integer2); 12 | println!("{}", integer3); 13 | println!("{}", integer4); 14 | println!("{}", integer5); 15 | println!("{}", integer6); 16 | println!("{}", integer7); 17 | 18 | let float1: f32 = 1.1; 19 | let float2 = 2.2f32; 20 | let float3 = 3.3; 21 | let float4 = 11_000.555_001; 22 | 23 | println!("{}", float1); 24 | println!("{}", float2); 25 | println!("{}", float3); 26 | println!("{}", float4); 27 | 28 | let t = true; 29 | let f: bool = false; 30 | println!("{}", t); 31 | println!("{}", f); 32 | 33 | let z = 'z'; 34 | let zz = 'ℤ'; 35 | let heart_eyed_cat = '😻'; 36 | println!("{}", z); 37 | println!("{}", zz); 38 | println!("{}", heart_eyed_cat); 39 | 40 | print!("(1..5): "); 41 | for i in 1..5 { 42 | print!("{} ", i); 43 | } 44 | println!(); 45 | 46 | print!("(1..=5).rev: "); 47 | for i in (1..=5).rev() { 48 | print!("{} ", i); 49 | } 50 | println!(); 51 | 52 | let sum: i32 = (1..=5).sum(); 53 | println!("1 + 2 + 3 + 4 + 5 = {}", sum); 54 | } 55 | -------------------------------------------------------------------------------- /chapter/chapter_2/enum_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "enum_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/enum_example/src/main.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | enum ColorNoParam { 3 | Red, 4 | Yellow, 5 | Blue, 6 | } 7 | 8 | #[derive(Debug)] 9 | enum ColorParam { 10 | Red(String), 11 | Yellow(String), 12 | Blue(String), 13 | } 14 | 15 | fn main() { 16 | let color_no_param = ColorNoParam::Red; 17 | match color_no_param { 18 | ColorNoParam::Red => println!("{:?}", ColorNoParam::Red), 19 | ColorNoParam::Yellow => println!("{:?}", ColorNoParam::Yellow), 20 | ColorNoParam::Blue => println!("{:?}", ColorNoParam::Blue), 21 | } 22 | 23 | println!("{:?}", ColorParam::Blue(String::from("blue"))); 24 | } 25 | -------------------------------------------------------------------------------- /chapter/chapter_2/hashmap_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hashmap_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/hashmap_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | fn main() { 4 | let mut map: HashMap<&str, i32> = HashMap::new(); 5 | 6 | let zhangsan1 = map.insert("zhangsan", 97); 7 | map.insert("lisi", 86); 8 | 9 | println!("{:?}", zhangsan1); 10 | println!("{:?}", map); 11 | 12 | let zhangsan2 = map.insert("zhangsan", 79); 13 | println!("{:?}", zhangsan2); 14 | println!("{:?}", map); 15 | 16 | let mut map: HashMap<&str, i32> = HashMap::new(); 17 | map.entry("zhangsan").or_insert(97); 18 | map.entry("lisi").or_insert(86); 19 | println!("{:?}", map); 20 | 21 | map.entry("zhangsan").or_insert(79); 22 | println!("{:?}", map); 23 | 24 | map.insert("zhangsan", 97); 25 | map.insert("lisi", 86); 26 | map.insert("wangwu", 55); 27 | println!("{:?}", map); 28 | 29 | for (_, val) in map.iter_mut() { 30 | *val += 2; 31 | } 32 | println!("{:?}", map); 33 | 34 | let result = map.remove("wangwu"); 35 | println!("{:?}", map); 36 | println!("{:?}", result); 37 | 38 | println!("zhangsan: {}", map["zhangsan"]); 39 | // println!("wangwu: {}", map["wangwu"]); 40 | 41 | println!("zhangsan: {:?}", map.get("zhangsan")); 42 | println!("wangwu: {:?}", map.get("wangwu")); 43 | } 44 | -------------------------------------------------------------------------------- /chapter/chapter_2/mutable_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mutable_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/mutable_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut x = 3; 3 | x = 5; 4 | println!("x: {}", x); 5 | } 6 | -------------------------------------------------------------------------------- /chapter/chapter_2/shadow_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "shadow_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/shadow_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x = 3; 3 | let x = x + 2; 4 | let x = x * 2; 5 | println!("x: {}", x); 6 | 7 | let x = "Hello, Rust!"; 8 | println!("x: {}", x); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/string_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "string_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/string_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut s = String::from("Hello, "); 3 | s.push('R'); 4 | s.push_str("ust!"); 5 | println!("{}", s); 6 | 7 | let mut s = String::from("Hello World!"); 8 | s.insert(5, ','); 9 | s.insert_str(7, "Rust "); 10 | println!("{}", s); 11 | 12 | let s1 = String::from("Hello"); 13 | let s2 = String::from(", "); 14 | let s3 = String::from("Rust "); 15 | let s4 = "World"; 16 | let mut s = s1 + &s2 + s3.as_str() + s4; 17 | s += "!"; 18 | println!("{}", s); 19 | 20 | let s1 = String::from("Hello"); 21 | let s2 = String::from("Rust"); 22 | let s3 = "World"; 23 | let s = format!("{}-{}-{}", s1, s2, s3); 24 | 25 | println!("{}", s); 26 | 27 | let s = String::from("aaabbbbccaadd"); 28 | let s1 = s.replace("aa", "77"); 29 | let s2 = s.replacen("aa", "77", 1); 30 | 31 | println!("{}", s1); 32 | println!("{}", s2); 33 | 34 | let mut s = String::from("Löwe 老虎 Léopard"); 35 | 36 | println!("{:?}", s.pop()); 37 | println!("{}", s); 38 | 39 | println!("{:?}", s.remove(9)); 40 | println!("{}", s); 41 | 42 | s.truncate(9); 43 | println!("{}", s); 44 | 45 | s.clear(); 46 | println!("{}", s); 47 | 48 | let s = String::from("Löwe 老虎"); 49 | println!("Löwe 老虎: {}", s.len()); 50 | 51 | let s = String::from("L"); 52 | println!("L: {}", s.len()); 53 | 54 | let s = String::from("ö"); 55 | println!("ö: {}", s.len()); 56 | 57 | let s = String::from("老"); 58 | println!("老: {}", s.len()); 59 | 60 | let s = String::from("Löwe 老虎"); 61 | let bytes = s.bytes(); 62 | for b in bytes { 63 | print!("{} | ", b); 64 | } 65 | 66 | println!(); 67 | 68 | let chars = s.chars(); 69 | for c in chars { 70 | print!("{} | ", c); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /chapter/chapter_2/struct_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "struct_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/struct_example/src/main.rs: -------------------------------------------------------------------------------- 1 | pub struct Student { 2 | name: &'static str, 3 | score: i32, 4 | } 5 | 6 | fn main() { 7 | let score = 59; 8 | let username = "zhangsan"; 9 | 10 | let mut student = Student { 11 | score, 12 | name: username, 13 | }; 14 | 15 | student.score = 60; 16 | println!("name: {}, score: {}", student.name, student.score); 17 | 18 | let student2 = Student { 19 | name: "lisi", 20 | ..student 21 | }; 22 | 23 | println!("name: {}, score: {}", student2.name, student2.score); 24 | } 25 | -------------------------------------------------------------------------------- /chapter/chapter_2/tuple_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tuple_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/tuple_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let tup1: (i8, f32, bool) = (-10, 7.7, false); 3 | let tup2 = (7.7, (false, 10)); 4 | let tup3 = (100, ); 5 | 6 | println!("{}, {}", tup1.0, (tup2.1).1); 7 | println!("{}", tup3.0); 8 | 9 | let (x, y, z) = tup1; 10 | println!("x: {}, y: {}, z: {}", x, y, z); 11 | } 12 | -------------------------------------------------------------------------------- /chapter/chapter_2/vec_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vec_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/vec_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut v: Vec = Vec::new(); 3 | v.push(1); 4 | v.push(2); 5 | v.push(3); 6 | 7 | v[1] = 5; 8 | println!("v: {:?}", v); 9 | 10 | let mut v: Vec = Vec::with_capacity(10); 11 | v.push(1); 12 | v.push(2); 13 | v.push(3); 14 | 15 | println!("e: {:?}", v.pop()); 16 | println!("v: {:?}", v); 17 | 18 | let mut v = vec![1, 2, 3]; 19 | 20 | println!("e: {}", v.remove(1)); 21 | println!("v: {:?}", v); 22 | 23 | let v = vec![1, 2, 3]; 24 | println!("e: {}", v[2]); 25 | // println!("e: {}", v[10]); 26 | 27 | println!("e: {:?}", v.get(2)); 28 | println!("e: {:?}", v.get(10)); 29 | 30 | let v = vec![10, 20, 30]; 31 | for i in v { 32 | print!("{} ", i); 33 | } 34 | 35 | let mut v = vec![10, 20, 30]; 36 | for i in &mut v { 37 | *i += 50; 38 | print!("{} ", i); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /chapter/chapter_2/vecdeque_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vecdeque_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_2/vecdeque_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::VecDeque; 2 | 3 | fn main() { 4 | let mut v: VecDeque = VecDeque::new(); 5 | v.push_back(1); 6 | v.push_back(2); 7 | v.push_back(3); 8 | v.push_front(1); 9 | v.push_front(2); 10 | 11 | v[1] = 5; 12 | println!("v: {:?}", v); 13 | 14 | println!("e: {:?}", v.pop_back()); 15 | println!("e: {:?}", v.pop_front()); 16 | println!("v: {:?}", v); 17 | 18 | let mut v: VecDeque = VecDeque::with_capacity(10); 19 | v.push_back(1); 20 | v.push_back(2); 21 | v.push_back(3); 22 | 23 | println!("e: {:?}", v.remove(1)); 24 | println!("e: {:?}", v.remove(5)); 25 | println!("v: {:?}", v); 26 | 27 | println!("e: {}", v[0]); 28 | // println!("e: {}", v[10]); 29 | 30 | println!("e: {:?}", v.get(0)); 31 | println!("e: {:?}", v.get(10)); 32 | } 33 | -------------------------------------------------------------------------------- /chapter/chapter_3/if_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "if_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_3/if_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn if_simple(age: i32) { 2 | if age > 18 { 3 | println!("You are an adult."); 4 | } 5 | } 6 | 7 | fn if_else(age: i32) { 8 | if age > 18 { 9 | println!("You are an adult."); 10 | } else { 11 | println!("You are not an adult"); 12 | } 13 | } 14 | 15 | fn if_elseif_else(age: i32) { 16 | if age < 1 { 17 | println!("You are a baby."); 18 | } else if age < 3 { 19 | println!("You are a toddler."); 20 | } else if age < 5 { 21 | println!("You are a preschooler."); 22 | } else if age < 10 { 23 | println!("You are a schoolchild."); 24 | } else if age < 12 { 25 | println!("You are a preteen."); 26 | } else if age < 18 { 27 | println!("You are a teenager."); 28 | } else { 29 | println!("You are an adult."); 30 | } 31 | } 32 | 33 | fn main() { 34 | if_simple(20); 35 | if_else(15); 36 | if_elseif_else(15); 37 | } 38 | -------------------------------------------------------------------------------- /chapter/chapter_3/iflet_whilelet_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iflet_whilelet_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_3/iflet_whilelet_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn match_value(value: Option) { 2 | match value { 3 | Some(7) => println!("seven"), 4 | _ => (), 5 | } 6 | } 7 | 8 | fn if_let_value(value: Option) { 9 | if let Some(7) = value { 10 | println!("seven"); 11 | } 12 | } 13 | 14 | fn match_vec() { 15 | let mut vec = vec![1, 2, 3, 4, 5]; 16 | loop { 17 | match vec.pop() { 18 | Some(value) => println!("{}", value), 19 | None => break, 20 | } 21 | } 22 | } 23 | 24 | fn while_let_vec() { 25 | let mut vec = vec![1, 2, 3, 4, 5]; 26 | while let Some(value) = vec.pop() { 27 | println!("{}", value); 28 | } 29 | } 30 | 31 | fn main() { 32 | match_value(Some(7)); 33 | if_let_value(Some(5)); 34 | 35 | match_vec(); 36 | while_let_vec(); 37 | } 38 | -------------------------------------------------------------------------------- /chapter/chapter_3/loop_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "loop_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_3/loop_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn loop_counter() { 2 | let mut count = 0; 3 | let counter = loop { 4 | count += 1; 5 | let counter = count * 2; 6 | println!("count: {}, counter: {}", count, counter); 7 | 8 | if count == 10 { 9 | break counter; 10 | } 11 | }; 12 | } 13 | 14 | fn while_counter() { 15 | let mut count = 0; 16 | let mut counter = 0; 17 | while count != 10 { 18 | count += 1; 19 | counter = count * 2; 20 | println!("count: {}, counter: {}", count, counter); 21 | } 22 | } 23 | 24 | fn for_counter() { 25 | let mut counter = 0; 26 | for count in 1..=10 { 27 | counter = count * 2; 28 | println!("count: {}, counter: {}", count, counter); 29 | } 30 | } 31 | 32 | fn continue_break() { 33 | for i in 0..10 { 34 | if i == 0 || i == 4 { continue; } 35 | if i == 6 { break; } 36 | 37 | println!("i: {}", i); 38 | }; 39 | } 40 | 41 | fn main() { 42 | loop_counter(); 43 | while_counter(); 44 | for_counter(); 45 | continue_break(); 46 | } 47 | -------------------------------------------------------------------------------- /chapter/chapter_3/match_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "match_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_3/match_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let age = 6; 3 | 4 | match age { 5 | 0 => println!("You are a baby."), 6 | 1..=2 => println!("You are a toddler."), 7 | 3..=4 => println!("You are a preschooler."), 8 | 5..=9 => println!("You are a schoolchild."), 9 | 10..=11 => println!("You are a preteen."), 10 | 12..=17 => println!("You are a teenager."), 11 | 18..=100 => println!("You are an adult."), 12 | _ => (), 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_filter_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adapter_filter_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_filter_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3]; 3 | 4 | let result: Vec = v.iter() 5 | .map(|x| x + 3) 6 | .filter(|x| x % 3 == 0) 7 | .collect(); 8 | 9 | println!("{:?}", result); 10 | } 11 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_map_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adapter_map_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_map_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3]; 3 | 4 | let result: Vec = v.iter() 5 | .map(|x| x + 3) 6 | .collect(); 7 | 8 | println!("{:?}", result); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_rev_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adapter_rev_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_rev_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3]; 3 | let result = v.iter().rev(); 4 | 5 | for i in result { 6 | println!("{}", i); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_take_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adapter_take_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_take_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3, 4, 5]; 3 | let result = v.iter().take(3); 4 | 5 | for i in result { 6 | println!("{}", i); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_zip_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "adapter_zip_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/adapter_zip_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v1 = [1, 2, 3]; 3 | let v2 = [2, 3, 6]; 4 | 5 | let result: Vec = v1.iter().zip(v2.iter()) 6 | .map(|(a, b)| a + b) 7 | .filter(|x| x % 3 == 0) 8 | .collect(); 9 | 10 | println!("{:?}", result); 11 | } 12 | -------------------------------------------------------------------------------- /chapter/chapter_4/closure_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "closure_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/closure_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | fn add_one_v1(x: u32) -> u32 { x + 1 } 3 | let add_one_v2 = |x: u32| -> u32 { x + 1 }; 4 | let add_one_v3 = |x| { x + 1 }; 5 | let add_one_v4 = |x| x + 1; 6 | 7 | println!("add_one_v1: {}", add_one_v1(1)); 8 | println!("add_one_v2: {}", add_one_v2(1)); 9 | println!("add_one_v3: {}", add_one_v3(1)); 10 | println!("add_one_v4: {}", add_one_v4(1)); 11 | 12 | let i = 1; 13 | let add = |x| { 14 | x + i 15 | }; 16 | 17 | println!("add result: {}", add(7)); 18 | } 19 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_any_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "consumer_any_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_any_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 3, 4, 5]; 3 | let result1 = v.iter().any(|&x| x == 2); 4 | let result2 = v.iter().any(|x| *x == 2); 5 | // let result3 = v.iter().any(|x| x == 2); 6 | 7 | println!("{}", result1); 8 | println!("{}", result2); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_collect_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "consumer_collect_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_collect_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v1 = [1, 2, 3, 4, 5]; 3 | let v2: Vec = v1.iter().map(|x| x + 1).collect(); 4 | 5 | println!("{:?}", v2); 6 | } 7 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_sum_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "consumer_sum_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/consumer_sum_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3]; 3 | let total: i32 = v.iter().sum(); 4 | 5 | println!("total: {}", total); 6 | } 7 | -------------------------------------------------------------------------------- /chapter/chapter_4/function_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "function_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/function_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn add(x: i32, y: i32) -> i32 { 2 | x + y 3 | } 4 | 5 | fn main() { 6 | let x = 5; 7 | let y = { 8 | let x = 2; 9 | x + 1 10 | }; 11 | 12 | let sum = add(x, y); 13 | println!("{} + {} = {}", x, y, sum); 14 | } 15 | -------------------------------------------------------------------------------- /chapter/chapter_4/function_pointer_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "function_pointer_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/function_pointer_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn hello() { 2 | println!("hello function pointer!"); 3 | } 4 | 5 | fn main() { 6 | let fn_ptr: fn() = hello; 7 | println!("{:p}", fn_ptr); 8 | 9 | let other_fn = hello; 10 | // println!("{:p}", other_fn); 11 | 12 | fn_ptr(); 13 | other_fn(); 14 | } 15 | -------------------------------------------------------------------------------- /chapter/chapter_4/higher_order_function_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "higher_order_function_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/higher_order_function_example/src/main.rs: -------------------------------------------------------------------------------- 1 | type MathOp = fn(i32, i32) -> i32; 2 | 3 | fn math(op: MathOp, x: i32, y: i32) -> i32 { 4 | println!("{:p}", op); 5 | op(x, y) 6 | } 7 | 8 | fn math_op(op: &str) -> MathOp { 9 | match op { 10 | "add" => add, 11 | _ => subtract, 12 | } 13 | } 14 | 15 | fn add(x: i32, y: i32) -> i32 { 16 | x + y 17 | } 18 | 19 | fn subtract(x: i32, y: i32) -> i32 { 20 | x - y 21 | } 22 | 23 | fn main() { 24 | let (x, y) = (8, 3); 25 | println!("add operation result: {}", math(add, x, y)); 26 | println!("subtraction operation result: {}", math(subtract, x, y)); 27 | 28 | let mut op = math_op("add"); 29 | println!("operation result: {}", op(x, y)); 30 | op = math_op("divide"); 31 | println!("operation result: {}", op(x, y)); 32 | } 33 | -------------------------------------------------------------------------------- /chapter/chapter_4/iterator_next_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iterator_next_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/iterator_next_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let v = [1, 2, 3]; 3 | let mut iter = v.iter(); 4 | 5 | println!("{:?}", iter.next()); 6 | println!("{:?}", iter.next()); 7 | println!("{:?}", iter.next()); 8 | println!("{:?}", iter.next()); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/struct_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "struct_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_4/struct_example/src/main.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, PartialEq)] 2 | pub struct Student { 3 | name: &'static str, 4 | score: i32, 5 | } 6 | 7 | impl Student { 8 | pub fn new(name: &'static str, score: i32) -> Self { 9 | Student { name, score } 10 | } 11 | 12 | pub fn get_name(&self) -> &str { 13 | self.name 14 | } 15 | 16 | pub fn set_name(&mut self, name: &'static str) { 17 | self.name = name; 18 | } 19 | 20 | pub fn get_score(&self) -> i32 { 21 | self.score 22 | } 23 | 24 | pub fn set_score(&mut self, score: i32) { 25 | self.score = score; 26 | } 27 | } 28 | 29 | fn main() { 30 | let mut student: Student = Student::new("zhangsan", 59); 31 | println!("name: {}, score: {}", student.get_name(), student.get_score()); 32 | 33 | student.set_score(60); 34 | println!("{:?}", student); 35 | } 36 | -------------------------------------------------------------------------------- /chapter/chapter_5/collection_generic_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "collection_generic_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/collection_generic_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut vec_integer: Vec = vec![10, 20]; 3 | vec_integer.push(30); 4 | // vec_integer.push("hello"); 5 | 6 | println!("{:?}", vec_integer); 7 | } 8 | -------------------------------------------------------------------------------- /chapter/chapter_5/debug_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "debug_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/debug_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Display, Formatter, Result}; 2 | 3 | #[derive(Debug)] 4 | struct Point { 5 | x: i32, 6 | y: i32, 7 | } 8 | 9 | impl Display for Point { 10 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 11 | write!(f, "({}, {})", self.x, self.y) 12 | } 13 | } 14 | 15 | fn main() { 16 | let origin = Point { x: 0, y: 0 }; 17 | println!("{}", origin); 18 | println!("{:?}", origin); 19 | println!("{:#?}", origin); 20 | } 21 | -------------------------------------------------------------------------------- /chapter/chapter_5/default_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "default_example" 3 | version = "0.1.0" 4 | authors = ["anray "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/default_example/src/main.rs: -------------------------------------------------------------------------------- 1 | #[derive(Default, Debug)] 2 | struct MyStruct { 3 | foo: i32, 4 | bar: f32, 5 | } 6 | 7 | fn main() { 8 | let options1: MyStruct = Default::default(); 9 | let options2 = MyStruct { foo: 7, ..Default::default() }; 10 | 11 | println!("options1: {:?}", options1); 12 | println!("options2: {:?}", options2); 13 | } -------------------------------------------------------------------------------- /chapter/chapter_5/enum_generic_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "enum_generic_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/enum_generic_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn option_add(x: Option, y: Option) -> Option { 2 | return if x.is_none() && y.is_none() { None } 3 | else if x.is_none() { y } 4 | else if y.is_none() { x } 5 | else { Some(x.unwrap() + y.unwrap()) }; 6 | } 7 | 8 | fn option_print(opt: Option) { 9 | match opt { 10 | Some(result) => println!("Option: {}", result), 11 | _ => println!("Option is None!"), 12 | } 13 | } 14 | 15 | fn main() { 16 | let result1 = option_add(Some(3), Some(5)); 17 | let result2 = option_add(Some(3), None); 18 | let result3 = option_add(None, None); 19 | 20 | option_print(result1); 21 | option_print(result2); 22 | option_print(result3); 23 | } 24 | -------------------------------------------------------------------------------- /chapter/chapter_5/ord_partialord_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ord_partialord_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/ord_partialord_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::Ordering; 2 | 3 | #[derive(Eq)] 4 | struct Person { 5 | id: u32, 6 | name: String, 7 | height: u32, 8 | } 9 | 10 | impl Ord for Person { 11 | fn cmp(&self, other: &Person) -> Ordering { 12 | self.height.cmp(&other.height) 13 | } 14 | } 15 | 16 | impl PartialOrd for Person { 17 | fn partial_cmp(&self, other: &Person) -> Option { 18 | Some(self.cmp(other)) 19 | } 20 | } 21 | 22 | impl PartialEq for Person { 23 | fn eq(&self, other: &Person) -> bool { 24 | self.height == other.height 25 | } 26 | } 27 | 28 | fn main() { 29 | let person1 = Person { id: 1, name: String::from("zhangsan"), height: 168 }; 30 | let person2 = Person { id: 2, name: String::from("lisi"), height: 175 }; 31 | let person3 = Person { id: 3, name: String::from("wanwu"), height: 180 }; 32 | 33 | assert_eq!(person1 < person2, true); 34 | assert_eq!(person2 > person3, false); 35 | 36 | assert!(person1.lt(&person2)); 37 | assert!(person3.gt(&person2)); 38 | 39 | let tallest_person = person1.max(person2).max(person3); 40 | println!("id: {}, name: {}", tallest_person.id, tallest_person.name); 41 | } 42 | -------------------------------------------------------------------------------- /chapter/chapter_5/partialeq_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "partialeq_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/partialeq_example/src/main.rs: -------------------------------------------------------------------------------- 1 | enum BookFormat { 2 | Paperback, 3 | Hardback, 4 | Ebook, 5 | } 6 | 7 | struct Book { 8 | isbn: i32, 9 | format: BookFormat, 10 | } 11 | 12 | impl PartialEq for Book { 13 | fn eq(&self, other: &Self) -> bool { 14 | self.isbn == other.isbn 15 | } 16 | } 17 | 18 | fn main() { 19 | let b1 = Book { isbn: 3, format: BookFormat::Paperback }; 20 | let b2 = Book { isbn: 3, format: BookFormat::Ebook }; 21 | let b3 = Book { isbn: 5, format: BookFormat::Paperback }; 22 | 23 | assert!(b1 == b2); 24 | assert!(b1 != b3); 25 | } 26 | -------------------------------------------------------------------------------- /chapter/chapter_5/struct_generic_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "struct_generic_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/struct_generic_example/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Rectangle1 { 2 | width: T, 3 | height: T, 4 | } 5 | 6 | struct Rectangle2 { 7 | width: T, 8 | height: U, 9 | } 10 | 11 | impl Rectangle1 { 12 | fn width(&self) -> &T { 13 | &self.width 14 | } 15 | 16 | fn height(&self) -> &T { 17 | &self.height 18 | } 19 | } 20 | 21 | impl Rectangle1 { 22 | fn area(&self) -> i32 { 23 | self.width * self.height 24 | } 25 | } 26 | 27 | impl Rectangle2 { 28 | fn width(&self) -> &T { 29 | &self.width 30 | } 31 | 32 | fn height(&self) -> &U { 33 | &self.height 34 | } 35 | } 36 | 37 | fn main() { 38 | // let rect = Rectangle1 { width: 8, height: 2.2 }; 39 | let rect1 = Rectangle1 { width: 8, height: 2 }; 40 | println!("rect1.width: {}, rect1.height: {}", rect1.width(), rect1.height()); 41 | println!("rect1.area: {}", rect1.area()); 42 | 43 | let rect2 = Rectangle2 { width: 8, height: 2.2 }; 44 | println!("rect2.width: {}, rect2.height: {}", rect2.width(), rect2.height()); 45 | } 46 | -------------------------------------------------------------------------------- /chapter/chapter_5/trait_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trait_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/trait_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Display, Formatter, Result}; 2 | 3 | trait Geometry { 4 | fn area(&self) -> f32; 5 | 6 | fn perimeter(&self) -> f32; 7 | } 8 | 9 | #[derive(Clone, Copy)] 10 | struct Rectangle { 11 | width: f32, 12 | height: f32, 13 | } 14 | 15 | impl Geometry for Rectangle { 16 | fn area(&self) -> f32 { 17 | self.width * self.height 18 | } 19 | 20 | fn perimeter(&self) -> f32 { 21 | (self.width + self.height) * 2.0 22 | } 23 | } 24 | 25 | impl Display for Rectangle { 26 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 27 | write!(f, "Rectangle: ({}, {})", self.width, self.height) 28 | } 29 | } 30 | 31 | #[derive(Clone, Copy)] 32 | struct Circle { 33 | radius: f32, 34 | } 35 | 36 | impl Geometry for Circle { 37 | fn area(&self) -> f32 { 38 | 3.14 * self.radius * self.radius 39 | } 40 | 41 | fn perimeter(&self) -> f32 { 42 | 3.14 * 2.0 * self.radius 43 | } 44 | } 45 | 46 | impl Display for Circle { 47 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 48 | write!(f, "Circle: ({})", self.radius) 49 | } 50 | } 51 | 52 | fn main() { 53 | let rect = Rectangle { width: 10.5, height: 5.5 }; 54 | print_by_impl_trait(rect); 55 | 56 | let circle = Circle { radius: 3.0 }; 57 | print_by_trait_bound(circle); 58 | 59 | area_add_by_impl_trait(rect, circle); 60 | area_add_by_trait_bound(rect, circle); 61 | 62 | let geometry = return_geometry(); 63 | // area_add_by_impl_trait(geometry, circle); 64 | area_add_by_impl_trait(geometry, rect); 65 | } 66 | 67 | fn return_geometry() -> impl Geometry { 68 | Rectangle { 69 | width: 12.5, 70 | height: 5.5, 71 | } 72 | } 73 | 74 | fn print_by_impl_trait(geometry: impl Geometry + Display) { 75 | println!("{}, area: {}, perimeter: {}", 76 | geometry, geometry.area(), geometry.perimeter()); 77 | } 78 | 79 | fn print_by_trait_bound(geometry: T) { 80 | println!("{}, area: {}, perimeter: {}", 81 | geometry, geometry.area(), geometry.perimeter()); 82 | } 83 | 84 | fn area_add_by_impl_trait(geo1: impl Geometry, geo2: impl Geometry) { 85 | println!("geo1.area: {}, geo2.area: {}, total area: {}", 86 | geo1.area(), geo2.area(), geo1.area() + geo2.area()); 87 | } 88 | 89 | fn area_add_by_trait_bound(geo1: T, geo2: U) { 90 | println!("geo1.area: {}, geo2.area: {}, total area: {}", 91 | geo1.area(), geo2.area(), geo1.area() + geo2.area()); 92 | } 93 | -------------------------------------------------------------------------------- /chapter/chapter_5/type_cast_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "type_cast_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_5/type_cast_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x: u16 = 7; 3 | let y = x as u32; 4 | println!("u16: {}, u32: {}", x, y); 5 | 6 | let x = std::u32::MAX; 7 | let y = x as u16; 8 | println!("u32: {}, u16: {}", x, y); 9 | 10 | let x = 65u8; 11 | let y = x as char; 12 | println!("u8: {}, char: {}", x, y); 13 | 14 | let x = 'A'; 15 | let y = x as u8; 16 | println!("char: {}, u8: {}", x, y); 17 | 18 | let x = 7; 19 | let y = x as f64; 20 | println!("i32: {}, f64: {}", x, y); 21 | 22 | let x = 7.7; 23 | let y = x as i32; 24 | println!("f64: {}, i32: {}", x, y); 25 | 26 | let x = 7; 27 | let y = x.to_string(); 28 | println!("i32: {}, String: {}", x, y); 29 | 30 | let x = 7.7; 31 | let y = x.to_string(); 32 | println!("f64: {}, String: {}", x, y); 33 | 34 | let x = String::from("7"); 35 | let y = x.parse::().unwrap(); 36 | println!("String: {}, i32: {}", x, y); 37 | 38 | let x = String::from("7.7"); 39 | let y = x.parse::().unwrap(); 40 | println!("String: {}, f64: {}", x, y); 41 | 42 | let x = String::from("hello"); 43 | let y = x.as_str(); 44 | println!("String: {}, &str: {}", x, y); 45 | 46 | let x = "hello"; 47 | let y = x.to_string(); 48 | println!("&str: {}, String: {}", x, y); 49 | } 50 | -------------------------------------------------------------------------------- /chapter/chapter_6/iterator_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iterator_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_6/iterator_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let vec = vec!["Java", "Rust", "Python"]; 3 | for str in vec.into_iter() { 4 | match str { 5 | "Rust" => println!("Niubility"), 6 | _ => println!("{}", str), 7 | } 8 | } 9 | 10 | let vec = vec!["Java", "Rust", "Python"]; 11 | for str in vec.iter() { 12 | match str { 13 | &"Rust" => println!("Niubility"), 14 | _ => println!("{}", str), 15 | } 16 | } 17 | 18 | println!("{:?}", vec); 19 | 20 | let mut vec = vec!["Java", "Rust", "Python"]; 21 | for str in vec.iter_mut() { 22 | match str { 23 | &mut "Rust" => { 24 | *str = "Niubility"; 25 | println!("{}", str); 26 | }, 27 | _ => println!("{}", str), 28 | } 29 | } 30 | 31 | println!("{:?}", vec); 32 | } 33 | -------------------------------------------------------------------------------- /chapter/chapter_6/lifetime_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lifetime_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_6/lifetime_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | struct Foo<'a, 'b> { 4 | x: &'a i32, 5 | y: &'b i32, 6 | } 7 | 8 | impl<'a, 'b> Foo<'a, 'b> { 9 | fn x(&self) -> &i32 { self.x } 10 | 11 | fn y(&self) -> &i32 { self.y } 12 | 13 | fn max_x(&'a self, f: &'a Foo) -> &'a i32 { 14 | if self.x > f.x { 15 | self.x 16 | } else { 17 | f.x 18 | } 19 | } 20 | } 21 | 22 | fn main() { 23 | let i = 7; 24 | let r = &i; 25 | println!("r: {}", r); 26 | 27 | let f1 = Foo { x: &3, y: &5 }; 28 | let f2 = Foo { x: &7, y: &9 }; 29 | println!("x: {}, y: {}", f1.x(), f1.y()); 30 | println!("max_x: {}", f1.max_x(&f2)); 31 | 32 | let str1 = String::from("abcd"); 33 | let result; 34 | { 35 | let str2 = "xyz"; 36 | result = long_str(str1.as_str(), str2); 37 | } 38 | println!("longer string: {}", result); 39 | 40 | let str1 = String::from("abcd"); 41 | let str2 = "xyz"; 42 | let result = long_str_with_tip(str1.as_str(), str2, 777); 43 | println!("longer string: {}", result); 44 | } 45 | 46 | fn long_str<'a>(x: &'a str, y: &'a str) -> &'a str { 47 | if x.len() > y.len() { 48 | x 49 | } else { 50 | y 51 | } 52 | } 53 | 54 | fn long_str_with_tip<'a, T>(x: &'a str, y: &'a str, tip: T) -> &'a str 55 | where T: Display { 56 | println!("Tip: {}", tip); 57 | if x.len() > y.len() { 58 | x 59 | } else { 60 | y 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /chapter/chapter_6/ownership_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ownership_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_6/ownership_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | #[derive(Debug, Copy, Clone)] 4 | struct Foo { 5 | x: i32, 6 | y: bool, 7 | } 8 | 9 | fn main() { 10 | let x = 5; 11 | let y = x; 12 | println!("x: {}, y: {}", x, y); 13 | 14 | let foo = Foo { x: 8, y: true }; 15 | let other = foo; 16 | println!("foo: {:?}, other: {:?}", foo, other); 17 | 18 | let s1 = String::from("hello"); 19 | let s2 = s1.clone(); 20 | println!("s1 = {}, s2 = {}", s1, s2); 21 | 22 | let key = String::from("Favorite color"); 23 | let value = String::from("Red"); 24 | 25 | let mut map = HashMap::new(); 26 | map.insert(&key, &value); 27 | println!("{}", map[&key]); 28 | 29 | let s = String::from("hello"); 30 | take_ownership(s); 31 | 32 | let x = 5; 33 | make_copy(x); 34 | 35 | let s1 = give_ownership(); 36 | let s2 = take_and_give_back(s1); 37 | println!("{}", s2); 38 | } 39 | 40 | fn take_ownership(str: String) { 41 | println!("{}", str); 42 | } 43 | 44 | fn make_copy(int: i32) { 45 | println!("{}", int); 46 | } 47 | 48 | fn give_ownership() -> String { 49 | let str = String::from("ownership"); 50 | str 51 | } 52 | 53 | fn take_and_give_back(name: String) -> String { 54 | let hello = String::from("hello"); 55 | hello + " " + &name 56 | } 57 | -------------------------------------------------------------------------------- /chapter/chapter_6/reference_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "reference_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_6/reference_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let vec1 = vec![1, 2, 3]; 3 | let vec2 = vec![4, 5, 6]; 4 | 5 | let answer = sum_vec(&vec1, &vec2); 6 | println!("v1: {:?}, v2: {:?}, sum: {}", vec1, vec2, answer); 7 | 8 | let mut vec = Vec::new(); 9 | push_vec(&mut vec, 1); 10 | push_vec(&mut vec, 2); 11 | push_vec(&mut vec, 2); 12 | push_vec(&mut vec, 5); 13 | println!("vec: {:?}", vec); 14 | 15 | let mut x = 6; 16 | 17 | let y = &mut x; 18 | *y += 1; 19 | 20 | println!("x: {}", x); 21 | } 22 | 23 | fn push_vec(v: &mut Vec, value: i32) { 24 | if v.is_empty() || v.get(v.len() - 1).unwrap() < &value { 25 | v.push(value); 26 | } 27 | } 28 | 29 | fn sum_vec(v1: &Vec, v2: &Vec) -> i32 { 30 | let sum1: i32 = v1.iter().sum(); 31 | let sum2: i32 = v2.iter().sum(); 32 | 33 | sum1 + sum2 34 | } 35 | -------------------------------------------------------------------------------- /chapter/chapter_6/slice_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "slice_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_6/slice_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let s = String::from("Hello, Rust!"); 3 | println!("{}", &s[0..5]); 4 | println!("{}", &s[..5]); 5 | println!("{}", &s[7..s.len()]); 6 | println!("{}", &s[7..]); 7 | println!("{}", &s[0..s.len()]); 8 | println!("{}", &s[..]); 9 | 10 | let vec = vec![1, 2, 3, 4, 5]; 11 | println!("{:?}", &vec[0..2]); 12 | println!("{:?}", &vec[..2]); 13 | println!("{:?}", &vec[2..vec.len()]); 14 | println!("{:?}", &vec[2..]); 15 | println!("{:?}", &vec[0..vec.len()]); 16 | println!("{:?}", &vec[..]); 17 | 18 | let str = "Hello"; 19 | print_str(&s[0..5]); 20 | print_str(&str); 21 | print_vec(&vec[2..]); 22 | 23 | let mut vec = vec![1, 2, 3, 4, 5]; 24 | let vec_slice = &mut vec[3..]; 25 | vec_slice[0] = 7; 26 | println!("{:?}", vec); 27 | } 28 | 29 | fn print_str(s: &str) { 30 | println!("slice: {:?}, length: {}", s, s.len()); 31 | } 32 | 33 | fn print_vec(vec: &[i32]) { 34 | println!("slice: {:?}, length: {}", vec, vec.len()); 35 | } 36 | -------------------------------------------------------------------------------- /chapter/chapter_7/box_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "box_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_7/box_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x:Box = Box::new(5); 3 | let y:Box = x; 4 | 5 | println!("x: {}", x); 6 | println!("y: {}", y); 7 | } 8 | -------------------------------------------------------------------------------- /chapter/chapter_7/deref_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "deref_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_7/deref_example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x: i32 = 5; 3 | let y: &i32 = &x; 4 | 5 | // assert_eq!(5, y); 6 | assert_eq!(5, *y); 7 | println!("pointer: {:p}", y); 8 | 9 | let x: i32 = 5; 10 | let y: Box = Box::new(x); 11 | 12 | assert_eq!(5, *y); 13 | println!("pointer: {:p}", y); 14 | } 15 | -------------------------------------------------------------------------------- /chapter/chapter_7/drop_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "drop_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_7/drop_example/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Custom { 2 | data: String, 3 | } 4 | 5 | impl Drop for Custom { 6 | fn drop(&mut self) { 7 | println!("Dropping Custom with data: {}", self.data); 8 | } 9 | } 10 | 11 | fn main() { 12 | let str1 = Custom { data: String::from("hello world!") }; 13 | let str2 = Custom { data: String::from("hello rust!") }; 14 | 15 | println!("Custom created"); 16 | println!("str1: {}", str1.data); 17 | println!("str2: {}", str2.data); 18 | } 19 | -------------------------------------------------------------------------------- /chapter/chapter_7/rc_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rc_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_7/rc_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | 3 | fn main() { 4 | let x = Rc::new(5); 5 | println!("{:p}, count after constructing x: {}", x, Rc::strong_count(&x)); 6 | let y = x.clone(); 7 | println!("{:p}, count after constructing y: {}", y, Rc::strong_count(&x)); 8 | { 9 | let z = Rc::clone(&x); 10 | println!("{:p}, count after constructing z: {}", z, Rc::strong_count(&x)); 11 | } 12 | 13 | println!("count after destructing z: {}", Rc::strong_count(&x)); 14 | } 15 | -------------------------------------------------------------------------------- /chapter/chapter_7/refcell_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "refcell_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_7/refcell_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | 3 | fn main() { 4 | let v: RefCell> = RefCell::new(vec![1, 2, 3, 4]); 5 | println!("{:?}", v.borrow()); 6 | 7 | v.borrow_mut().push(5); 8 | println!("{:?}", v.borrow()); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_8/async_std_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | async-std = "1.5.0" 11 | -------------------------------------------------------------------------------- /chapter/chapter_8/async_std_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use async_std::task; 2 | use std::time::Duration; 3 | 4 | fn main() { 5 | let async_1 = task::spawn(async { 6 | for i in 1..=5 { 7 | print_async_1(i).await; 8 | } 9 | }); 10 | 11 | let async_2 = task::spawn(async { 12 | for i in 1..=5 { 13 | print_async_2(i).await; 14 | } 15 | }); 16 | 17 | for i in 1..=5 { 18 | println!("number {} from the main!", i); 19 | task::block_on(async { 20 | task::sleep(Duration::from_secs(8)).await; 21 | }); 22 | } 23 | 24 | task::block_on(async_1); 25 | task::block_on(async_2); 26 | } 27 | 28 | async fn print_async_1(i: i32) { 29 | println!("number {} from the async_1!", i); 30 | task::sleep(Duration::from_secs(2)).await; 31 | } 32 | 33 | async fn print_async_2(i: i32) { 34 | println!("number {} from the async_2!", i); 35 | task::sleep(Duration::from_secs(4)).await; 36 | } 37 | -------------------------------------------------------------------------------- /chapter/chapter_8/thread_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "thread_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_8/thread_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::time::Duration; 3 | 4 | fn main() { 5 | let thread_1 = thread::spawn(|| { 6 | for i in 1..=5 { 7 | println!("number {} from the spawned_1 thread!", i); 8 | thread::sleep(Duration::from_secs(2)); 9 | } 10 | }); 11 | 12 | let thread_2 = thread::spawn(|| { 13 | for i in 1..=5 { 14 | println!("number {} from the spawned_2 thread!", i); 15 | thread::sleep(Duration::from_secs(4)); 16 | } 17 | }); 18 | 19 | for i in 1..=5 { 20 | println!("number {} from the main thread!", i); 21 | thread::sleep(Duration::from_secs(8)); 22 | } 23 | 24 | thread_1.join().unwrap(); 25 | thread_2.join().unwrap(); 26 | } 27 | -------------------------------------------------------------------------------- /chapter/chapter_8/thread_move_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "thread_move_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_8/thread_move_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | fn main() { 4 | let v = vec![1, 2, 3, 4, 5]; 5 | 6 | let handle = thread::spawn(move || { 7 | println!("{:?}", v); 8 | }); 9 | 10 | handle.join().unwrap(); 11 | } 12 | -------------------------------------------------------------------------------- /chapter/chapter_8/threadpool_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "threadpool_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | threadpool = "1.7.1" 11 | -------------------------------------------------------------------------------- /chapter/chapter_8/threadpool_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use threadpool::ThreadPool; 2 | 3 | fn main() { 4 | let pool = ThreadPool::new(3); 5 | 6 | for i in 1..=5 { 7 | pool.execute(move || { 8 | println!("number {} from the spawned_1 thread!", i); 9 | }); 10 | } 11 | 12 | for i in 1..=5 { 13 | pool.execute(move || { 14 | println!("number {} from the spawned_2 thread!", i); 15 | }); 16 | } 17 | 18 | for i in 1..=5 { 19 | println!("number {} from the main thread!", i); 20 | } 21 | 22 | pool.join(); 23 | } 24 | -------------------------------------------------------------------------------- /chapter/chapter_9/panic_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "panic_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_9/panic_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::panic; 2 | 3 | fn main() { 4 | let v = vec![1, 2, 3]; 5 | println!("{}", v[0]); 6 | let result = panic::catch_unwind(|| { println!("{}", v[99]) }); 7 | assert!(result.is_err()); 8 | println!("{}", v[1]); 9 | } 10 | -------------------------------------------------------------------------------- /chapter/chapter_9/result_example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "result_example" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /chapter/chapter_9/result_example/hello.txt: -------------------------------------------------------------------------------- 1 | Hello, Rust! -------------------------------------------------------------------------------- /chapter/chapter_9/result_example/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io; 3 | use std::io::ErrorKind; 4 | use std::io::Read; 5 | 6 | fn main() { 7 | println!("content: {}", read_from_file_7().unwrap()); 8 | } 9 | 10 | fn read_from_file_1() { 11 | let f = File::open("hello.txt"); 12 | 13 | let file = match f { 14 | Ok(file) => file, 15 | Err(error) => { 16 | panic!("Failed to open hello.txt: {:?}", error) 17 | } 18 | }; 19 | } 20 | 21 | fn read_from_file_2() { 22 | let file = File::open("hello.txt").expect("Failed to open hello.txt"); 23 | } 24 | 25 | fn read_from_file_3() { 26 | let f = File::open("hello.txt"); 27 | 28 | let file = match f { 29 | Ok(file) => file, 30 | Err(error) => match error.kind() { 31 | ErrorKind::NotFound => match File::create("hello.txt") { 32 | Ok(fc) => fc, 33 | Err(e) => panic!("Failed to create hello.txt: {:?}", e), 34 | }, 35 | other_error => panic!("Failed to open hello.txt: {:?}", other_error), 36 | }, 37 | }; 38 | } 39 | 40 | fn read_from_file_4() { 41 | let f = File::open("hello.txt").unwrap_or_else(|error| { 42 | if error.kind() == ErrorKind::NotFound { 43 | File::create("hello.txt").unwrap_or_else(|error| { 44 | panic!("Failed to create hello.txt: {:?}", error); 45 | }) 46 | } else { 47 | panic!("Failed to open hello.txt: {:?}", error); 48 | } 49 | }); 50 | } 51 | 52 | fn read_from_file_5() -> Result { 53 | let f = File::open("hello.txt"); 54 | 55 | let mut file = match f { 56 | Ok(file) => file, 57 | Err(e) => return Err(e), 58 | }; 59 | 60 | let mut s = String::new(); 61 | 62 | match file.read_to_string(&mut s) { 63 | Ok(_) => Ok(s), 64 | Err(e) => Err(e), 65 | } 66 | } 67 | 68 | fn read_from_file_6() -> Result { 69 | let mut f = File::open("hello.txt")?; 70 | let mut s = String::new(); 71 | f.read_to_string(&mut s)?; 72 | Ok(s) 73 | } 74 | 75 | fn read_from_file_7() -> Result { 76 | let mut s = String::new(); 77 | File::open("hello.txt")?.read_to_string(&mut s)?; 78 | Ok(s) 79 | } 80 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_11_container-with-most-water/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_11_container-with-most-water" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_11_container-with-most-water/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn max_area(height: Vec) -> i32 { 7 | let mut max: i32 = 0; 8 | let mut i: i32 = 0; 9 | let mut j: i32 = height.len() as i32 - 1; 10 | while i < j { 11 | let mut min_height: i32 = 0; 12 | let x = height[i as usize]; 13 | let y = height[j as usize]; 14 | if x < y { 15 | min_height = x; 16 | i += 1; 17 | } else { 18 | min_height = y; 19 | j -= 1; 20 | } 21 | max = cmp::max(max, (j - i + 1) * min_height); 22 | } 23 | 24 | return max; 25 | } 26 | } 27 | 28 | fn main() { 29 | let vec: Vec = vec![1, 8, 6, 2, 5, 4, 8, 3, 7]; 30 | let area = Solution::max_area(vec); 31 | println!("{:?}", area); 32 | } 33 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_26_remove-duplicates-from-sorted-array/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_26_remove-duplicates-from-sorted-array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_26_remove-duplicates-from-sorted-array" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_26_remove-duplicates-from-sorted-array/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn remove_duplicates(nums: &mut Vec) -> i32 { 5 | if nums.len() == 0 { 6 | return 0; 7 | } 8 | 9 | let mut i = 0; 10 | for j in 1..nums.len() { 11 | if nums[i] != nums[j] { 12 | if j - i > 1 { 13 | nums[i + 1] = nums[j]; 14 | } 15 | i += 1; 16 | } 17 | } 18 | 19 | (i + 1) as i32 20 | } 21 | } 22 | 23 | fn main() { 24 | let mut vec: Vec = vec![0,0,1,1,1,2,2,3,3,4]; 25 | let len = Solution::remove_duplicates(&mut vec); 26 | for i in 0..len as usize { 27 | print!("{} ", vec[i]); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bug/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bug/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_283_move-zeroes_bug" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bug/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn move_zeroes(nums: Vec) { 5 | let i = 0; 6 | let j = 0; 7 | while j < nums.len() { 8 | if nums[j] != 0 { 9 | nums[i] = nums[j]; 10 | i += 1; 11 | } 12 | j += 1; 13 | } 14 | 15 | let k = i; 16 | while k < nums.len() { 17 | nums[k] = 0; 18 | k += 1; 19 | } 20 | } 21 | } 22 | 23 | fn main() { 24 | let vec: Vec = vec![0, 1, 0, 3, 12]; 25 | Solution::move_zeroes(vec); 26 | println!("{:?}", vec); 27 | } 28 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bugfix/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bugfix/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_283_move-zeroes_bugfix" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_bugfix/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn move_zeroes(nums: &mut Vec) { 5 | let mut i = 0; 6 | let mut j = 0; 7 | while j < nums.len() { 8 | if nums[j] != 0 { 9 | nums[i] = nums[j]; 10 | i += 1; 11 | } 12 | j += 1; 13 | } 14 | 15 | let mut k = i; 16 | while k < nums.len() { 17 | nums[k] = 0; 18 | k += 1; 19 | } 20 | } 21 | } 22 | 23 | fn main() { 24 | let mut vec: Vec = vec![0, 1, 0, 3, 12]; 25 | Solution::move_zeroes(&mut vec); 26 | println!("{:?}", vec); 27 | } 28 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_upgrade/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_upgrade/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_283_move-zeroes_upgrade" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_283_move-zeroes_upgrade/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn move_zeroes(nums: &mut Vec) { 5 | let mut i = 0; 6 | for j in 0..nums.len() { 7 | if nums[j] != 0 { 8 | nums[i] = nums[j]; 9 | i += 1; 10 | } 11 | } 12 | 13 | for k in i..nums.len() { 14 | nums[k] = 0; 15 | } 16 | } 17 | } 18 | 19 | fn main() { 20 | let mut vec: Vec = vec![0, 1, 0, 3, 12]; 21 | Solution::move_zeroes(&mut vec); 22 | println!("{:?}", vec); 23 | } 24 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_66_plus-one/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_66_plus-one/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_66_plus-one" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/array/leetcode_66_plus-one/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn plus_one(mut digits: Vec) -> Vec { 5 | let mut i = digits.len() - 1; 6 | loop { 7 | if digits[i] < 9 { 8 | digits[i] += 1; 9 | return digits; 10 | } 11 | 12 | digits[i] = 0; 13 | if i > 0 { 14 | i -= 1; 15 | } else if i == 0 { 16 | break; 17 | } 18 | } 19 | 20 | digits = vec![0; digits.len() + 1]; 21 | digits[0] = 1; 22 | return digits; 23 | } 24 | } 25 | 26 | fn main() { 27 | let mut vec: Vec = vec![9, 9, 9]; 28 | vec = Solution::plus_one(vec); 29 | println!("{:?}", vec); 30 | } 31 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_1_two-sum" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 7 | let mut map: HashMap = HashMap::new(); 8 | for i in 0..nums.len() { 9 | map.insert(nums[i], i); 10 | } 11 | 12 | for i in 0..nums.len() { 13 | let complement = target - nums[i]; 14 | if map.contains_key(&complement) && map[&complement] != i { 15 | return vec![i as i32, map[&complement] as i32]; 16 | } 17 | } 18 | 19 | return vec![]; 20 | } 21 | } 22 | 23 | fn main() { 24 | let nums = vec![2, 7, 11, 15]; 25 | let target = 9; 26 | 27 | println!("{:?}", Solution::two_sum(nums, target)); 28 | } 29 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum_upgrade/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum_upgrade/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_1_two-sum_upgrade" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_1_two-sum_upgrade/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 7 | let mut map: HashMap = HashMap::new(); 8 | 9 | for i in 0..nums.len() { 10 | let complement = target - nums[i]; 11 | if map.contains_key(&complement) { 12 | return vec![i as i32, map[&complement] as i32]; 13 | } 14 | 15 | map.insert(nums[i], i); 16 | } 17 | 18 | return vec![]; 19 | } 20 | } 21 | 22 | fn main() { 23 | let nums = vec![2, 7, 11, 15]; 24 | let target = 9; 25 | 26 | println!("{:?}", Solution::two_sum(nums, target)); 27 | } 28 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_242_valid-anagram/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_242_valid-anagram/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_242_valid-anagram" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_242_valid-anagram/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn is_anagram(s: String, t: String) -> bool { 7 | if s.len() != t.len() { 8 | return false; 9 | } 10 | 11 | let mut map = HashMap::new(); 12 | 13 | for c in s.chars() { 14 | let count = map.entry(c).or_insert(0); 15 | *count += 1; 16 | } 17 | 18 | for c in t.chars() { 19 | let count = map.entry(c).or_insert(0); 20 | *count -= 1; 21 | if *count < 0 { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | } 29 | 30 | fn main() { 31 | let s = String::from("anagram"); 32 | let t = String::from("nagaram"); 33 | 34 | println!("{}", Solution::is_anagram(s, t)); 35 | } 36 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_49_group-anagrams" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn group_anagrams(strs: Vec) -> Vec> { 7 | let mut vecs: Vec> = Vec::new(); 8 | let mut used: Vec = vec![false; strs.len()]; 9 | 10 | for i in 0..strs.len() { 11 | let mut temp: Vec = Vec::new(); 12 | if !used[i] { 13 | temp.push(strs[i].clone()); 14 | for j in i + 1..strs.len() { 15 | let mut is_anagram: bool = true; 16 | if strs[i].len() != strs[j].len() { 17 | continue; 18 | } 19 | 20 | let mut map = HashMap::new(); 21 | for c in strs[i].chars() { 22 | let count = map.entry(c).or_insert(0); 23 | *count += 1; 24 | } 25 | for c in strs[j].chars() { 26 | let count = map.entry(c).or_insert(0); 27 | *count -= 1; 28 | if *count < 0 { 29 | is_anagram = false; 30 | break; 31 | } 32 | } 33 | 34 | if is_anagram { 35 | used[j] = true; 36 | temp.push(strs[j].clone()); 37 | } 38 | } 39 | } 40 | 41 | if !temp.is_empty() { 42 | vecs.push(temp); 43 | } 44 | } 45 | 46 | return vecs; 47 | } 48 | } 49 | 50 | fn main() { 51 | let eat = String::from("eat"); 52 | let tea = String::from("tea"); 53 | let tan = String::from("tan"); 54 | let ate = String::from("ate"); 55 | let nat = String::from("nat"); 56 | let bat = String::from("bat"); 57 | let strs: Vec = vec![eat, tea, tan, ate, nat, bat]; 58 | 59 | println!("{:?}", Solution::group_anagrams(strs)); 60 | } 61 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_addition/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_addition/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_49_group-anagrams_addition" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_addition/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn group_anagrams(strs: Vec) -> Vec> { 7 | let mut vecs: Vec> = Vec::new(); 8 | let mut map: HashMap> = HashMap::new(); 9 | 10 | for i in 0..strs.len() { 11 | let mut count = [0; 26]; 12 | for c in strs[i].chars() { 13 | let index = (c as u32 - 'a' as u32) as usize; 14 | count[index] += 1; 15 | } 16 | 17 | let mut chars = vec![]; 18 | for i in 0..count.len() { 19 | chars.push(count[i].to_string() + "#"); 20 | } 21 | 22 | let key: String = chars.into_iter().collect(); 23 | let value = map.get(&key); 24 | if value != None { 25 | let mut v = value.unwrap().to_vec(); 26 | v.push(strs[i].clone()); 27 | map.insert(key, v); 28 | } else { 29 | let v = vec![strs[i].clone()]; 30 | map.insert(key, v); 31 | } 32 | } 33 | 34 | for val in map.values() { 35 | // vecs.push((*val).clone()); 36 | vecs.push(val.to_vec()); 37 | } 38 | 39 | return vecs; 40 | } 41 | } 42 | 43 | fn main() { 44 | let eat = String::from("eat"); 45 | let tea = String::from("tea"); 46 | let tan = String::from("tan"); 47 | let ate = String::from("ate"); 48 | let nat = String::from("nat"); 49 | let bat = String::from("bat"); 50 | let strs: Vec = vec![eat, tea, tan, ate, nat, bat]; 51 | 52 | println!("{:?}", Solution::group_anagrams(strs)); 53 | } 54 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_upgrade/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_upgrade/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_49_group-anagrams_upgrade" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/hashtable/leetcode_49_group-anagrams_upgrade/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn group_anagrams(strs: Vec) -> Vec> { 7 | let mut vecs: Vec> = Vec::new(); 8 | let mut map: HashMap> = HashMap::new(); 9 | 10 | for i in 0..strs.len() { 11 | let mut chars = vec![]; 12 | for c in strs[i].chars() { 13 | chars.push(c); 14 | } 15 | chars.sort(); 16 | 17 | let key: String = chars.into_iter().collect(); 18 | let value = map.get(&key); 19 | if value != None { 20 | let mut v = value.unwrap().to_vec(); 21 | v.push(strs[i].clone()); 22 | map.insert(key, v); 23 | } else { 24 | let v = vec![strs[i].clone()]; 25 | map.insert(key, v); 26 | } 27 | } 28 | 29 | for val in map.values() { 30 | vecs.push((*val).clone()); 31 | } 32 | 33 | return vecs; 34 | } 35 | } 36 | 37 | fn main() { 38 | let eat = String::from("eat"); 39 | let tea = String::from("tea"); 40 | let tan = String::from("tan"); 41 | let ate = String::from("ate"); 42 | let nat = String::from("nat"); 43 | let bat = String::from("bat"); 44 | let strs: Vec = vec![eat, tea, tan, ate, nat, bat]; 45 | 46 | println!("{:?}", Solution::group_anagrams(strs)); 47 | } 48 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_19_remove-nth-node-from-end-of-list/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_19_remove-nth-node-from-end-of-list" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_19_remove-nth-node-from-end-of-list/src/linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { 11 | next: None, 12 | val, 13 | } 14 | } 15 | } 16 | 17 | pub fn to_list(vec: Vec) -> Option> { 18 | let mut current = None; 19 | for &v in vec.iter().rev() { 20 | let mut node = ListNode::new(v); 21 | node.next = current; 22 | current = Some(Box::new(node)); 23 | } 24 | 25 | current 26 | } 27 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_19_remove-nth-node-from-end-of-list/src/main.rs: -------------------------------------------------------------------------------- 1 | mod linked_list; 2 | 3 | use crate::linked_list::{ListNode, to_list}; 4 | 5 | struct Solution; 6 | 7 | impl Solution { 8 | pub fn remove_nth_from_end_1(head: Option>, n: i32) -> Option> { 9 | let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); 10 | let mut cur = &mut dummy; 11 | let mut length = 0; 12 | 13 | while let Some(node) = cur.as_mut() { 14 | cur = &mut node.next; 15 | if let Some(_node) = cur { length += 1; } 16 | } 17 | 18 | let mut new_cur = dummy.as_mut(); 19 | let idx = length - n; 20 | 21 | for _ in 0..idx { 22 | new_cur = new_cur.unwrap().next.as_mut(); 23 | } 24 | 25 | let next = new_cur.as_mut().unwrap().next.as_mut().unwrap().next.take(); 26 | new_cur.as_mut().unwrap().next = next; 27 | 28 | dummy.unwrap().next 29 | } 30 | 31 | pub fn remove_nth_from_end_2(head: Option>, n: i32) -> Option> { 32 | let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); 33 | let mut slow_p = &mut dummy; 34 | let mut fast_p = &mut slow_p.clone(); 35 | 36 | for _ in 1..=n + 1 { 37 | fast_p = &mut fast_p.as_mut().unwrap().next; 38 | } 39 | 40 | while fast_p.is_some() { 41 | fast_p = &mut fast_p.as_mut().unwrap().next; 42 | slow_p = &mut slow_p.as_mut().unwrap().next; 43 | } 44 | 45 | let next = &slow_p.as_mut().unwrap().next.as_mut().unwrap().next; 46 | slow_p.as_mut().unwrap().next = next.clone(); 47 | 48 | dummy.unwrap().next 49 | } 50 | } 51 | 52 | fn main() { 53 | println!("{:?}", Solution::remove_nth_from_end_1(to_list(vec![1, 2, 3, 4, 5]), 2)); 54 | } 55 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_206_reverse-linked-list/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_206_reverse-linked-list" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_206_reverse-linked-list/src/linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { 11 | next: None, 12 | val, 13 | } 14 | } 15 | } 16 | 17 | pub fn to_list(vec: Vec) -> Option> { 18 | let mut current = None; 19 | for &v in vec.iter().rev() { 20 | let mut node = ListNode::new(v); 21 | node.next = current; 22 | current = Some(Box::new(node)); 23 | } 24 | 25 | current 26 | } 27 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_206_reverse-linked-list/src/main.rs: -------------------------------------------------------------------------------- 1 | mod linked_list; 2 | 3 | use crate::linked_list::{ListNode, to_list}; 4 | 5 | struct Solution; 6 | 7 | impl Solution { 8 | pub fn reverse_list(head: Option>) -> Option> { 9 | let mut prev = None; 10 | let mut curr = head; 11 | 12 | while let Some(mut curr_node) = curr.take() { 13 | let next_temp = curr_node.next.take(); 14 | curr_node.next = prev.take(); 15 | prev = Some(curr_node); 16 | curr = next_temp; 17 | } 18 | 19 | prev 20 | } 21 | } 22 | 23 | fn main() { 24 | println!("{:?}", Solution::reverse_list(to_list(vec![1, 2, 3, 4, 5]))); 25 | } 26 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_21_merge-two-sorted-lists/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_21_merge-two-sorted-lists" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_21_merge-two-sorted-lists/src/linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { 11 | next: None, 12 | val, 13 | } 14 | } 15 | } 16 | 17 | pub fn to_list(vec: Vec) -> Option> { 18 | let mut current = None; 19 | for &v in vec.iter().rev() { 20 | let mut node = ListNode::new(v); 21 | node.next = current; 22 | current = Some(Box::new(node)); 23 | } 24 | 25 | current 26 | } 27 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_21_merge-two-sorted-lists/src/main.rs: -------------------------------------------------------------------------------- 1 | mod linked_list; 2 | 3 | use crate::linked_list::{ListNode, to_list}; 4 | 5 | struct Solution; 6 | 7 | impl Solution { 8 | pub fn merge_two_lists(l1: Option>, l2: Option>) -> Option> { 9 | match (l1, l2) { 10 | (Some(node1), None) => Some(node1), 11 | (None, Some(node2)) => Some(node2), 12 | (Some(mut node1), Some(mut node2)) => { 13 | if node1.val < node2.val { 14 | let n = node1.next.take(); 15 | node1.next = Solution::merge_two_lists(n, Some(node2)); 16 | Some(node1) 17 | } else { 18 | let n = node2.next.take(); 19 | node2.next = Solution::merge_two_lists(Some(node1), n); 20 | Some(node2) 21 | } 22 | } 23 | _ => None, 24 | } 25 | } 26 | } 27 | 28 | fn main() { 29 | println!("{:?}", Solution::merge_two_lists(to_list(vec![1, 2, 4]), to_list(vec![1, 3, 4]))); 30 | } 31 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_876_middle-of-the-linked-list/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_876_middle-of-the-linked-list" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_876_middle-of-the-linked-list/src/linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { 11 | next: None, 12 | val, 13 | } 14 | } 15 | } 16 | 17 | pub fn to_list(vec: Vec) -> Option> { 18 | let mut current = None; 19 | for &v in vec.iter().rev() { 20 | let mut node = ListNode::new(v); 21 | node.next = current; 22 | current = Some(Box::new(node)); 23 | } 24 | 25 | current 26 | } 27 | -------------------------------------------------------------------------------- /data-structure/linked_list/leetcode_876_middle-of-the-linked-list/src/main.rs: -------------------------------------------------------------------------------- 1 | mod linked_list; 2 | 3 | use crate::linked_list::{ListNode, to_list}; 4 | 5 | struct Solution; 6 | 7 | impl Solution { 8 | pub fn middle_node(head: Option>) -> Option> { 9 | let mut fast_p = &head; 10 | let mut slow_p = &head; 11 | 12 | while fast_p.is_some() && fast_p.as_ref().unwrap().next.is_some() { 13 | slow_p = &slow_p.as_ref().unwrap().next; 14 | fast_p = &fast_p.as_ref().unwrap().next.as_ref().unwrap().next; 15 | } 16 | 17 | slow_p.clone() 18 | } 19 | } 20 | 21 | fn main() { 22 | println!("{:?}", Solution::middle_node(to_list(vec![1, 2, 3, 4, 5, 6]))); 23 | } 24 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_155_min-stack/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_155_min-stack" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_155_min-stack/src/main.rs: -------------------------------------------------------------------------------- 1 | struct MinStack { 2 | stack: Vec, 3 | min_stack: Vec, 4 | } 5 | 6 | impl MinStack { 7 | fn new() -> Self { 8 | MinStack { 9 | stack: Vec::new(), 10 | min_stack: Vec::new(), 11 | } 12 | } 13 | 14 | fn push(&mut self, x: i32) { 15 | self.stack.push(x); 16 | if self.min_stack.is_empty() || x <= *self.min_stack.last().unwrap() { 17 | self.min_stack.push(x); 18 | } 19 | } 20 | 21 | fn pop(&mut self) { 22 | if self.stack.is_empty() { return; } 23 | if self.stack.pop().unwrap() == *self.min_stack.last().unwrap() { 24 | self.min_stack.pop(); 25 | } 26 | } 27 | 28 | fn top(&self) -> i32 { 29 | return *self.stack.last().unwrap(); 30 | } 31 | 32 | fn get_min(&self) -> i32 { 33 | return *self.min_stack.last().unwrap(); 34 | } 35 | } 36 | 37 | fn main() { 38 | let mut stack = MinStack::new(); 39 | stack.push(-2); 40 | stack.push(0); 41 | stack.push(-3); 42 | println!("{}", stack.get_min()); 43 | stack.pop(); 44 | println!("{}", stack.top()); 45 | println!("{}", stack.get_min()); 46 | } 47 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_20_valid-parentheses/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_20_valid-parentheses" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_20_valid-parentheses/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn is_valid(s: String) -> bool { 5 | let chars: Vec = s.chars().collect(); 6 | if chars.len() == 0 { 7 | return true; 8 | } 9 | 10 | let mut stack: Vec = Vec::new(); 11 | for i in 0..chars.len() { 12 | if chars[i] == '(' { 13 | stack.push(')'); 14 | } else if chars[i] == '[' { 15 | stack.push(']'); 16 | } else if chars[i] == '{' { 17 | stack.push('}'); 18 | } else if stack.is_empty() || chars[i] != stack.pop().unwrap() { 19 | return false; 20 | } 21 | } 22 | 23 | return stack.is_empty(); 24 | } 25 | } 26 | 27 | fn main() { 28 | let parenthes = String::from("{[]}"); 29 | println!("{}", Solution::is_valid(parenthes)); 30 | } 31 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_239_sliding-window-maximum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_239_sliding-window-maximum" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/stack-queue/leetcode_239_sliding-window-maximum/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::VecDeque; 2 | 3 | struct Solution; 4 | 5 | impl Solution { 6 | pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { 7 | if nums.len() == 0 || k == 1 { 8 | return nums; 9 | } 10 | 11 | let mut res: Vec = Vec::new(); 12 | let mut deque: VecDeque = VecDeque::new(); 13 | for i in 0..nums.len() { 14 | push(&mut deque, nums[i]); 15 | 16 | if (i as i32) > k - 1 { 17 | pop(&mut deque, nums[i - k as usize]); 18 | res.push(max(&deque)); 19 | } else if (i as i32) == k - 1 { 20 | res.push(max(&deque)); 21 | } 22 | } 23 | 24 | return res; 25 | } 26 | } 27 | 28 | fn push(deque: &mut VecDeque, n: i32) { 29 | while !deque.is_empty() && *deque.back().unwrap() < n { 30 | deque.pop_back(); 31 | } 32 | deque.push_back(n); 33 | } 34 | 35 | fn pop(deque: &mut VecDeque, n: i32) { 36 | if !deque.is_empty() && *deque.front().unwrap() == n { 37 | deque.pop_front(); 38 | } 39 | } 40 | 41 | fn max(deque: &VecDeque) -> i32 { 42 | return *deque.front().unwrap(); 43 | } 44 | 45 | fn main() { 46 | let nums = vec![1, 3, -1, -3, 5, 3, 6, 7]; 47 | println!("{:?}", Solution::max_sliding_window(nums, 3)); 48 | } 49 | -------------------------------------------------------------------------------- /data-structure/tree/binary_tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "binary_tree" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/binary_tree/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | 44 | fn main() { 45 | let vec = vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]; 46 | println!("{:?}", to_tree(vec)); 47 | } 48 | -------------------------------------------------------------------------------- /data-structure/tree/heap/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "heap" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/heap/src/main.rs: -------------------------------------------------------------------------------- 1 | pub fn build_heap_down_up(nums: &mut Vec) { 2 | for i in 1..nums.len() { 3 | heapify_down_up(nums, i); 4 | } 5 | } 6 | 7 | fn heapify_down_up(nums: &mut Vec, idx: usize) { 8 | let mut idx = idx; 9 | let mut parent_idx = (idx - 1) / 2; 10 | while nums[idx] > nums[parent_idx] { 11 | nums.swap(idx, parent_idx); 12 | idx = parent_idx; 13 | if idx == 0 { break; } 14 | parent_idx = (idx - 1) / 2; 15 | } 16 | } 17 | 18 | pub fn build_heap_up_down(nums: &mut Vec) { 19 | let len = nums.len(); 20 | for i in (0..len / 2).rev() { 21 | heapify_up_down(nums, i, len); 22 | } 23 | } 24 | 25 | fn heapify_up_down(nums: &mut Vec, idx: usize, len: usize) { 26 | let mut idx = idx; 27 | loop { 28 | let mut max_pos = idx; 29 | if 2 * idx + 1 < len && nums[idx] < nums[2 * idx + 1] { max_pos = 2 * idx + 1; } 30 | if 2 * idx + 2 < len && nums[max_pos] < nums[2 * idx + 2] { max_pos = 2 * idx + 2; } 31 | 32 | if max_pos == idx { break; } 33 | nums.swap(idx, max_pos); 34 | idx = max_pos; 35 | } 36 | } 37 | 38 | pub fn insert(nums: &mut Vec, x: i32) { 39 | nums.push(x); 40 | 41 | heapify_down_up(nums, nums.len() - 1); 42 | } 43 | 44 | pub fn remove_max(nums: &mut Vec) -> Option { 45 | if nums.len() == 0 { return None; } 46 | 47 | let max_value = nums[0]; 48 | nums[0] = nums[nums.len() - 1]; 49 | nums.remove(nums.len() - 1); 50 | 51 | if nums.len() > 1 { 52 | heapify_up_down(nums, 0, nums.len()); 53 | } 54 | 55 | Some(max_value) 56 | } 57 | 58 | fn main() { 59 | let mut nums1 = vec![1, 4, 5, 7, 8, 13, 16, 19, 20]; 60 | build_heap_down_up(&mut nums1); 61 | println!("{:?}", nums1); 62 | insert(&mut nums1, 21); 63 | println!("{:?}", nums1); 64 | 65 | let mut nums2 = vec![1, 4, 5, 7, 8, 13, 16, 19, 20]; 66 | build_heap_up_down(&mut nums2); 67 | println!("{:?}", nums2); 68 | remove_max(&mut nums2); 69 | println!("{:?}", nums2); 70 | } 71 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_102_binary-tree-level-order-traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_102_binary-tree-level-order-traversal" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_102_binary-tree-level-order-traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | use std::collections::VecDeque; 8 | 9 | struct Solution; 10 | 11 | impl Solution { 12 | pub fn level_order(root: Option>>) -> Vec> { 13 | let mut levels: Vec> = vec![]; 14 | if root.is_none() { return levels; } 15 | 16 | let mut deque: VecDeque>>> = VecDeque::new(); 17 | deque.push_back(root); 18 | 19 | while !deque.is_empty() { 20 | let mut current_level = vec![]; 21 | 22 | let level_length = deque.len(); 23 | for _ in 0..level_length { 24 | let n = deque.pop_front(); 25 | if let Some(Some(node)) = n { 26 | current_level.push(node.borrow().val); 27 | 28 | if node.borrow().left.is_some() { deque.push_back(node.borrow().left.clone()); } 29 | if node.borrow().right.is_some() { deque.push_back(node.borrow().right.clone()); } 30 | } 31 | } 32 | 33 | levels.push(current_level); 34 | } 35 | 36 | levels 37 | } 38 | } 39 | 40 | fn main() { 41 | let vec = vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]; 42 | println!("{:?}", Solution::level_order(to_tree(vec))); 43 | } 44 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_102_binary-tree-level-order-traversal/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_144_binary-tree-preorder-traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_144_binary-tree-preorder-traversal" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_144_binary-tree-preorder-traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | mod preorder_func; 2 | 3 | use crate::preorder_func::{traversal_by_recursive, traversal_by_stack}; 4 | use crate::preorder_func::tree::{TreeNode, to_tree}; 5 | 6 | use std::rc::Rc; 7 | use std::cell::RefCell; 8 | 9 | struct Solution; 10 | 11 | impl Solution { 12 | pub fn preorder_traversal(root: Option>>) -> Vec { 13 | return traversal_by_stack(root); 14 | } 15 | } 16 | 17 | fn main() { 18 | let vec = vec![Some(1), None, Some(2), Some(3)]; 19 | println!("{:?}", Solution::preorder_traversal(to_tree(vec))); 20 | } 21 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_144_binary-tree-preorder-traversal/src/preorder_func.rs: -------------------------------------------------------------------------------- 1 | pub mod tree; 2 | 3 | use tree::TreeNode; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | pub fn traversal_by_recursive(root: Option>>) -> Vec { 9 | let mut result: Vec = vec![]; 10 | if root.is_none() { return result; } 11 | 12 | preorder_recursive(root, &mut result); 13 | result 14 | } 15 | 16 | fn preorder_recursive(root: Option>>, result: &mut Vec) { 17 | match root { 18 | Some(node) => { 19 | result.push(node.borrow().val); 20 | preorder_recursive(node.borrow().left.clone(), result); 21 | preorder_recursive(node.borrow().right.clone(), result); 22 | } 23 | None => { return; } 24 | } 25 | } 26 | 27 | pub fn traversal_by_stack(root: Option>>) -> Vec { 28 | let mut result = vec![]; 29 | if root.is_none() { return result; } 30 | 31 | let mut stack: Vec>> = Vec::new(); 32 | let mut r = root.clone(); 33 | 34 | while r.is_some() || !stack.is_empty() { 35 | while let Some(node) = r { 36 | result.push(node.borrow().val); 37 | stack.push(node.clone()); 38 | r = node.borrow().left.clone(); 39 | } 40 | r = stack.pop(); 41 | if let Some(node) = r { 42 | r = node.borrow().right.clone(); 43 | } 44 | } 45 | result 46 | } -------------------------------------------------------------------------------- /data-structure/tree/leetcode_144_binary-tree-preorder-traversal/src/preorder_func/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_145_binary-tree-postorder-traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_145_binary-tree-postorder-traversal" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_145_binary-tree-postorder-traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | mod postorder_func; 2 | 3 | use crate::postorder_func::{traversal_by_recursive, traversal_by_stack}; 4 | use crate::postorder_func::tree::{TreeNode, to_tree}; 5 | 6 | use std::rc::Rc; 7 | use std::cell::RefCell; 8 | 9 | struct Solution; 10 | 11 | impl Solution { 12 | pub fn postorder_traversal(root: Option>>) -> Vec { 13 | return traversal_by_recursive(root); 14 | } 15 | } 16 | 17 | fn main() { 18 | let vec = vec![Some(1), None, Some(2), Some(3)]; 19 | println!("{:?}", Solution::postorder_traversal(to_tree(vec))); 20 | } 21 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_145_binary-tree-postorder-traversal/src/postorder_func.rs: -------------------------------------------------------------------------------- 1 | pub mod tree; 2 | 3 | use tree::TreeNode; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | pub fn traversal_by_recursive(root: Option>>) -> Vec { 9 | let mut result: Vec = vec![]; 10 | if root.is_none() { return result; } 11 | 12 | postorder_recursive(root, &mut result); 13 | result 14 | } 15 | 16 | fn postorder_recursive(root: Option>>, result: &mut Vec) { 17 | match root { 18 | Some(node) => { 19 | postorder_recursive(node.borrow().left.clone(), result); 20 | postorder_recursive(node.borrow().right.clone(), result); 21 | result.push(node.borrow().val); 22 | }, 23 | None => { return; } 24 | } 25 | } 26 | 27 | pub fn traversal_by_stack(root: Option>>) -> Vec { 28 | let mut result = vec![]; 29 | if root.is_none() { return result; } 30 | 31 | let mut stack1: Vec>>> = Vec::new(); 32 | let mut stack2: Vec>>> = Vec::new(); 33 | stack1.push(root); 34 | 35 | while let Some(Some(node)) = stack1.pop() { 36 | if node.borrow().left.is_some() { 37 | stack1.push(node.borrow().left.clone()); 38 | } 39 | if node.borrow().right.is_some() { 40 | stack1.push(node.borrow().right.clone()); 41 | } 42 | stack2.push(Some(node)); 43 | } 44 | 45 | while let Some(Some(node)) = stack2.pop() { 46 | result.push(node.borrow().val); 47 | } 48 | 49 | result 50 | } -------------------------------------------------------------------------------- /data-structure/tree/leetcode_145_binary-tree-postorder-traversal/src/postorder_func/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_701_insert-into-a-binary-search-tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_701_insert-into-a-binary-search-tree" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_701_insert-into-a-binary-search-tree/src/main.rs: -------------------------------------------------------------------------------- 1 | mod tree; 2 | 3 | use crate::tree::{TreeNode, to_tree}; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | struct Solution; 9 | 10 | impl Solution { 11 | pub fn insert_into_bst(root: Option>>, val: i32) -> Option>> { 12 | if root.is_none() { return Some(Rc::new(RefCell::new(TreeNode::new(val)))); } 13 | insert(&root, val); 14 | root 15 | } 16 | } 17 | 18 | fn insert(root: &Option>>, val: i32) { 19 | if let Some(node) = root { 20 | let mut n = node.borrow_mut(); 21 | let target = if val > n.val { &mut n.right } else { &mut n.left }; 22 | 23 | if target.is_some() { 24 | return insert(target, val); 25 | } 26 | 27 | *target = Some(Rc::new(RefCell::new(TreeNode::new(val)))); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_701_insert-into-a-binary-search-tree/src/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_94_binary-tree-inorder-traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode_94_binary-tree-inorder-traversal" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_94_binary-tree-inorder-traversal/src/inorder_func.rs: -------------------------------------------------------------------------------- 1 | pub mod tree; 2 | 3 | use tree::TreeNode; 4 | 5 | use std::rc::Rc; 6 | use std::cell::RefCell; 7 | 8 | pub fn traversal_by_recursive(root: Option>>) -> Vec { 9 | let mut result: Vec = vec![]; 10 | if root.is_none() { return result; } 11 | 12 | inorder_recursive(root, &mut result); 13 | result 14 | } 15 | 16 | fn inorder_recursive(root: Option>>, result: &mut Vec) { 17 | match root { 18 | Some(node) => { 19 | inorder_recursive(node.borrow().left.clone(), result); 20 | result.push(node.borrow().val); 21 | inorder_recursive(node.borrow().right.clone(), result); 22 | } 23 | None => { return; } 24 | } 25 | } 26 | 27 | pub fn traversal_by_stack(root: Option>>) -> Vec { 28 | let mut result = vec![]; 29 | if root.is_none() { return result; } 30 | 31 | let mut stack: Vec>> = Vec::new(); 32 | let mut r = root.clone(); 33 | 34 | while r.is_some() || !stack.is_empty() { 35 | while let Some(node) = r { 36 | stack.push(node.clone()); 37 | r = node.borrow().left.clone(); 38 | } 39 | r = stack.pop(); 40 | if let Some(node) = r { 41 | result.push(node.borrow().val); 42 | r = node.borrow().right.clone(); 43 | } 44 | } 45 | result 46 | } -------------------------------------------------------------------------------- /data-structure/tree/leetcode_94_binary-tree-inorder-traversal/src/inorder_func/tree.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::collections::VecDeque; 4 | 5 | #[derive(Debug, PartialEq, Eq)] 6 | pub struct TreeNode { 7 | pub val: i32, 8 | pub left: Option>>, 9 | pub right: Option>>, 10 | } 11 | 12 | impl TreeNode { 13 | #[inline] 14 | pub fn new(val: i32) -> Self { 15 | TreeNode { 16 | val, 17 | left: None, 18 | right: None, 19 | } 20 | } 21 | } 22 | 23 | pub fn to_tree(vec: Vec>) -> Option>> { 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | -------------------------------------------------------------------------------- /data-structure/tree/leetcode_94_binary-tree-inorder-traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | mod inorder_func; 2 | 3 | use crate::inorder_func::{traversal_by_recursive, traversal_by_stack}; 4 | use crate::inorder_func::tree::{TreeNode, to_tree}; 5 | 6 | use std::rc::Rc; 7 | use std::cell::RefCell; 8 | 9 | struct Solution; 10 | 11 | impl Solution { 12 | pub fn inorder_traversal(root: Option>>) -> Vec { 13 | return traversal_by_stack(root); 14 | } 15 | } 16 | 17 | fn main() { 18 | let vec = vec![Some(1), None, Some(2), Some(3)]; 19 | println!("{:?}", Solution::inorder_traversal(to_tree(vec))); 20 | } 21 | -------------------------------------------------------------------------------- /project/async_run/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async_run" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | sort_middleware_lib = { path = "../sort_middleware_lib" } 11 | random_data_lib = { path = "../random_data_lib" } 12 | async-std = "1.6.3" 13 | time = "0.1" 14 | -------------------------------------------------------------------------------- /project/async_run/src/main.rs: -------------------------------------------------------------------------------- 1 | use async_std::task; 2 | use sort_middleware_lib::async_lib; 3 | 4 | fn main() { 5 | let n = 20000; 6 | let start = time::get_time(); 7 | 8 | let arr1 = random_data_lib::generate_random_array(n, 0, n); 9 | let arr2 = arr1.clone(); 10 | let arr3 = arr1.clone(); 11 | let arr4 = arr1.clone(); 12 | let arr5 = arr1.clone(); 13 | let arr6 = arr1.clone(); 14 | 15 | let arr11 = random_data_lib::generate_nearly_ordered_array(n, 100); 16 | let arr12 = arr11.clone(); 17 | let arr13 = arr11.clone(); 18 | let arr14 = arr11.clone(); 19 | let arr15 = arr11.clone(); 20 | let arr16 = arr11.clone(); 21 | 22 | let bubble_random_sort_task = task::spawn(async { 23 | async_lib::bubble_sort(arr1, "bubble_random_sort").await; 24 | }); 25 | let selection_random_sort_task = task::spawn(async { 26 | async_lib::selection_sort(arr2, "selection_random_sort").await; 27 | }); 28 | let insertion_random_sort_task = task::spawn(async { 29 | async_lib::insertion_sort(arr3, "insertion_random_sort").await; 30 | }); 31 | let heap_random_sort_task = task::spawn(async { 32 | async_lib::heap_sort(arr4, "heap_random_sort").await; 33 | }); 34 | let merge_random_sort_task = task::spawn(async { 35 | async_lib::merge_sort(arr5, "merge_random_sort").await; 36 | }); 37 | let quick_random_sort_task = task::spawn(async { 38 | async_lib::quick_sort(arr6, "quick_random_sort").await; 39 | }); 40 | 41 | let bubble_nearly_ordered_sort_task = task::spawn(async { 42 | async_lib::bubble_sort(arr11, "bubble_nearly_ordered_sort").await; 43 | }); 44 | let selection_nearly_ordered_sort_task = task::spawn(async { 45 | async_lib::selection_sort(arr12, "selection_nearly_ordered_sort").await; 46 | }); 47 | let insertion_nearly_ordered_sort_task = task::spawn(async { 48 | async_lib::insertion_sort(arr13, "insertion_nearly_ordered_sort").await; 49 | }); 50 | let heap_nearly_ordered_sort_task = task::spawn(async { 51 | async_lib::heap_sort(arr14, "heap_nearly_ordered_sort").await; 52 | }); 53 | let merge_nearly_ordered_sort_task = task::spawn(async { 54 | async_lib::merge_sort(arr15, "merge_nearly_ordered_sort").await; 55 | }); 56 | let quick_nearly_ordered_sort_task = task::spawn(async { 57 | async_lib::quick_sort(arr16, "quick_nearly_ordered_sort").await; 58 | }); 59 | 60 | task::block_on(bubble_random_sort_task); 61 | task::block_on(selection_random_sort_task); 62 | task::block_on(insertion_random_sort_task); 63 | task::block_on(heap_random_sort_task); 64 | task::block_on(merge_random_sort_task); 65 | task::block_on(quick_random_sort_task); 66 | 67 | task::block_on(bubble_nearly_ordered_sort_task); 68 | task::block_on(selection_nearly_ordered_sort_task); 69 | task::block_on(insertion_nearly_ordered_sort_task); 70 | task::block_on(heap_nearly_ordered_sort_task); 71 | task::block_on(merge_nearly_ordered_sort_task); 72 | task::block_on(quick_nearly_ordered_sort_task); 73 | 74 | let end = time::get_time(); 75 | println!("duration: {:?}", (end - start).num_milliseconds()); 76 | } 77 | -------------------------------------------------------------------------------- /project/generic/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "generic" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | sort_lib = { path = "../sort_lib" } 11 | -------------------------------------------------------------------------------- /project/generic/src/data_source.rs: -------------------------------------------------------------------------------- 1 | mod student; 2 | 3 | use student::Student; 4 | 5 | pub fn integer() -> Vec { 6 | return vec![1, 3, 6, 7, 8, 5, 4, 2, 10, 9]; 7 | } 8 | 9 | pub fn floating_point() -> Vec { 10 | return vec![2.2, 1.1, 6.6, 5.5, 4.4, 3.3]; 11 | } 12 | 13 | pub fn str() -> Vec<&'static str> { 14 | return vec!["B", "C", "D", "A", "G", "F", "E"]; 15 | } 16 | 17 | pub fn student() -> Vec { 18 | return vec![Student::new("D", 90), 19 | Student::new("C", 100), 20 | Student::new("B", 95), 21 | Student::new("A", 95)]; 22 | } 23 | -------------------------------------------------------------------------------- /project/generic/src/data_source/student.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::Ordering; 2 | 3 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 4 | pub struct Student { 5 | name: &'static str, 6 | score: i32, 7 | } 8 | 9 | impl Student { 10 | pub fn new(name: &'static str, score: i32) -> Self { 11 | Student { name, score } 12 | } 13 | 14 | pub fn name(&self) -> &str { 15 | self.name 16 | } 17 | 18 | pub fn score(&self) -> i32 { 19 | self.score 20 | } 21 | } 22 | 23 | impl PartialOrd for Student { 24 | fn partial_cmp(&self, other: &Student) -> Option { 25 | return if self.score == other.score { 26 | Some(self.name().cmp(&other.name())) 27 | } else { 28 | Some(self.score().cmp(&other.score())) 29 | }; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /project/generic/src/main.rs: -------------------------------------------------------------------------------- 1 | mod data_source; 2 | 3 | use sort_lib::sync_lib; 4 | 5 | fn main() { 6 | let arr1 = &mut data_source::integer(); 7 | sync_lib::insertion_sort(arr1); 8 | println!("{:?}", arr1); 9 | 10 | let arr2 = &mut data_source::floating_point(); 11 | sync_lib::insertion_sort(arr2); 12 | println!("{:?}", arr2); 13 | 14 | let arr3 = &mut data_source::str(); 15 | sync_lib::insertion_sort(arr3); 16 | println!("{:?}", arr3); 17 | 18 | let arr4 = &mut data_source::student(); 19 | sync_lib::insertion_sort(arr4); 20 | println!("{:#?}", arr4); 21 | } 22 | -------------------------------------------------------------------------------- /project/random_data_lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "random_data_lib" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | rand = "0.7.3" 11 | -------------------------------------------------------------------------------- /project/random_data_lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | use rand::Rng; 2 | 3 | pub fn generate_random_array(n: i32, range_left: i32, range_right: i32) -> Vec { 4 | let arr = vec![0; n as usize]; 5 | if range_left > range_right { 6 | return arr; 7 | } 8 | 9 | let mut rng = rand::thread_rng(); 10 | return arr.iter().map(|_| rng.gen_range(range_left, range_right)).collect(); 11 | } 12 | 13 | pub fn generate_nearly_ordered_array(n: i32, swap_times: i32) -> Vec { 14 | let mut arr = vec![0; n as usize]; 15 | for i in 0..n { 16 | arr[i as usize] = i; 17 | } 18 | 19 | let mut rng = rand::thread_rng(); 20 | for _ in 0..swap_times { 21 | let posx = rng.gen_range(0, n); 22 | let posy = rng.gen_range(0, n); 23 | arr.swap(posx as usize, posy as usize); 24 | } 25 | 26 | return arr; 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::*; 32 | 33 | #[test] 34 | fn random_array_test() { 35 | let n = 20; 36 | let arr = generate_random_array(n, 0, n); 37 | assert_eq!(arr.len(), n as usize); 38 | } 39 | 40 | #[test] 41 | fn nearly_ordered_array_test() { 42 | let n = 20; 43 | let arr = generate_nearly_ordered_array(n, 1); 44 | assert_eq!(arr.len(), n as usize); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /project/random_data_lib/src/main.rs: -------------------------------------------------------------------------------- 1 | use random_data_lib; 2 | 3 | fn main() { 4 | let n = 20; 5 | let arr1 = random_data_lib::generate_random_array(n, 0, n); 6 | let arr2 = random_data_lib::generate_nearly_ordered_array(n, 1); 7 | 8 | println!("{:?}", arr1); 9 | println!("{:?}", arr2); 10 | } -------------------------------------------------------------------------------- /project/sort_lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sort_lib" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | async-std = "1.6.3" 11 | -------------------------------------------------------------------------------- /project/sort_lib/src/async_lib.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | pub async fn bubble_sort(arr: &mut Vec) { 4 | if arr.is_empty() { return; } 5 | 6 | for i in 0..arr.len() - 1 { 7 | let mut flag = false; 8 | for j in 0..arr.len() - i - 1 { 9 | if arr[j] > arr[j + 1] { 10 | let tmp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = tmp; 13 | 14 | flag = true; 15 | } 16 | } 17 | 18 | if !flag { break; } 19 | } 20 | } 21 | 22 | pub async fn selection_sort(arr: &mut Vec) { 23 | if arr.is_empty() { return; } 24 | 25 | for i in 0..arr.len() - 1 { 26 | let mut min_index = i; 27 | for j in i + 1..arr.len() { 28 | if arr[j] < arr[min_index] { 29 | min_index = j; 30 | } 31 | } 32 | 33 | if i != min_index { 34 | arr.swap(i, min_index); 35 | } 36 | } 37 | } 38 | 39 | pub async fn insertion_sort(arr: &mut Vec) { 40 | if arr.is_empty() { return; } 41 | 42 | for i in 1..arr.len() { 43 | let current = arr[i]; 44 | 45 | let mut j = (i - 1) as i32; 46 | while j >= 0 { 47 | if arr[j as usize] > current { 48 | arr[(j + 1) as usize] = arr[j as usize]; 49 | } else { 50 | break; 51 | } 52 | j -= 1; 53 | } 54 | 55 | arr[(j + 1) as usize] = current; 56 | } 57 | } 58 | 59 | pub async fn heap_sort(arr: &mut Vec) { 60 | build_heap(arr); 61 | 62 | for i in (0..arr.len()).rev() { 63 | arr.swap(0, i); 64 | heapify(arr, 0, i); 65 | } 66 | } 67 | 68 | fn build_heap(arr: &mut Vec) { 69 | let len = arr.len(); 70 | for i in (0..len / 2).rev() { 71 | heapify(arr, i, len); 72 | } 73 | } 74 | 75 | fn heapify(arr: &mut Vec, idx: usize, len: usize) { 76 | let mut idx = idx; 77 | loop { 78 | let mut max_pos = idx; 79 | if 2 * idx + 1 < len && arr[idx] < arr[2 * idx + 1] { max_pos = 2 * idx + 1; } 80 | if 2 * idx + 2 < len && arr[max_pos] < arr[2 * idx + 2] { max_pos = 2 * idx + 2; } 81 | 82 | if max_pos == idx { break; } 83 | arr.swap(idx, max_pos); 84 | idx = max_pos; 85 | } 86 | } 87 | 88 | pub async fn merge_sort(arr: &mut Vec) { 89 | if arr.is_empty() { return; } 90 | 91 | let n = arr.len() - 1; 92 | merge_sort_recursion(arr, 0, n); 93 | } 94 | 95 | fn merge_sort_recursion(arr: &mut Vec, left: usize, right: usize) { 96 | if left >= right { return; } 97 | let middle = left + (right - left) / 2; 98 | 99 | merge_sort_recursion(arr, left, middle); 100 | merge_sort_recursion(arr, middle + 1, right); 101 | 102 | merge(arr, left, middle, right); 103 | } 104 | 105 | fn merge(arr: &mut Vec, left: usize, middle: usize, right: usize) { 106 | let mut i = left; 107 | let mut j = middle + 1; 108 | let mut k = left; 109 | let mut tmp = vec![]; 110 | 111 | while k <= right { 112 | if i > middle { 113 | tmp.push(arr[j]); 114 | j += 1; 115 | k += 1; 116 | } else if j > right { 117 | tmp.push(arr[i]); 118 | i += 1; 119 | k += 1; 120 | } else if arr[i] < arr[j] { 121 | tmp.push(arr[i]); 122 | i += 1; 123 | k += 1; 124 | } else { 125 | tmp.push(arr[j]); 126 | j += 1; 127 | k += 1; 128 | } 129 | } 130 | 131 | for i in 0..=(right - left) { 132 | arr[left + i] = tmp[i]; 133 | } 134 | } 135 | 136 | pub async fn quick_sort(arr: &mut Vec) { 137 | if arr.is_empty() { return; } 138 | 139 | let len = arr.len(); 140 | quick_sort_recursion(arr, 0, len - 1); 141 | } 142 | 143 | fn quick_sort_recursion(arr: &mut Vec, left: usize, right: usize) { 144 | if left >= right { return; } 145 | 146 | let pivot = partition(arr, left, right); 147 | if pivot != 0 { 148 | quick_sort_recursion(arr, left, pivot - 1); 149 | } 150 | quick_sort_recursion(arr, pivot + 1, right); 151 | } 152 | 153 | fn partition(arr: &mut Vec, left: usize, right: usize) -> usize { 154 | let pivot = right; 155 | let mut i = left; 156 | 157 | for j in left..right { 158 | if arr[j] < arr[pivot] { 159 | arr.swap(i, j); 160 | i += 1; 161 | } 162 | } 163 | 164 | arr.swap(i, right); 165 | i 166 | } 167 | -------------------------------------------------------------------------------- /project/sort_lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod sync_lib; 2 | pub mod async_lib; 3 | -------------------------------------------------------------------------------- /project/sort_lib/src/sync_lib.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | pub fn bubble_sort(arr: &mut Vec) { 4 | if arr.is_empty() { return; } 5 | 6 | for i in 0..arr.len() - 1 { 7 | let mut flag = false; 8 | for j in 0..arr.len() - i - 1 { 9 | if arr[j] > arr[j + 1] { 10 | let tmp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = tmp; 13 | 14 | flag = true; 15 | } 16 | } 17 | 18 | if !flag { break; } 19 | } 20 | } 21 | 22 | pub fn selection_sort(arr: &mut Vec) { 23 | if arr.is_empty() { return; } 24 | 25 | for i in 0..arr.len() - 1 { 26 | let mut min_index = i; 27 | for j in i + 1..arr.len() { 28 | if arr[j] < arr[min_index] { 29 | min_index = j; 30 | } 31 | } 32 | 33 | if i != min_index { 34 | arr.swap(i, min_index); 35 | } 36 | } 37 | } 38 | 39 | pub fn insertion_sort(arr: &mut Vec) { 40 | if arr.is_empty() { return; } 41 | 42 | for i in 1..arr.len() { 43 | let current = arr[i]; 44 | 45 | let mut j = (i - 1) as i32; 46 | while j >= 0 { 47 | if arr[j as usize] > current { 48 | arr[(j + 1) as usize] = arr[j as usize]; 49 | } else { 50 | break; 51 | } 52 | j -= 1; 53 | } 54 | 55 | arr[(j + 1) as usize] = current; 56 | } 57 | } 58 | 59 | pub fn heap_sort(arr: &mut Vec) { 60 | build_heap(arr); 61 | 62 | for i in (0..arr.len()).rev() { 63 | arr.swap(0, i); 64 | heapify(arr, 0, i); 65 | } 66 | } 67 | 68 | fn build_heap(arr: &mut Vec) { 69 | let len = arr.len(); 70 | for i in (0..len / 2).rev() { 71 | heapify(arr, i, len); 72 | } 73 | } 74 | 75 | fn heapify(arr: &mut Vec, idx: usize, len: usize) { 76 | let mut idx = idx; 77 | loop { 78 | let mut max_pos = idx; 79 | if 2 * idx + 1 < len && arr[idx] < arr[2 * idx + 1] { max_pos = 2 * idx + 1; } 80 | if 2 * idx + 2 < len && arr[max_pos] < arr[2 * idx + 2] { max_pos = 2 * idx + 2; } 81 | 82 | if max_pos == idx { break; } 83 | arr.swap(idx, max_pos); 84 | idx = max_pos; 85 | } 86 | } 87 | 88 | pub fn merge_sort(arr: &mut Vec) { 89 | if arr.is_empty() { return; } 90 | 91 | let n = arr.len() - 1; 92 | merge_sort_recursion(arr, 0, n); 93 | } 94 | 95 | fn merge_sort_recursion(arr: &mut Vec, left: usize, right: usize) { 96 | if left >= right { return; } 97 | let middle = left + (right - left) / 2; 98 | 99 | merge_sort_recursion(arr, left, middle); 100 | merge_sort_recursion(arr, middle + 1, right); 101 | 102 | merge(arr, left, middle, right); 103 | } 104 | 105 | fn merge(arr: &mut Vec, left: usize, middle: usize, right: usize) { 106 | let mut i = left; 107 | let mut j = middle + 1; 108 | let mut k = left; 109 | let mut tmp = vec![]; 110 | 111 | while k <= right { 112 | if i > middle { 113 | tmp.push(arr[j]); 114 | j += 1; 115 | k += 1; 116 | } else if j > right { 117 | tmp.push(arr[i]); 118 | i += 1; 119 | k += 1; 120 | } else if arr[i] < arr[j] { 121 | tmp.push(arr[i]); 122 | i += 1; 123 | k += 1; 124 | } else { 125 | tmp.push(arr[j]); 126 | j += 1; 127 | k += 1; 128 | } 129 | } 130 | 131 | for i in 0..=(right - left) { 132 | arr[left + i] = tmp[i]; 133 | } 134 | } 135 | 136 | pub fn quick_sort(arr: &mut Vec) { 137 | if arr.is_empty() { return; } 138 | 139 | let len = arr.len(); 140 | quick_sort_recursion(arr, 0, len - 1); 141 | } 142 | 143 | fn quick_sort_recursion(arr: &mut Vec, left: usize, right: usize) { 144 | if left >= right { return; } 145 | 146 | let pivot = partition(arr, left, right); 147 | if pivot != 0 { 148 | quick_sort_recursion(arr, left, pivot - 1); 149 | } 150 | quick_sort_recursion(arr, pivot + 1, right); 151 | } 152 | 153 | fn partition(arr: &mut Vec, left: usize, right: usize) -> usize { 154 | let pivot = right; 155 | let mut i = left; 156 | 157 | for j in left..right { 158 | if arr[j] < arr[pivot] { 159 | arr.swap(i, j); 160 | i += 1; 161 | } 162 | } 163 | 164 | arr.swap(i, right); 165 | i 166 | } 167 | 168 | pub fn is_sorted(arr: &Vec) -> bool { 169 | for i in 0..arr.len() - 1 { 170 | if arr[i] > arr[i + 1] { 171 | return false; 172 | } 173 | } 174 | 175 | return true; 176 | } 177 | 178 | #[cfg(test)] 179 | mod tests { 180 | use super::*; 181 | 182 | #[test] 183 | fn bubble_test() { 184 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 185 | bubble_sort(&mut nums); 186 | assert!(is_sorted(&nums)); 187 | } 188 | 189 | #[test] 190 | fn selection_test() { 191 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 192 | selection_sort(&mut nums); 193 | assert!(is_sorted(&nums)); 194 | } 195 | 196 | #[test] 197 | fn insertion_test() { 198 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 199 | insertion_sort(&mut nums); 200 | assert!(is_sorted(&nums)); 201 | } 202 | 203 | #[test] 204 | fn heap_test() { 205 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 206 | heap_sort(&mut nums); 207 | assert!(is_sorted(&nums)); 208 | } 209 | 210 | #[test] 211 | fn merge_test() { 212 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 213 | merge_sort(&mut nums); 214 | assert!(is_sorted(&nums)); 215 | } 216 | 217 | #[test] 218 | fn quick_test() { 219 | let mut nums = vec![7.7, 9.9, 12.12, 11.11, 6.6, 3.3]; 220 | quick_sort(&mut nums); 221 | assert!(is_sorted(&nums)); 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /project/sort_middleware_lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sort_middleware_lib" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | sort_lib = { path = "../sort_lib" } 11 | random_data_lib = { path = "../random_data_lib" } 12 | async-std = "1.6.3" 13 | time = "0.1" 14 | -------------------------------------------------------------------------------- /project/sort_middleware_lib/src/async_lib.rs: -------------------------------------------------------------------------------- 1 | use sort_lib::async_lib; 2 | 3 | pub async fn bubble_sort(mut arr: Vec, function_name: &str) { 4 | let start = time::get_time(); 5 | async_lib::bubble_sort(&mut arr).await; 6 | let end = time::get_time(); 7 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 8 | } 9 | 10 | pub async fn selection_sort(mut arr: Vec, function_name: &str) { 11 | let start = time::get_time(); 12 | async_lib::selection_sort(&mut arr).await; 13 | let end = time::get_time(); 14 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 15 | } 16 | 17 | pub async fn insertion_sort(mut arr: Vec, function_name: &str) { 18 | let start = time::get_time(); 19 | async_lib::insertion_sort(&mut arr).await; 20 | let end = time::get_time(); 21 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 22 | } 23 | 24 | pub async fn heap_sort(mut arr: Vec, function_name: &str) { 25 | let start = time::get_time(); 26 | async_lib::heap_sort(&mut arr).await; 27 | let end = time::get_time(); 28 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 29 | } 30 | 31 | pub async fn merge_sort(mut arr: Vec, function_name: &str) { 32 | let start = time::get_time(); 33 | async_lib::merge_sort(&mut arr).await; 34 | let end = time::get_time(); 35 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 36 | } 37 | 38 | pub async fn quick_sort(mut arr: Vec, function_name: &str) { 39 | let start = time::get_time(); 40 | async_lib::quick_sort(&mut arr).await; 41 | let end = time::get_time(); 42 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 43 | } 44 | -------------------------------------------------------------------------------- /project/sort_middleware_lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod sync_lib; 2 | pub mod async_lib; 3 | -------------------------------------------------------------------------------- /project/sort_middleware_lib/src/main.rs: -------------------------------------------------------------------------------- 1 | use sort_middleware_lib::sync_lib; 2 | 3 | fn main() { 4 | let n = 20000; 5 | let start = time::get_time(); 6 | 7 | let arr1 = random_data_lib::generate_random_array(n, 0, n); 8 | let arr2 = arr1.clone(); 9 | let arr3 = arr1.clone(); 10 | let arr4 = arr1.clone(); 11 | let arr5 = arr1.clone(); 12 | let arr6 = arr1.clone(); 13 | 14 | sync_lib::bubble_sort(arr1, "bubble_random_sort"); 15 | sync_lib::selection_sort(arr2, "selection_random_sort"); 16 | sync_lib::insertion_sort(arr3, "insertion_random_sort"); 17 | sync_lib::heap_sort(arr4, "heap_random_sort"); 18 | sync_lib::merge_sort(arr5, "merge_random_sort"); 19 | sync_lib::quick_sort(arr6, "quick_random_sort"); 20 | 21 | let arr1 = random_data_lib::generate_nearly_ordered_array(n, 100); 22 | let arr2 = arr1.clone(); 23 | let arr3 = arr1.clone(); 24 | let arr4 = arr1.clone(); 25 | let arr5 = arr1.clone(); 26 | let arr6 = arr1.clone(); 27 | 28 | sync_lib::bubble_sort(arr1, "bubble_nearly_ordered_sort"); 29 | sync_lib::selection_sort(arr2, "selection_nearly_ordered_sort"); 30 | sync_lib::insertion_sort(arr3, "insertion_nearly_ordered_sort"); 31 | sync_lib::heap_sort(arr4, "heap_nearly_ordered_sort"); 32 | sync_lib::merge_sort(arr5, "merge_nearly_ordered_sort"); 33 | sync_lib::quick_sort(arr6, "quick_nearly_ordered_sort"); 34 | 35 | let end = time::get_time(); 36 | println!("duration: {:?}", (end - start).num_milliseconds()); 37 | } -------------------------------------------------------------------------------- /project/sort_middleware_lib/src/sync_lib.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | use sort_lib::sync_lib; 4 | 5 | pub fn bubble_sort(mut arr: Vec, function_name: &str) { 6 | sort(sync_lib::bubble_sort, &mut arr, function_name); 7 | } 8 | 9 | pub fn selection_sort(mut arr: Vec, function_name: &str) { 10 | sort(sync_lib::selection_sort, &mut arr, function_name); 11 | } 12 | 13 | pub fn insertion_sort(mut arr: Vec, function_name: &str) { 14 | sort(sync_lib::insertion_sort, &mut arr, function_name); 15 | } 16 | 17 | pub fn heap_sort(mut arr: Vec, function_name: &str) { 18 | sort(sync_lib::heap_sort, &mut arr, function_name); 19 | } 20 | 21 | pub fn merge_sort(mut arr: Vec, function_name: &str) { 22 | sort(sync_lib::merge_sort, &mut arr, function_name); 23 | } 24 | 25 | pub fn quick_sort(mut arr: Vec, function_name: &str) { 26 | sort(sync_lib::quick_sort, &mut arr, function_name); 27 | } 28 | 29 | fn sort(sort_function: fn(&mut Vec), arr: &mut Vec, function_name: &str) { 30 | let start = time::get_time(); 31 | sort_function(arr); 32 | let end = time::get_time(); 33 | 34 | println!("{} duration: {:?}", function_name, (end - start).num_milliseconds()); 35 | } 36 | -------------------------------------------------------------------------------- /project/thread_run/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "thread_run" 3 | version = "0.1.0" 4 | authors = ["anray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | sort_middleware_lib = { path = "../sort_middleware_lib" } 11 | random_data_lib = { path = "../random_data_lib" } 12 | threadpool = "1.8.1" 13 | time = "0.1" 14 | -------------------------------------------------------------------------------- /project/thread_run/src/main.rs: -------------------------------------------------------------------------------- 1 | use threadpool::ThreadPool; 2 | use sort_middleware_lib::sync_lib; 3 | 4 | fn main() { 5 | let n = 20000; 6 | let n_workers = 5; 7 | let pool = ThreadPool::new(n_workers); 8 | let start = time::get_time(); 9 | 10 | let arr1 = random_data_lib::generate_random_array(n, 0, n); 11 | let arr2 = arr1.clone(); 12 | let arr3 = arr1.clone(); 13 | let arr4 = arr1.clone(); 14 | let arr5 = arr1.clone(); 15 | let arr6 = arr1.clone(); 16 | 17 | let arr11 = random_data_lib::generate_nearly_ordered_array(n, 100); 18 | let arr12 = arr11.clone(); 19 | let arr13 = arr11.clone(); 20 | let arr14 = arr11.clone(); 21 | let arr15 = arr11.clone(); 22 | let arr16 = arr11.clone(); 23 | 24 | pool.execute(move || { 25 | sync_lib::bubble_sort(arr1, "bubble_random_sort"); 26 | }); 27 | 28 | pool.execute(move || { 29 | sync_lib::selection_sort(arr2, "selection_random_sort"); 30 | }); 31 | 32 | pool.execute(move || { 33 | sync_lib::insertion_sort(arr3, "insertion_random_sort"); 34 | }); 35 | 36 | pool.execute(move || { 37 | sync_lib::heap_sort(arr4, "heap_random_sort"); 38 | }); 39 | 40 | pool.execute(move || { 41 | sync_lib::merge_sort(arr5, "merge_random_sort"); 42 | }); 43 | 44 | pool.execute(move || { 45 | sync_lib::quick_sort(arr6, "quick_random_sort"); 46 | }); 47 | 48 | pool.execute(move || { 49 | sync_lib::bubble_sort(arr11, "bubble_nearly_ordered_sort"); 50 | }); 51 | 52 | pool.execute(move || { 53 | sync_lib::selection_sort(arr12, "selection_nearly_ordered_sort"); 54 | }); 55 | 56 | pool.execute(move || { 57 | sync_lib::insertion_sort(arr13, "insertion_nearly_ordered_sort"); 58 | }); 59 | 60 | pool.execute(move || { 61 | sync_lib::heap_sort(arr14, "heap_nearly_ordered_sort"); 62 | }); 63 | 64 | pool.execute(move || { 65 | sync_lib::merge_sort(arr15, "merge_nearly_ordered_sort"); 66 | }); 67 | 68 | pool.execute(move || { 69 | sync_lib::quick_sort(arr16, "quick_nearly_ordered_sort"); 70 | }); 71 | 72 | pool.join(); 73 | 74 | let end = time::get_time(); 75 | println!("duration: {:?}", (end - start).num_milliseconds()); 76 | } 77 | --------------------------------------------------------------------------------