From 6d87340ce30f90c6ad30e9a9f78c36a17ec24e9f Mon Sep 17 00:00:00 2001 From: yilin <1479826151@qq.com> Date: Sat, 20 Sep 2025 23:16:04 +0800 Subject: [PATCH] Update --- exercises/algorithm/algorithm1.rs | 170 ++++++++++------ exercises/algorithm/algorithm10.rs | 46 ++++- exercises/algorithm/algorithm2.rs | 87 +++++---- exercises/algorithm/algorithm3.rs | 52 ++++- exercises/algorithm/algorithm4.rs | 63 ++++-- exercises/algorithm/algorithm5.rs | 32 +-- exercises/algorithm/algorithm6.rs | 36 ++-- exercises/algorithm/algorithm7.rs | 260 ++++++++++++++----------- exercises/algorithm/algorithm8.rs | 30 ++- exercises/algorithm/algorithm9.rs | 55 +++++- exercises/clippy/clippy1.rs | 4 +- exercises/clippy/clippy2.rs | 6 +- exercises/clippy/clippy3.rs | 19 +- exercises/conversions/as_ref_mut.rs | 11 +- exercises/conversions/from_into.rs | 18 +- exercises/conversions/from_str.rs | 22 ++- exercises/conversions/try_from_into.rs | 35 +++- exercises/conversions/using_as.rs | 4 +- exercises/enums/enums1.rs | 6 +- exercises/enums/enums2.rs | 6 +- exercises/enums/enums3.rs | 21 +- exercises/error_handling/errors1.rs | 8 +- exercises/error_handling/errors2.rs | 4 +- exercises/error_handling/errors3.rs | 21 +- exercises/error_handling/errors4.rs | 8 +- exercises/error_handling/errors5.rs | 4 +- exercises/error_handling/errors6.rs | 7 +- exercises/generics/generics1.rs | 4 +- exercises/generics/generics2.rs | 10 +- exercises/hashmaps/hashmaps1.rs | 7 +- exercises/hashmaps/hashmaps2.rs | 5 +- exercises/hashmaps/hashmaps3.rs | 27 ++- exercises/iterators/iterators1.rs | 10 +- exercises/iterators/iterators2.rs | 10 +- exercises/iterators/iterators3.rs | 21 +- exercises/iterators/iterators4.rs | 3 +- exercises/iterators/iterators5.rs | 6 +- exercises/lifetimes/lifetimes1.rs | 4 +- exercises/lifetimes/lifetimes2.rs | 4 +- exercises/lifetimes/lifetimes3.rs | 8 +- exercises/macros/macros1.rs | 4 +- exercises/macros/macros2.rs | 11 +- exercises/macros/macros3.rs | 5 +- exercises/macros/macros4.rs | 4 +- exercises/modules/modules1.rs | 4 +- exercises/modules/modules2.rs | 6 +- exercises/modules/modules3.rs | 4 +- exercises/options/options1.rs | 12 +- exercises/options/options2.rs | 12 +- exercises/options/options3.rs | 4 +- exercises/quiz2.rs | 23 ++- exercises/quiz3.rs | 18 +- exercises/smart_pointers/arc1.rs | 6 +- exercises/smart_pointers/box1.rs | 8 +- exercises/smart_pointers/cow1.rs | 9 +- exercises/smart_pointers/rc1.rs | 11 +- exercises/strings/strings1.rs | 4 +- exercises/strings/strings2.rs | 4 +- exercises/strings/strings3.rs | 8 +- exercises/strings/strings4.rs | 22 +-- exercises/structs/structs1.rs | 12 +- exercises/structs/structs2.rs | 7 +- exercises/structs/structs3.rs | 8 +- exercises/tests/Cargo.lock | 7 + exercises/tests/Cargo.toml | 7 + exercises/tests/build.rs | 11 +- exercises/tests/tests1.rs | 4 +- exercises/tests/tests2.rs | 4 +- exercises/tests/tests3.rs | 6 +- exercises/tests/tests4.rs | 8 +- exercises/tests/tests5.rs | 7 +- exercises/tests/tests6.rs | 8 +- exercises/tests/tests7.rs | 2 +- exercises/tests/tests8.rs | 2 +- exercises/tests/tests9.rs | 6 +- exercises/threads/threads1.rs | 3 +- exercises/threads/threads2.rs | 11 +- exercises/threads/threads3.rs | 9 +- exercises/traits/traits1.rs | 5 +- exercises/traits/traits2.rs | 10 +- exercises/traits/traits3.rs | 6 +- exercises/traits/traits4.rs | 4 +- exercises/traits/traits5.rs | 4 +- 83 files changed, 997 insertions(+), 487 deletions(-) create mode 100644 exercises/tests/Cargo.lock create mode 100644 exercises/tests/Cargo.toml diff --git a/exercises/algorithm/algorithm1.rs b/exercises/algorithm/algorithm1.rs index f7a99bf02..f2c0a0d84 100644 --- a/exercises/algorithm/algorithm1.rs +++ b/exercises/algorithm/algorithm1.rs @@ -1,8 +1,8 @@ /* - single linked list merge - This problem requires you to merge two ordered singly linked lists into one ordered singly linked list + single linked list merge + This problem requires you to merge two ordered singly linked lists into one ordered singly linked list */ -// I AM NOT DONE +// use std::fmt::{self, Display, Formatter}; use std::ptr::NonNull; @@ -16,10 +16,7 @@ struct Node { impl Node { fn new(t: T) -> Node { - Node { - val: t, - next: None, - } + Node { val: t, next: None } } } #[derive(Debug)] @@ -29,13 +26,13 @@ struct LinkedList { end: Option>>, } -impl Default for LinkedList { +impl Default for LinkedList { fn default() -> Self { Self::new() } } -impl LinkedList { +impl LinkedList { pub fn new() -> Self { Self { length: 0, @@ -69,15 +66,72 @@ impl LinkedList { }, } } - pub fn merge(list_a:LinkedList,list_b:LinkedList) -> Self - { - //TODO - Self { - length: 0, - start: None, - end: None, + pub fn merge(list_a: LinkedList, list_b: LinkedList) -> Self { + //TODO + let mut ret = LinkedList::new(); + + let mut a_node = list_a.start; + let mut b_node = list_b.start; + ret.length = list_a.length + list_b.length; + let mut stop = false; + let mut first = true; + + while !stop { + match (a_node, b_node) { + (Some(a_ptr), Some(b_ptr)) => { + let a_val = unsafe { &(*a_ptr.as_ptr()).val }; + let b_val = unsafe { &(*b_ptr.as_ptr()).val }; + if a_val <= b_val { + if first { + ret.start = a_node; + ret.end = a_node; + first = false; + } else { + unsafe { (*ret.end.unwrap().as_ptr()).next = a_node }; + ret.end = a_node; + } + a_node = unsafe { (*a_node.unwrap().as_ptr()).next }; + } else { + if first { + ret.start = b_node; + ret.end = b_node; + first = false; + } else { + unsafe { (*ret.end.unwrap().as_ptr()).next = b_node }; + ret.end = b_node; + } + b_node = unsafe { (*b_node.unwrap().as_ptr()).next }; + } + } + (None, None) => { + stop = true; + } + (Some(a_ptr), None) => { + if first { + ret.start = a_node; + ret.end = list_a.end; + first = false; + } else { + unsafe { (*ret.end.unwrap().as_ptr()).next = a_node }; + ret.end = list_a.end; + } + stop = true; + } + (None, Some(b_ptr)) => { + if first { + ret.start = b_node; + ret.end = list_b.end; + first = false; + } else { + unsafe { (*ret.end.unwrap().as_ptr()).next = b_node }; + ret.end = list_b.end; + } + stop = true; + } + } } - } + ret + } } impl Display for LinkedList @@ -130,44 +184,44 @@ mod tests { #[test] fn test_merge_linked_list_1() { - let mut list_a = LinkedList::::new(); - let mut list_b = LinkedList::::new(); - let vec_a = vec![1,3,5,7]; - let vec_b = vec![2,4,6,8]; - let target_vec = vec![1,2,3,4,5,6,7,8]; - - for i in 0..vec_a.len(){ - list_a.add(vec_a[i]); - } - for i in 0..vec_b.len(){ - list_b.add(vec_b[i]); - } - println!("list a {} list b {}", list_a,list_b); - let mut list_c = LinkedList::::merge(list_a,list_b); - println!("merged List is {}", list_c); - for i in 0..target_vec.len(){ - assert_eq!(target_vec[i],*list_c.get(i as i32).unwrap()); - } - } - #[test] - fn test_merge_linked_list_2() { - let mut list_a = LinkedList::::new(); - let mut list_b = LinkedList::::new(); - let vec_a = vec![11,33,44,88,89,90,100]; - let vec_b = vec![1,22,30,45]; - let target_vec = vec![1,11,22,30,33,44,45,88,89,90,100]; - - for i in 0..vec_a.len(){ - list_a.add(vec_a[i]); - } - for i in 0..vec_b.len(){ - list_b.add(vec_b[i]); - } - println!("list a {} list b {}", list_a,list_b); - let mut list_c = LinkedList::::merge(list_a,list_b); - println!("merged List is {}", list_c); - for i in 0..target_vec.len(){ - assert_eq!(target_vec[i],*list_c.get(i as i32).unwrap()); - } - } -} \ No newline at end of file + let mut list_a = LinkedList::::new(); + let mut list_b = LinkedList::::new(); + let vec_a = vec![1, 3, 5, 7]; + let vec_b = vec![2, 4, 6, 8]; + let target_vec = vec![1, 2, 3, 4, 5, 6, 7, 8]; + + for i in 0..vec_a.len() { + list_a.add(vec_a[i]); + } + for i in 0..vec_b.len() { + list_b.add(vec_b[i]); + } + println!("list a {} list b {}", list_a, list_b); + let mut list_c = LinkedList::::merge(list_a, list_b); + println!("merged List is {}", list_c); + for i in 0..target_vec.len() { + assert_eq!(target_vec[i], *list_c.get(i as i32).unwrap()); + } + } + #[test] + fn test_merge_linked_list_2() { + let mut list_a = LinkedList::::new(); + let mut list_b = LinkedList::::new(); + let vec_a = vec![11, 33, 44, 88, 89, 90, 100]; + let vec_b = vec![1, 22, 30, 45]; + let target_vec = vec![1, 11, 22, 30, 33, 44, 45, 88, 89, 90, 100]; + + for i in 0..vec_a.len() { + list_a.add(vec_a[i]); + } + for i in 0..vec_b.len() { + list_b.add(vec_b[i]); + } + println!("list a {} list b {}", list_a, list_b); + let mut list_c = LinkedList::::merge(list_a, list_b); + println!("merged List is {}", list_c); + for i in 0..target_vec.len() { + assert_eq!(target_vec[i], *list_c.get(i as i32).unwrap()); + } + } +} diff --git a/exercises/algorithm/algorithm10.rs b/exercises/algorithm/algorithm10.rs index a2ad731d0..c12eb3e37 100644 --- a/exercises/algorithm/algorithm10.rs +++ b/exercises/algorithm/algorithm10.rs @@ -1,8 +1,8 @@ /* - graph - This problem requires you to implement a basic graph functio + graph + This problem requires you to implement a basic graph functio */ -// I AM NOT DONE +// use std::collections::{HashMap, HashSet}; use std::fmt; @@ -30,6 +30,36 @@ impl Graph for UndirectedGraph { } fn add_edge(&mut self, edge: (&str, &str, i32)) { //TODO + let table = self.adjacency_table_mutable(); + let (l, r, val) = edge; + if let Some(ref mut adj) = table.get_mut(l) { + let mut exist = false; + for (ref mut s, ref mut v) in adj.iter_mut() { + if s == r { + *v = val; + exist = true; + } + } + if !exist { + adj.push((String::from(r), val)); + } + } else { + table.insert(String::from(l), vec![(String::from(r), val)]); + } + if let Some(ref mut adj) = table.get_mut(r) { + let mut exist = false; + for (ref mut s, ref mut v) in adj.iter_mut() { + if s == l { + *v = val; + exist = true; + } + } + if !exist { + adj.push((String::from(l), val)); + } + } else { + table.insert(String::from(r), vec![(String::from(l), val)]); + } } } pub trait Graph { @@ -38,7 +68,13 @@ pub trait Graph { fn adjacency_table(&self) -> &HashMap>; fn add_node(&mut self, node: &str) -> bool { //TODO - true + + if self.contains(node) { + return false; + } + let mut table = self.adjacency_table_mutable(); + table.insert(String::from(node), Vec::new()); + true } fn add_edge(&mut self, edge: (&str, &str, i32)) { //TODO @@ -81,4 +117,4 @@ mod test_undirected_graph { assert_eq!(graph.edges().contains(edge), true); } } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm2.rs b/exercises/algorithm/algorithm2.rs index 08720ff44..093d8bb49 100644 --- a/exercises/algorithm/algorithm2.rs +++ b/exercises/algorithm/algorithm2.rs @@ -1,8 +1,8 @@ /* - double linked list reverse - This problem requires you to reverse a doubly linked list + double linked list reverse + This problem requires you to reverse a doubly linked list */ -// I AM NOT DONE +// use std::fmt::{self, Display, Formatter}; use std::ptr::NonNull; @@ -72,9 +72,26 @@ impl LinkedList { }, } } - pub fn reverse(&mut self){ - // TODO - } + pub fn reverse(&mut self) { + // TODO + let mut current = self.start; + let mut before = None; + self.end = self.start; + while let Some(node_ptr) = current { + let next = unsafe { (*node_ptr.as_ptr()).next }; + if next.is_some() { + unsafe { (*node_ptr.as_ptr()).next = before }; + unsafe { (*node_ptr.as_ptr()).prev = next }; + before = current; + current = next; + } else { + self.start = current; + unsafe { (*node_ptr.as_ptr()).next = before }; + unsafe { (*node_ptr.as_ptr()).prev = next }; + break; + } + } + } } impl Display for LinkedList @@ -127,33 +144,33 @@ mod tests { #[test] fn test_reverse_linked_list_1() { - let mut list = LinkedList::::new(); - let original_vec = vec![2,3,5,11,9,7]; - let reverse_vec = vec![7,9,11,5,3,2]; - for i in 0..original_vec.len(){ - list.add(original_vec[i]); - } - println!("Linked List is {}", list); - list.reverse(); - println!("Reversed Linked List is {}", list); - for i in 0..original_vec.len(){ - assert_eq!(reverse_vec[i],*list.get(i as i32).unwrap()); - } - } + let mut list = LinkedList::::new(); + let original_vec = vec![2, 3, 5, 11, 9, 7]; + let reverse_vec = vec![7, 9, 11, 5, 3, 2]; + for i in 0..original_vec.len() { + list.add(original_vec[i]); + } + println!("Linked List is {}", list); + list.reverse(); + println!("Reversed Linked List is {}", list); + for i in 0..original_vec.len() { + assert_eq!(reverse_vec[i], *list.get(i as i32).unwrap()); + } + } - #[test] - fn test_reverse_linked_list_2() { - let mut list = LinkedList::::new(); - let original_vec = vec![34,56,78,25,90,10,19,34,21,45]; - let reverse_vec = vec![45,21,34,19,10,90,25,78,56,34]; - for i in 0..original_vec.len(){ - list.add(original_vec[i]); - } - println!("Linked List is {}", list); - list.reverse(); - println!("Reversed Linked List is {}", list); - for i in 0..original_vec.len(){ - assert_eq!(reverse_vec[i],*list.get(i as i32).unwrap()); - } - } -} \ No newline at end of file + #[test] + fn test_reverse_linked_list_2() { + let mut list = LinkedList::::new(); + let original_vec = vec![34, 56, 78, 25, 90, 10, 19, 34, 21, 45]; + let reverse_vec = vec![45, 21, 34, 19, 10, 90, 25, 78, 56, 34]; + for i in 0..original_vec.len() { + list.add(original_vec[i]); + } + println!("Linked List is {}", list); + list.reverse(); + println!("Reversed Linked List is {}", list); + for i in 0..original_vec.len() { + assert_eq!(reverse_vec[i], *list.get(i as i32).unwrap()); + } + } +} diff --git a/exercises/algorithm/algorithm3.rs b/exercises/algorithm/algorithm3.rs index 37878d6a7..5a8a371b1 100644 --- a/exercises/algorithm/algorithm3.rs +++ b/exercises/algorithm/algorithm3.rs @@ -1,12 +1,46 @@ /* - sort - This problem requires you to implement a sorting algorithm - you can use bubble sorting, insertion sorting, heap sorting, etc. + sort + This problem requires you to implement a sorting algorithm + you can use bubble sorting, insertion sorting, heap sorting, etc. */ -// I AM NOT DONE +// -fn sort(array: &mut [T]){ - //TODO +fn sort(array: &mut [T]) { + //TODO + let len = array.len(); + if len <= 1 { + return; + } + fn sift_down(arr: &mut [T], mut root: usize, heap_size: usize) { + loop { + let left_child = 2 * root + 1; + if left_child >= heap_size { + break; + } + let mut biggest = if arr[left_child] > arr[root] { + left_child + } else { + root + }; + if left_child + 1 < heap_size && arr[left_child + 1] > arr[biggest] { + biggest = left_child + 1; + } + if biggest == root { + break; + } + arr.swap(root, biggest); + root = biggest; + } + } + + for start in (0..len / 2).rev() { + sift_down(array, start, len); + } + + for end in (1..len).rev() { + array.swap(0, end); + sift_down(array, 0, end); + } } #[cfg(test)] mod tests { @@ -18,16 +52,16 @@ mod tests { sort(&mut vec); assert_eq!(vec, vec![19, 37, 46, 57, 64, 73, 75, 91]); } - #[test] + #[test] fn test_sort_2() { let mut vec = vec![1]; sort(&mut vec); assert_eq!(vec, vec![1]); } - #[test] + #[test] fn test_sort_3() { let mut vec = vec![99, 88, 77, 66, 55, 44, 33, 22, 11]; sort(&mut vec); assert_eq!(vec, vec![11, 22, 33, 44, 55, 66, 77, 88, 99]); } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm4.rs b/exercises/algorithm/algorithm4.rs index 271b772c5..37a83d67b 100644 --- a/exercises/algorithm/algorithm4.rs +++ b/exercises/algorithm/algorithm4.rs @@ -1,13 +1,12 @@ /* - binary_search tree - This problem requires you to implement a basic interface for a binary tree + binary_search tree + This problem requires you to implement a basic interface for a binary tree */ -//I AM NOT DONE +// use std::cmp::Ordering; use std::fmt::Debug; - #[derive(Debug)] struct TreeNode where @@ -43,7 +42,6 @@ impl BinarySearchTree where T: Ord, { - fn new() -> Self { BinarySearchTree { root: None } } @@ -51,12 +49,27 @@ where // Insert a value into the BST fn insert(&mut self, value: T) { //TODO + if let None = self.root { + self.root = Some(Box::new(TreeNode::new(value))); + } else { + if let Some(ref mut node) = self.root { + node.insert(value); + } + } } // Search for a value in the BST fn search(&self, value: T) -> bool { //TODO - true + let mut current = &self.root; + while let Some(node) = current { + match node.value.cmp(&value) { + Ordering::Equal => return true, + Ordering::Less => current = &node.right, + Ordering::Greater => current = &node.left, + } + } + false } } @@ -67,10 +80,33 @@ where // Insert a node into the tree fn insert(&mut self, value: T) { //TODO + let mut node = self; + loop { + match node.value.cmp(&value) { + Ordering::Equal => return, + Ordering::Less => { + if let Some(ref mut r_node) = node.right { + node = r_node; + } + else { + node.right = Some(Box::new(TreeNode::new(value))); + return; + } + }, + Ordering::Greater => { + if let Some(ref mut l_node) = node.left { + node = l_node; + } + else { + node.left = Some(Box::new(TreeNode::new(value))); + return; + } + }, + } + } } } - #[cfg(test)] mod tests { use super::*; @@ -79,24 +115,20 @@ mod tests { fn test_insert_and_search() { let mut bst = BinarySearchTree::new(); - assert_eq!(bst.search(1), false); - bst.insert(5); bst.insert(3); bst.insert(7); bst.insert(2); bst.insert(4); - assert_eq!(bst.search(5), true); assert_eq!(bst.search(3), true); assert_eq!(bst.search(7), true); assert_eq!(bst.search(2), true); assert_eq!(bst.search(4), true); - assert_eq!(bst.search(1), false); assert_eq!(bst.search(6), false); } @@ -105,22 +137,17 @@ mod tests { fn test_insert_duplicate() { let mut bst = BinarySearchTree::new(); - bst.insert(1); bst.insert(1); - assert_eq!(bst.search(1), true); - match bst.root { Some(ref node) => { assert!(node.left.is_none()); assert!(node.right.is_none()); - }, + } None => panic!("Root should not be None after insertion"), } } -} - - +} diff --git a/exercises/algorithm/algorithm5.rs b/exercises/algorithm/algorithm5.rs index 8f206d1a9..80477c25d 100644 --- a/exercises/algorithm/algorithm5.rs +++ b/exercises/algorithm/algorithm5.rs @@ -1,14 +1,14 @@ /* - bfs - This problem requires you to implement a basic BFS algorithm + bfs + This problem requires you to implement a basic BFS algorithm */ -//I AM NOT DONE +// use std::collections::VecDeque; // Define a graph struct Graph { - adj: Vec>, + adj: Vec>, } impl Graph { @@ -21,21 +21,32 @@ impl Graph { // Add an edge to the graph fn add_edge(&mut self, src: usize, dest: usize) { - self.adj[src].push(dest); - self.adj[dest].push(src); + self.adj[src].push(dest); + self.adj[dest].push(src); } // Perform a breadth-first search on the graph, return the order of visited nodes fn bfs_with_return(&self, start: usize) -> Vec { - - //TODO - + //TODO + let mut visited = std::collections::HashSet::new(); + let mut queue = VecDeque::new(); let mut visit_order = vec![]; + queue.push_back(start); + while !queue.is_empty() { + let node = queue.pop_front().unwrap(); + if visited.contains(&node) { + continue; + } + visited.insert(node); + visit_order.push(node); + for &neighbor in &self.adj[node] { + queue.push_back(neighbor); + } + } visit_order } } - #[cfg(test)] mod tests { use super::*; @@ -84,4 +95,3 @@ mod tests { assert_eq!(visited_order, vec![0]); } } - diff --git a/exercises/algorithm/algorithm6.rs b/exercises/algorithm/algorithm6.rs index 813146f7c..b85518e1b 100644 --- a/exercises/algorithm/algorithm6.rs +++ b/exercises/algorithm/algorithm6.rs @@ -1,13 +1,13 @@ /* - dfs - This problem requires you to implement a basic DFS traversal + dfs + This problem requires you to implement a basic DFS traversal */ -// I AM NOT DONE +// use std::collections::HashSet; struct Graph { - adj: Vec>, + adj: Vec>, } impl Graph { @@ -19,17 +19,32 @@ impl Graph { fn add_edge(&mut self, src: usize, dest: usize) { self.adj[src].push(dest); - self.adj[dest].push(src); + self.adj[dest].push(src); } fn dfs_util(&self, v: usize, visited: &mut HashSet, visit_order: &mut Vec) { //TODO + let mut stack = std::collections::VecDeque::new(); + stack.push_back(v); + while !stack.is_empty() { + let val = stack.pop_back().unwrap(); + if visited.contains(&val) { + continue; + } + visited.insert(val); + visit_order.push(val); + for &loc in self.adj[val].iter().rev() { + if !visited.contains(&loc) { + stack.push_back(loc); + } + } + } } // Perform a depth-first search on the graph, return the order of visited nodes fn dfs(&self, start: usize) -> Vec { let mut visited = HashSet::new(); - let mut visit_order = Vec::new(); + let mut visit_order = Vec::new(); self.dfs_util(start, &mut visited, &mut visit_order); visit_order } @@ -56,7 +71,7 @@ mod tests { graph.add_edge(0, 2); graph.add_edge(1, 2); graph.add_edge(2, 3); - graph.add_edge(3, 3); + graph.add_edge(3, 3); let visit_order = graph.dfs(0); assert_eq!(visit_order, vec![0, 1, 2, 3]); @@ -67,12 +82,11 @@ mod tests { let mut graph = Graph::new(5); graph.add_edge(0, 1); graph.add_edge(0, 2); - graph.add_edge(3, 4); + graph.add_edge(3, 4); let visit_order = graph.dfs(0); - assert_eq!(visit_order, vec![0, 1, 2]); + assert_eq!(visit_order, vec![0, 1, 2]); let visit_order_disconnected = graph.dfs(3); - assert_eq!(visit_order_disconnected, vec![3, 4]); + assert_eq!(visit_order_disconnected, vec![3, 4]); } } - diff --git a/exercises/algorithm/algorithm7.rs b/exercises/algorithm/algorithm7.rs index e0c3a5ab2..e250a8328 100644 --- a/exercises/algorithm/algorithm7.rs +++ b/exercises/algorithm/algorithm7.rs @@ -1,142 +1,166 @@ /* - stack - This question requires you to use a stack to achieve a bracket match + stack + This question requires you to use a stack to achieve a bracket match */ -// I AM NOT DONE +// #[derive(Debug)] struct Stack { - size: usize, - data: Vec, + size: usize, + data: Vec, } impl Stack { - fn new() -> Self { - Self { - size: 0, - data: Vec::new(), - } - } - fn is_empty(&self) -> bool { - 0 == self.size - } - fn len(&self) -> usize { - self.size - } - fn clear(&mut self) { - self.size = 0; - self.data.clear(); - } - fn push(&mut self, val: T) { - self.data.push(val); - self.size += 1; - } - fn pop(&mut self) -> Option { - // TODO - None - } - fn peek(&self) -> Option<&T> { - if 0 == self.size { - return None; - } - self.data.get(self.size - 1) - } - fn peek_mut(&mut self) -> Option<&mut T> { - if 0 == self.size { - return None; - } - self.data.get_mut(self.size - 1) - } - fn into_iter(self) -> IntoIter { - IntoIter(self) - } - fn iter(&self) -> Iter { - let mut iterator = Iter { - stack: Vec::new() - }; - for item in self.data.iter() { - iterator.stack.push(item); - } - iterator - } - fn iter_mut(&mut self) -> IterMut { - let mut iterator = IterMut { - stack: Vec::new() - }; - for item in self.data.iter_mut() { - iterator.stack.push(item); - } - iterator - } + fn new() -> Self { + Self { + size: 0, + data: Vec::new(), + } + } + fn is_empty(&self) -> bool { + 0 == self.size + } + fn len(&self) -> usize { + self.size + } + fn clear(&mut self) { + self.size = 0; + self.data.clear(); + } + fn push(&mut self, val: T) { + self.data.push(val); + self.size += 1; + } + fn pop(&mut self) -> Option { + // TODO + if self.size == 0 { + None + } else { + self.size -= 1; + self.data.pop() + } + } + fn peek(&self) -> Option<&T> { + if 0 == self.size { + return None; + } + self.data.get(self.size - 1) + } + fn peek_mut(&mut self) -> Option<&mut T> { + if 0 == self.size { + return None; + } + self.data.get_mut(self.size - 1) + } + fn into_iter(self) -> IntoIter { + IntoIter(self) + } + fn iter(&self) -> Iter { + let mut iterator = Iter { stack: Vec::new() }; + for item in self.data.iter() { + iterator.stack.push(item); + } + iterator + } + fn iter_mut(&mut self) -> IterMut { + let mut iterator = IterMut { stack: Vec::new() }; + for item in self.data.iter_mut() { + iterator.stack.push(item); + } + iterator + } } struct IntoIter(Stack); impl Iterator for IntoIter { - type Item = T; - fn next(&mut self) -> Option { - if !self.0.is_empty() { - self.0.size -= 1;self.0.data.pop() - } - else { - None - } - } + type Item = T; + fn next(&mut self) -> Option { + if !self.0.is_empty() { + self.0.size -= 1; + self.0.data.pop() + } else { + None + } + } } struct Iter<'a, T: 'a> { - stack: Vec<&'a T>, + stack: Vec<&'a T>, } impl<'a, T> Iterator for Iter<'a, T> { - type Item = &'a T; - fn next(&mut self) -> Option { - self.stack.pop() - } + type Item = &'a T; + fn next(&mut self) -> Option { + self.stack.pop() + } } struct IterMut<'a, T: 'a> { - stack: Vec<&'a mut T>, + stack: Vec<&'a mut T>, } impl<'a, T> Iterator for IterMut<'a, T> { - type Item = &'a mut T; - fn next(&mut self) -> Option { - self.stack.pop() - } + type Item = &'a mut T; + fn next(&mut self) -> Option { + self.stack.pop() + } } -fn bracket_match(bracket: &str) -> bool -{ - //TODO - true +fn bracket_match(bracket: &str) -> bool { + //TODO + let mut sta = Stack::new(); + let brackets = std::collections::HashSet::from(['(', ')', '{', '}', '[', ']']); + for c in bracket.chars() { + if !brackets.contains(&c) { + continue; + } + if c == '(' || c == '{' || c == '[' { + sta.push(c); + } else { + if let Some(top) = sta.pop() { + match (top, c) { + ('(', ')') | ('[', ']') | ('{', '}') => continue, + _ => return false, + } + } else { + return false; + } + } + } + if sta.is_empty() { + true + } + else { + false + } } #[cfg(test)] mod tests { - use super::*; - - #[test] - fn bracket_matching_1(){ - let s = "(2+3){func}[abc]"; - assert_eq!(bracket_match(s),true); - } - #[test] - fn bracket_matching_2(){ - let s = "(2+3)*(3-1"; - assert_eq!(bracket_match(s),false); - } - #[test] - fn bracket_matching_3(){ - let s = "{{([])}}"; - assert_eq!(bracket_match(s),true); - } - #[test] - fn bracket_matching_4(){ - let s = "{{(}[)]}"; - assert_eq!(bracket_match(s),false); - } - #[test] - fn bracket_matching_5(){ - let s = "[[[]]]]]]]]]"; - assert_eq!(bracket_match(s),false); - } - #[test] - fn bracket_matching_6(){ - let s = ""; - assert_eq!(bracket_match(s),true); - } -} \ No newline at end of file + use super::*; + + #[test] + fn bracket_matching_1() { + let s = "(2+3){func}[abc]"; + assert_eq!(bracket_match(s), true); + } + #[test] + fn bracket_matching_2() { + let s = "(2+3)*(3-1"; + assert_eq!(bracket_match(s), false); + } + #[test] + fn bracket_matching_3() { + let s = "{{([])}}"; + assert_eq!(bracket_match(s), true); + } + #[test] + fn bracket_matching_4() { + let s = "{{(}[)]}"; + assert_eq!(bracket_match(s), false); + } + #[test] + fn bracket_matching_5() { + let s = "[[[]]]]]]]]]"; + assert_eq!(bracket_match(s), false); + } + #[test] + fn bracket_matching_6() { + let s = ""; + assert_eq!(bracket_match(s), true); + } +} diff --git a/exercises/algorithm/algorithm8.rs b/exercises/algorithm/algorithm8.rs index d1d183b84..8dcfd3e67 100644 --- a/exercises/algorithm/algorithm8.rs +++ b/exercises/algorithm/algorithm8.rs @@ -2,7 +2,7 @@ queue This question requires you to use queues to implement the functionality of the stac */ -// I AM NOT DONE +// #[derive(Debug)] pub struct Queue { @@ -68,14 +68,38 @@ impl myStack { } pub fn push(&mut self, elem: T) { //TODO + if self.q1.is_empty() { + self.q2.enqueue(elem); + } + else { + self.q1.enqueue(elem); + } } pub fn pop(&mut self) -> Result { //TODO - Err("Stack is empty") + if self.is_empty() { + Err("Stack is empty") + } + else { + if self.q1.is_empty() { + let len = self.q2.size(); + for _ in 1..len { + self.q1.enqueue(self.q2.dequeue().unwrap()); + } + self.q2.dequeue() + } + else { + let len = self.q1.size(); + for _ in 1..len { + self.q2.enqueue(self.q1.dequeue().unwrap()); + } + self.q1.dequeue() + } + } } pub fn is_empty(&self) -> bool { //TODO - true + self.q1.is_empty() && self.q2.is_empty() } } diff --git a/exercises/algorithm/algorithm9.rs b/exercises/algorithm/algorithm9.rs index 6c8021a4d..7ede55bc1 100644 --- a/exercises/algorithm/algorithm9.rs +++ b/exercises/algorithm/algorithm9.rs @@ -1,15 +1,15 @@ /* - heap - This question requires you to implement a binary heap function + heap + This question requires you to implement a binary heap function */ -// I AM NOT DONE +// use std::cmp::Ord; use std::default::Default; pub struct Heap where - T: Default, + T: Default + Ord, { count: usize, items: Vec, @@ -18,7 +18,7 @@ where impl Heap where - T: Default, + T: Default + Ord, { pub fn new(comparator: fn(&T, &T) -> bool) -> Self { Self { @@ -38,6 +38,18 @@ where pub fn add(&mut self, value: T) { //TODO + self.count += 1; + self.items.push(value); + let mut idx = self.count; + while idx > 1 { + let mut par_idx = self.parent_idx(idx); + if (self.comparator)(&self.items[par_idx], &self.items[idx]) { + break; + } else { + self.items.swap(par_idx, idx); + idx = par_idx; + } + } } fn parent_idx(&self, idx: usize) -> usize { @@ -58,7 +70,16 @@ where fn smallest_child_idx(&self, idx: usize) -> usize { //TODO - 0 + let l_idx = self.left_child_idx(idx); + let r_idx = self.right_child_idx(idx); + if r_idx >= self.count { + return l_idx; + } + if (self.comparator)(&self.items[l_idx], &self.items[r_idx]) { + l_idx + } else { + r_idx + } } } @@ -79,13 +100,29 @@ where impl Iterator for Heap where - T: Default, + T: Default + Ord, { type Item = T; fn next(&mut self) -> Option { //TODO - None + if self.count == 0 { + return None; + } + + self.items.swap(1usize, self.count); + self.count -= 1; + let mut idx = 1; + while self.children_present(idx) { + let ex_child = self.smallest_child_idx(idx); + if (self.comparator)(&self.items[idx], &self.items[ex_child]) { + break; + } else { + self.items.swap(idx, ex_child); + idx = ex_child; + } + } + self.items.pop() } } @@ -151,4 +188,4 @@ mod tests { heap.add(1); assert_eq!(heap.next(), Some(2)); } -} \ No newline at end of file +} diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index 95c0141f4..40dac35dc 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -9,12 +9,12 @@ // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::f32; fn main() { - let pi = 3.14f32; + let pi = f32::consts::PI; let radius = 5.00f32; let area = pi * f32::powi(radius, 2); diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index 9b87a0b70..e208a6dbb 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -3,13 +3,13 @@ // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() { let mut res = 42; let option = Some(12); - for x in option { - res += x; + if let Some(v) = option { + res += v; } println!("{}", res); } diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index 35021f841..b07def759 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -1,31 +1,24 @@ // clippy3.rs -// +// // Here's a couple more easy Clippy fixes, so you can see its utility. // // Execute `rustlings hint clippy3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// #[allow(unused_variables, unused_assignments)] fn main() { let my_option: Option<()> = None; - if my_option.is_none() { - my_option.unwrap(); - } - let my_arr = &[ - -1, -2, -3 - -4, -5, -6 - ]; + let my_arr = &[-1, -2, -3, -4, -5, -6]; println!("My array! Here it is: {:?}", my_arr); - let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); - println!("This Vec is empty, see? {:?}", my_empty_vec); + vec![1, 2, 3, 4, 5].resize(0, 5); + println!("This Vec is empty, see? {:?}", [1; 0]); let mut value_a = 45; let mut value_b = 66; // Let's swap these two! - value_a = value_b; - value_b = value_a; + std::mem::swap(&mut value_a, &mut value_b); println!("value a: {}; value b: {}", value_a, value_b); } diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index 626a36c45..d7ad981cb 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -7,25 +7,26 @@ // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// // Obtain the number of bytes (not characters) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { +fn byte_counter>(arg: T) -> usize { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn char_counter(arg: T) -> usize { +fn char_counter>(arg: T) -> usize { arg.as_ref().chars().count() } // Squares a number using as_mut(). // TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { +fn num_sq, U: Copy + std::ops::Mul>(arg: &mut T) { // TODO: Implement the function body. - ??? + let mut mut_arg = arg.as_mut(); + *mut_arg = *mut_arg * *mut_arg; } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index aba471d92..1ebfc195e 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -40,10 +40,26 @@ impl Default for Person { // If while parsing the age, something goes wrong, then return the default of // Person Otherwise, then return an instantiated Person object with the results -// I AM NOT DONE +// impl From<&str> for Person { fn from(s: &str) -> Person { + if s.len() == 0 { + return Person::default(); + } + let v: Vec<&str> = s.split(',').collect(); + if v.len() != 2 { + return Person::default(); + } + let name = v[0]; + if name.len() == 0 { + return Person::default(); + } + if let Ok(age) = v[1].parse::() { + Person { name:String::from(name), age } + } else { + Person::default() + } } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32c..01e99d03e 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -31,7 +31,7 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE +// // Steps: // 1. If the length of the provided string is 0, an error should be returned @@ -52,6 +52,26 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.len() == 0 { + return Err(ParsePersonError::Empty); + } + let output :Vec<&str>= s.split(',').collect(); + if output.len()!=2 { + return Err(ParsePersonError::BadLen); + } + let name = output[0]; + if name.len() == 0 { + return Err(ParsePersonError::NoName); + } + let age = output[1].parse::(); + match age { + Ok(age) => { + Ok(Person{ name:String::from(name), age }) + } + Err(err) => { + Err(ParsePersonError::ParseInt(err)) + } + } } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39e..cd5ac5ea3 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -27,7 +27,7 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE +// // Your task is to complete this implementation and return an Ok result of inner // type Color. You need to create an implementation for a tuple of three @@ -41,6 +41,15 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + let (r, g, b) = tuple; + match (r, g, b) { + (0..=255, 0..=255, 0..=255) => Ok(Color { + red: r as u8, + green: g as u8, + blue: b as u8, + }), + _ => Err(IntoColorError::IntConversion), + } } } @@ -48,6 +57,15 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + let [r, g, b] = arr; + match (r, g, b) { + (0..=255, 0..=255, 0..=255) => Ok(Color { + red: r as u8, + green: g as u8, + blue: b as u8, + }), + _ => Err(IntoColorError::IntConversion), + } } } @@ -55,6 +73,21 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + let len = slice.len(); + if len != 3 { + return Err(IntoColorError::BadLen); + } + let r = slice[0]; + let g = slice[1]; + let b = slice[2]; + match (r, g, b) { + (0..=255, 0..=255, 0..=255) => Ok(Color { + red: r as u8, + green: g as u8, + blue: b as u8, + }), + _ => Err(IntoColorError::IntConversion), + } } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 414cef3a0..a42781926 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -10,11 +10,11 @@ // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); - total / values.len() + total / values.len() as f64 } fn main() { diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index 25525b252..28dc94348 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -2,11 +2,15 @@ // // No hints this time! ;) -// I AM NOT DONE +// #[derive(Debug)] enum Message { // TODO: define a few types of messages as used below + Quit, + Echo, + Move, + ChangeColor, } fn main() { diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index df93fe0f1..6e64cd16c 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -3,11 +3,15 @@ // Execute `rustlings hint enums2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[derive(Debug)] enum Message { // TODO: define the different variants used below + Move { x: i32, y: i32 }, + Echo(String), + ChangeColor(i32, i32, i32), + Quit, } impl Message { diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index 5d284417e..339d3a3e3 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -5,10 +5,14 @@ // Execute `rustlings hint enums3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// enum Message { // TODO: implement the message variant types based on their usage below + ChangeColor(u8, u8, u8), + Echo(String), + Move(Point), + Quit, } struct Point { @@ -43,6 +47,21 @@ impl State { // variants // Remember: When passing a tuple as a function argument, you'll need // extra parentheses: fn function((t, u, p, l, e)) + match message { + Message::ChangeColor(r, g, b) => { + let color = (r, g, b); + self.change_color(color); + }, + Message::Echo(s) => { + self.echo(s); + }, + Message::Move(p) => { + self.move_position(p); + }, + Message::Quit => { + self.quit() + } + } } } diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 13d2724cb..0cebb92e7 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -9,14 +9,14 @@ // Execute `rustlings hint errors1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".into()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index d86f326d0..2d474b210 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -19,14 +19,14 @@ // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index d42d3b17c..5fac317fa 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::num::ParseIntError; @@ -15,13 +15,20 @@ fn main() { let mut tokens = 100; let pretend_user_input = "8"; - let cost = total_cost(pretend_user_input)?; + let cost = total_cost(pretend_user_input); - if cost > tokens { - println!("You can't afford that many!"); - } else { - tokens -= cost; - println!("You now have {} tokens.", tokens); + match cost { + Ok(cost) => { + if cost > tokens { + println!("You can't afford that many!"); + } else { + tokens -= cost; + println!("You now have {} tokens.", tokens); + } + } + Err(msg) => { + println!("{:?}", msg); + } } } diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index e04bff77a..476583bba 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -17,7 +17,11 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + match value { + 0 => Err(CreationError::Zero), + 1.. => Ok(PositiveNonzeroInteger(value as u64)), + ..0 => Err(CreationError::Negative), + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 92461a7e0..1ec6e5268 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -22,14 +22,14 @@ // Execute `rustlings hint errors5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::error; use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let pretend_user_input = "42"; let x: i64 = pretend_user_input.parse()?; println!("output={:?}", PositiveNonzeroInteger::new(x)?); diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index aaf0948ef..f7c9665ea 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -9,7 +9,7 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::num::ParseIntError; @@ -26,12 +26,15 @@ impl ParsePosNonzeroError { } // TODO: add another error conversion function here. // fn from_parseint... + fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError{ + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) -> Result { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); + let x = s.parse().map_err(ParsePosNonzeroError::from_parseint)?; PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) } diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 35c1d2fee..e071d8876 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -6,9 +6,9 @@ // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() { - let mut shopping_list: Vec = Vec::new(); + let mut shopping_list: Vec<_> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 074cd938c..0cd6cd436 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -6,14 +6,14 @@ // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// -struct Wrapper { - value: u32, +struct Wrapper { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl Wrapper { + pub fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index 80829eaa6..b8c43c1a0 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -11,16 +11,17 @@ // Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::collections::HashMap; fn fruit_basket() -> HashMap { - let mut basket = // TODO: declare your hash map here. + let mut basket = HashMap::new();// TODO: declare your hash map here. // Two bananas are already given for you :) basket.insert(String::from("banana"), 2); - + basket.insert(String::from("apple"), 3); + basket.insert(String::from("orange"), 4); // TODO: Put more fruits in your basket here. basket diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a59256909..35022d979 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -14,7 +14,7 @@ // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::collections::HashMap; @@ -40,6 +40,9 @@ fn fruit_basket(basket: &mut HashMap) { // TODO: Insert new fruits if they are not already present in the // basket. Note that you are not allowed to put any type of fruit that's // already present! + if !basket.contains_key(&fruit) { + basket.insert(fruit, 3); + } } } diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 08e977c33..83406328c 100644 --- a/exercises/hashmaps/hashmaps3.rs +++ b/exercises/hashmaps/hashmaps3.rs @@ -14,7 +14,7 @@ // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::collections::HashMap; @@ -39,7 +39,32 @@ fn build_scores_table(results: String) -> HashMap { // will be the number of goals conceded from team_2, and similarly // goals scored by team_2 will be the number of goals conceded by // team_1. + if let Some(ref mut team1) = scores.get_mut(&team_1_name) { + team1.goals_scored += team_1_score; + team1.goals_conceded += team_2_score; + } else { + scores.insert( + team_1_name, + Team { + goals_scored: team_1_score, + goals_conceded: team_2_score, + }, + ); + } + if let Some(ref mut team2) = scores.get_mut(&team_2_name) { + team2.goals_scored += team_2_score; + team2.goals_conceded += team_1_score; + } else { + scores.insert( + team_2_name, + Team { + goals_scored: team_2_score, + goals_conceded: team_1_score, + }, + ); + } } + scores } diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs index b3f698be3..6cbbffced 100644 --- a/exercises/iterators/iterators1.rs +++ b/exercises/iterators/iterators1.rs @@ -9,17 +9,17 @@ // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2 assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3 assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 + assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4 } diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs index dda82a085..9d885a1f3 100644 --- a/exercises/iterators/iterators2.rs +++ b/exercises/iterators/iterators2.rs @@ -6,7 +6,7 @@ // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// // Step 1. // Complete the `capitalize_first` function. @@ -15,7 +15,9 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => { + String::from(first.to_ascii_uppercase()) + &input[1..] + }, } } @@ -24,7 +26,7 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + words.iter().map(|word| capitalize_first(word)).collect() } // Step 3. @@ -32,7 +34,7 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + capitalize_words_vector(words).join("") } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index 29fa23a3e..88ec0f62e 100644 --- a/exercises/iterators/iterators3.rs +++ b/exercises/iterators/iterators3.rs @@ -9,7 +9,7 @@ // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { @@ -26,23 +26,32 @@ pub struct NotDivisibleError { // Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. pub fn divide(a: i32, b: i32) -> Result { - todo!(); + if b == 0 { + return Err(DivisionError::DivideByZero); + } else if a % b != 0 { + return Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: a, + divisor: b, + })); + } else { + return Ok(a / b); + } } // Complete the function and return a value of the correct type so the test // passes. // Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { +fn result_with_list() -> Result, DivisionError> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + numbers.into_iter().map(|n| divide(n, 27)).collect() } // Complete the function and return a value of the correct type so the test // passes. // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + numbers.into_iter().map(|n| divide(n, 27)).collect() } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index 79e1692ba..894e95457 100644 --- a/exercises/iterators/iterators4.rs +++ b/exercises/iterators/iterators4.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num @@ -15,6 +15,7 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + (1..=num).fold(1, |acc, x| acc * x) } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index a062ee4c7..128e517fc 100644 --- a/exercises/iterators/iterators5.rs +++ b/exercises/iterators/iterators5.rs @@ -11,7 +11,7 @@ // Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::collections::HashMap; @@ -35,7 +35,7 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + map.values().filter(|&prog| prog == &value).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -54,7 +54,7 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + collection.iter().map(|hash| hash.values().filter(|&prog| prog == &value).count()).sum::() } #[cfg(test)] diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs index 87bde490c..82d4dd1d2 100644 --- a/exercises/lifetimes/lifetimes1.rs +++ b/exercises/lifetimes/lifetimes1.rs @@ -8,9 +8,9 @@ // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// -fn longest(x: &str, y: &str) -> &str { +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs index 4f3d8c185..849e665c3 100644 --- a/exercises/lifetimes/lifetimes2.rs +++ b/exercises/lifetimes/lifetimes2.rs @@ -6,7 +6,7 @@ // Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { @@ -22,6 +22,6 @@ fn main() { { let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); + println!("The longest string is '{}'", result); } - println!("The longest string is '{}'", result); } diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs index 9c59f9c02..fb685eb3b 100644 --- a/exercises/lifetimes/lifetimes3.rs +++ b/exercises/lifetimes/lifetimes3.rs @@ -5,11 +5,11 @@ // Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// -struct Book { - author: &str, - title: &str, +struct Book<'a> { + author: &'a str, + title: &'a str, } fn main() { diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs index 678de6eec..3c46da6c6 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// macro_rules! my_macro { () => { @@ -12,5 +12,5 @@ macro_rules! my_macro { } fn main() { - my_macro(); + my_macro!(); } diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index 788fc16a9..352d263e5 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -3,14 +3,13 @@ // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - -fn main() { - my_macro!(); -} - +// macro_rules! my_macro { () => { println!("Check out my macro!"); }; } + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs index b795c1493..54f0dc918 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -5,7 +5,7 @@ // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// mod macros { macro_rules! my_macro { @@ -13,8 +13,9 @@ mod macros { println!("Check out my macro!"); }; } + pub(crate) use my_macro; } fn main() { - my_macro!(); + macros::my_macro!(); } diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 71b45a095..30b3af9b0 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -3,13 +3,13 @@ // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[rustfmt::skip] macro_rules! my_macro { () => { println!("Check out my macro!"); - } + }; ($val:expr) => { println!("Look at this other macro: {}", $val); } diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 9eb5a48b7..abde74638 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint modules1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// mod sausage_factory { // Don't let anybody outside of this module see this! @@ -11,7 +11,7 @@ mod sausage_factory { String::from("Ginger") } - fn make_sausage() { + pub fn make_sausage() { get_secret_recipe(); println!("sausage!"); } diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs index 041545431..f9d7b0a90 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -7,12 +7,12 @@ // Execute `rustlings hint modules2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// mod delicious_snacks { // TODO: Fix these use statements - use self::fruits::PEAR as ??? - use self::veggies::CUCUMBER as ??? + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; mod fruits { pub const PEAR: &'static str = "Pear"; diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index f2bb05038..a6a697ac3 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,10 +8,10 @@ // Execute `rustlings hint modules3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// // TODO: Complete this use statement -use ??? +use std::time::{SystemTime, UNIX_EPOCH}; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs index e131b48b9..6e4a7d31b 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint options1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// // This function returns how much icecream there is left in the fridge. // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them @@ -13,7 +13,13 @@ fn maybe_icecream(time_of_day: u16) -> Option { // value of 0 The Option output should gracefully handle cases where // time_of_day > 23. // TODO: Complete the function body - remember to return an Option! - ??? + match time_of_day { + 0..22 => { + Some(5) + }, + 22..25 => Some(0), + _ => None + } } #[cfg(test)] @@ -33,7 +39,7 @@ mod tests { fn raw_value() { // TODO: Fix this test. How do you get at the value contained in the // Option? - let icecreams = maybe_icecream(12); + let icecreams = maybe_icecream(12).unwrap(); assert_eq!(icecreams, 5); } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4d998e7d0..54654dff5 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint options2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[cfg(test)] mod tests { @@ -13,7 +13,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -32,9 +32,11 @@ mod tests { // TODO: make this a while let statement - remember that vector.pop also // adds another layer of Option. You can stack `Option`s into // while let and if let. - integer = optional_integers.pop() { - assert_eq!(integer, cursor); - cursor -= 1; + while let Some(integer) = optional_integers.pop() { + if let Some(integer) = integer { + assert_eq!(integer, cursor); + cursor -= 1; + } } assert_eq!(cursor, 0); diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 23c15eab8..bdae4a524 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint options3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// struct Point { x: i32, @@ -14,7 +14,7 @@ fn main() { let y: Option = Some(Point { x: 100, y: 200 }); match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), + Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y), _ => panic!("no match!"), } y; // Fix without deleting this line. diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index 29925cafc..aa92e5f59 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -20,7 +20,7 @@ // // No hints this time! -// I AM NOT DONE +// pub enum Command { Uppercase, @@ -32,11 +32,26 @@ mod my_module { use super::Command; // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { + pub fn transformer(input: Vec<(String, Command)>) -> Vec { // TODO: Complete the output declaration! - let mut output: ??? = vec![]; + let mut output: _ = vec![]; for (string, command) in input.iter() { // TODO: Complete the function body. You can do it! + match command { + Command::Uppercase => { + output.push(string.to_uppercase()); + } + Command::Trim => { + output.push(string.trim().to_string()); + } + Command::Append(count) => { + let mut s = String::from(string); + for _ in 0..*count { + s += "bar"; + } + output.push(s); + } + } } output } @@ -45,8 +60,8 @@ mod my_module { #[cfg(test)] mod tests { // TODO: What do we need to import to have `transformer` in scope? - use ???; use super::Command; + use crate::my_module::transformer; #[test] fn it_works() { diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 3b01d3132..152d19f7c 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -16,18 +16,20 @@ // // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -pub struct ReportCard { - pub grade: f32, +// +use std::fmt::Display; +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade + ) } } @@ -52,7 +54,7 @@ mod tests { fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+", student_name: "Gary Plotter".to_string(), student_age: 11, }; diff --git a/exercises/smart_pointers/arc1.rs b/exercises/smart_pointers/arc1.rs index 3526ddcb9..01c9e0a45 100644 --- a/exercises/smart_pointers/arc1.rs +++ b/exercises/smart_pointers/arc1.rs @@ -21,7 +21,7 @@ // // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// #![forbid(unused_imports)] // Do not change this, (or the next) line. use std::sync::Arc; @@ -29,11 +29,11 @@ use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(numbers);// TODO let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = Arc::clone(&shared_numbers);// TODO joinhandles.push(thread::spawn(move || { let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); println!("Sum of offset {} is {}", offset, sum); diff --git a/exercises/smart_pointers/box1.rs b/exercises/smart_pointers/box1.rs index 513e7daa3..18b0e8f8b 100644 --- a/exercises/smart_pointers/box1.rs +++ b/exercises/smart_pointers/box1.rs @@ -18,11 +18,11 @@ // // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } @@ -35,11 +35,11 @@ fn main() { } pub fn create_empty_list() -> List { - todo!() + List::Nil } pub fn create_non_empty_list() -> List { - todo!() + List::Cons(0, Box::new(List::Nil)) } #[cfg(test)] diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs index 7ca916866..7fd5eef86 100644 --- a/exercises/smart_pointers/cow1.rs +++ b/exercises/smart_pointers/cow1.rs @@ -12,7 +12,7 @@ // // Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// use std::borrow::Cow; @@ -48,7 +48,8 @@ mod tests { let slice = [0, 1, 2]; let mut input = Cow::from(&slice[..]); match abs_all(&mut input) { - // TODO + Cow::Borrowed(_) => Ok(()), + _ => Err("Expected borrowed value"), } } @@ -61,6 +62,8 @@ mod tests { let mut input = Cow::from(slice); match abs_all(&mut input) { // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value") } } @@ -73,6 +76,8 @@ mod tests { let mut input = Cow::from(slice); match abs_all(&mut input) { // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), } } } diff --git a/exercises/smart_pointers/rc1.rs b/exercises/smart_pointers/rc1.rs index ad3f1ce29..ce043c021 100644 --- a/exercises/smart_pointers/rc1.rs +++ b/exercises/smart_pointers/rc1.rs @@ -10,7 +10,7 @@ // // Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// use std::rc::Rc; @@ -60,17 +60,17 @@ fn main() { jupiter.details(); // TODO - let saturn = Planet::Saturn(Rc::new(Sun {})); + let saturn = Planet::Saturn(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 7 references saturn.details(); // TODO - let uranus = Planet::Uranus(Rc::new(Sun {})); + let uranus = Planet::Uranus(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 8 references uranus.details(); // TODO - let neptune = Planet::Neptune(Rc::new(Sun {})); + let neptune = Planet::Neptune(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 9 references neptune.details(); @@ -92,12 +92,15 @@ fn main() { println!("reference count = {}", Rc::strong_count(&sun)); // 4 references // TODO + drop(earth); println!("reference count = {}", Rc::strong_count(&sun)); // 3 references // TODO + drop(venus); println!("reference count = {}", Rc::strong_count(&sun)); // 2 references // TODO + drop(mercury); println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference assert_eq!(Rc::strong_count(&sun), 1); diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index f50e1fa98..5dd625c2a 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -5,7 +5,7 @@ // Execute `rustlings hint strings1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() { let answer = current_favorite_color(); @@ -13,5 +13,5 @@ fn main() { } fn current_favorite_color() -> String { - "blue" + String::from("blue") } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 4d95d16a1..649be64df 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -5,11 +5,11 @@ // Execute `rustlings hint strings2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() { let word = String::from("green"); // Try not changing this line :) - if is_a_color_word(word) { + if is_a_color_word(&word) { println!("That is a color word I know!"); } else { println!("That is not a color word I know."); diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs index b29f9325b..21a1d3d80 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -3,21 +3,21 @@ // Execute `rustlings hint strings3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn trim_me(input: &str) -> String { // TODO: Remove whitespace from both ends of a string! - ??? + String::from(input.trim()) } fn compose_me(input: &str) -> String { // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? + String::from(input) + " world!" } fn replace_me(input: &str) -> String { // TODO: Replace "cars" in the string with "balloons"! - ??? + input.replace("cars", "balloons") } #[cfg(test)] diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index e8c54acc5..4878fa3db 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -7,7 +7,7 @@ // // No hints this time! -// I AM NOT DONE +// fn string_slice(arg: &str) { println!("{}", arg); @@ -17,14 +17,14 @@ fn string(arg: String) { } fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string_slice("blue"); + string("red".to_string()); + string(String::from("hi")); + string("rust is fun!".to_owned()); + string("nice weather".into()); + string(format!("Interpolation {}", "Station")); + string_slice(&String::from("abc")[0..1]); + string_slice(" hello there ".trim()); + string("Happy Monday!".to_string().replace("Mon", "Tues")); + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); } diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs index 5fa5821c5..bacf5ceb2 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -5,13 +5,16 @@ // Execute `rustlings hint structs1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// struct ColorClassicStruct { // TODO: Something goes here + red: u8, + green: u8, + blue: u8, } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct(u8, u8, u8); #[derive(Debug)] struct UnitLikeStruct; @@ -24,7 +27,7 @@ mod tests { fn classic_c_structs() { // TODO: Instantiate a classic c struct! // let green = - + let green = ColorClassicStruct {red:0, green: 255, blue: 0}; assert_eq!(green.red, 0); assert_eq!(green.green, 255); assert_eq!(green.blue, 0); @@ -34,7 +37,7 @@ mod tests { fn tuple_structs() { // TODO: Instantiate a tuple struct! // let green = - + let green = ColorTupleStruct(0,255,0); assert_eq!(green.0, 0); assert_eq!(green.1, 255); assert_eq!(green.2, 0); @@ -44,6 +47,7 @@ mod tests { fn unit_structs() { // TODO: Instantiate a unit-like struct! // let unit_like_struct = + let unit_like_struct = UnitLikeStruct; let message = format!("{:?}s are fun!", unit_like_struct); assert_eq!(message, "UnitLikeStructs are fun!"); diff --git a/exercises/structs/structs2.rs b/exercises/structs/structs2.rs index 328567f03..113000e47 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -5,7 +5,7 @@ // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[derive(Debug)] struct Order { @@ -39,6 +39,11 @@ mod tests { let order_template = create_order_template(); // TODO: Create your own order using the update syntax and template above! // let your_order = + let your_order = Order { + name: String::from("Hacker in Rust"), + count: 1, + ..order_template + }; assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.year, order_template.year); assert_eq!(your_order.made_by_phone, order_template.made_by_phone); diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs index 4851317c5..6b0a8b8ae 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[derive(Debug)] struct Package { @@ -29,12 +29,14 @@ impl Package { } } - fn is_international(&self) -> ??? { + fn is_international(&self) -> bool { // Something goes here... + self.sender_country != self.recipient_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { + fn get_fees(&self, cents_per_gram: i32) -> i32 { // Something goes here... + self.weight_in_grams * cents_per_gram } } diff --git a/exercises/tests/Cargo.lock b/exercises/tests/Cargo.lock new file mode 100644 index 000000000..d3a8d8c09 --- /dev/null +++ b/exercises/tests/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "tests8" +version = "0.0.1" diff --git a/exercises/tests/Cargo.toml b/exercises/tests/Cargo.toml new file mode 100644 index 000000000..646d1f04e --- /dev/null +++ b/exercises/tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tests8" +version = "0.0.1" +edition = "2021" +[[bin]] +name = "tests8" +path = "tests8.rs" \ No newline at end of file diff --git a/exercises/tests/build.rs b/exercises/tests/build.rs index aa518cef2..e78a06943 100644 --- a/exercises/tests/build.rs +++ b/exercises/tests/build.rs @@ -11,14 +11,15 @@ fn main() { .unwrap() .as_secs(); // What's the use of this timestamp here? let your_command = format!( - "Your command here with {}, please checkout exercises/tests/build.rs", - timestamp + "rustc-env=TEST_FOO={timestamp}" ); - println!("cargo:{}", your_command); + println!("cargo::{}", your_command); // In tests8, we should enable "pass" feature to make the // testcase return early. Fill in the command to tell // Cargo about that. - let your_command = "Your command here, please checkout exercises/tests/build.rs"; - println!("cargo:{}", your_command); + let your_command = "rustc-check-cfg=cfg(feature, values(\"pass\"))"; + //println!("cargo::{}", your_command); + println!("cargo::rustc-cfg=feature=\"pass\""); + } diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 810277ac3..ebdec97b5 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -10,12 +10,12 @@ // Execute `rustlings hint tests1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[cfg(test)] mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index f8024e9f2..d8cdc0b06 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -6,12 +6,12 @@ // Execute `rustlings hint tests2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// #[cfg(test)] mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1, 1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 4013e3841..be0857183 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint tests3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// pub fn is_even(num: i32) -> bool { num % 2 == 0 @@ -19,11 +19,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(2)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(!is_even(5)); } } diff --git a/exercises/tests/tests4.rs b/exercises/tests/tests4.rs index 935d0db17..6a7d4f6dc 100644 --- a/exercises/tests/tests4.rs +++ b/exercises/tests/tests4.rs @@ -5,7 +5,7 @@ // Execute `rustlings hint tests4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// struct Rectangle { width: i32, @@ -30,17 +30,19 @@ mod tests { fn correct_width_and_height() { // This test should check if the rectangle is the size that we pass into its constructor let rect = Rectangle::new(10, 20); - assert_eq!(???, 10); // check width - assert_eq!(???, 20); // check height + assert_eq!(rect.width, 10); // check width + assert_eq!(rect.height, 20); // check height } #[test] + #[should_panic] fn negative_width() { // This test should check if program panics when we try to create rectangle with negative width let _rect = Rectangle::new(-10, 10); } #[test] + #[should_panic] fn negative_height() { // This test should check if program panics when we try to create rectangle with negative height let _rect = Rectangle::new(10, -10); diff --git a/exercises/tests/tests5.rs b/exercises/tests/tests5.rs index 0cd5cb256..023917a37 100644 --- a/exercises/tests/tests5.rs +++ b/exercises/tests/tests5.rs @@ -22,7 +22,7 @@ // Execute `rustlings hint tests5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// /// # Safety /// @@ -31,8 +31,11 @@ unsafe fn modify_by_address(address: usize) { // TODO: Fill your safety notice of the code block below to match your // code's behavior and the contract of this function. You may use the // comment of the test below as your format reference. + // SAFETY: The address is guaranteed to be valid and contains + // a unique reference to a `u32` local variable. unsafe { - todo!("Your code goes here") + let ptr = address as *mut u32; + *ptr = 0xAABBCCDD; } } diff --git a/exercises/tests/tests6.rs b/exercises/tests/tests6.rs index 4c913779d..8dd5dd5e2 100644 --- a/exercises/tests/tests6.rs +++ b/exercises/tests/tests6.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint tests6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// struct Foo { a: u128, @@ -20,10 +20,10 @@ struct Foo { unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box { // SAFETY: The `ptr` contains an owned box of `Foo` by contract. We // simply reconstruct the box from that pointer. - let mut ret: Box = unsafe { ??? }; - todo!("The rest of the code goes here") + let mut ret: Box = unsafe { Box::from_raw(ptr) }; + ret.b = Some(String::from("hello")); + ret } - #[cfg(test)] mod tests { use super::*; diff --git a/exercises/tests/tests7.rs b/exercises/tests/tests7.rs index 66b37b72d..96f380ed5 100644 --- a/exercises/tests/tests7.rs +++ b/exercises/tests/tests7.rs @@ -34,7 +34,7 @@ // Execute `rustlings hint tests7` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() {} diff --git a/exercises/tests/tests8.rs b/exercises/tests/tests8.rs index ce7e35d8d..adf82443e 100644 --- a/exercises/tests/tests8.rs +++ b/exercises/tests/tests8.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint tests8` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// fn main() {} diff --git a/exercises/tests/tests9.rs b/exercises/tests/tests9.rs index ea2a8ec02..f55fd1873 100644 --- a/exercises/tests/tests9.rs +++ b/exercises/tests/tests9.rs @@ -27,15 +27,19 @@ // // You should NOT modify any existing code except for adding two lines of attributes. -// I AM NOT DONE +// + extern "Rust" { fn my_demo_function(a: u32) -> u32; + #[link_name= "my_demo_function"] fn my_demo_function_alias(a: u32) -> u32; } + mod Foo { // No `extern` equals `extern "Rust"`. + #[no_mangle] fn my_demo_function(a: u32) -> u32 { a } diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index 80b6def3e..0ca4aa7bf 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -8,7 +8,7 @@ // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::thread; use std::time::{Duration, Instant}; @@ -27,6 +27,7 @@ fn main() { let mut results: Vec = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + results.push(handle.join().expect("Error")); } if results.len() != 10 { diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d6..a8ce19967 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,25 +7,27 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::sync::Arc; use std::thread; use std::time::Duration; +use std::sync::Mutex; struct JobStatus { jobs_completed: u32, } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 })); let mut handles = vec![]; for _ in 0..10 { let status_shared = Arc::clone(&status); let handle = thread::spawn(move || { thread::sleep(Duration::from_millis(250)); // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; + let mut sta = status_shared.lock().unwrap(); + (*sta).jobs_completed += 1; }); handles.push(handle); } @@ -34,6 +36,7 @@ fn main() { // TODO: Print the value of the JobStatus.jobs_completed. Did you notice // anything interesting in the output? Do you have to 'join' on all the // handles? - println!("jobs completed {}", ???); + let sta = status.lock().unwrap(); + println!("jobs completed {:?}", sta.jobs_completed); } } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index db7d41ba6..62839882e 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint threads3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// use std::sync::mpsc; use std::sync::Arc; @@ -31,10 +31,13 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc1 = Arc::clone(&qc); let qc2 = Arc::clone(&qc); + let tx1 = tx.clone(); + let tx2 = tx.clone(); + thread::spawn(move || { for val in &qc1.first_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + tx1.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); @@ -42,7 +45,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { thread::spawn(move || { for val in &qc2.second_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + tx2.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 37dfcbfe8..40680d13b 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// trait AppendBar { fn append_bar(self) -> Self; @@ -15,6 +15,9 @@ trait AppendBar { impl AppendBar for String { // TODO: Implement `AppendBar` for type `String`. + fn append_bar(self) -> Self { + self + "Bar" + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 3e35f8e11..db194199d 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -8,13 +8,21 @@ // // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +// trait AppendBar { fn append_bar(self) -> Self; } // TODO: Implement trait `AppendBar` for a vector of strings. +impl AppendBar for Vec { + fn append_bar(self) -> Self { + let mut ret = self; + ret.push(String::from("Bar")); + ret + } +} + #[cfg(test)] mod tests { diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 4e2b06b0e..860b62998 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -8,10 +8,12 @@ // Execute `rustlings hint traits3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// pub trait Licensed { - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String { + String::from("Some information") + } } struct SomeSoftware { diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 4bda3e571..7933aac42 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint traits4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// pub trait Licensed { fn licensing_info(&self) -> String { @@ -23,7 +23,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { +fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index df1838054..ce712a39c 100644 --- a/exercises/traits/traits5.rs +++ b/exercises/traits/traits5.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint traits5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// pub trait SomeTrait { fn some_function(&self) -> bool { @@ -30,7 +30,7 @@ impl SomeTrait for OtherStruct {} impl OtherTrait for OtherStruct {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { item.some_function() && item.other_function() }