From fbb0d68df039e2d128e49601db7fbb14a6d42765 Mon Sep 17 00:00:00 2001 From: ylwqf Date: Sat, 27 Sep 2025 00:03:39 +0800 Subject: [PATCH 1/2] update --- exercises/algorithm/algorithm1.rs | 128 +++++++------ exercises/algorithm/algorithm10.rs | 41 ++++- exercises/algorithm/algorithm2.rs | 81 ++++---- exercises/algorithm/algorithm3.rs | 25 ++- exercises/algorithm/algorithm4.rs | 52 +++--- exercises/algorithm/algorithm5.rs | 32 +++- exercises/algorithm/algorithm6.rs | 31 ++-- exercises/algorithm/algorithm7.rs | 246 +++++++++++++------------ exercises/algorithm/algorithm8.rs | 24 ++- exercises/algorithm/algorithm9.rs | 57 +++++- exercises/clippy/clippy1.rs | 4 +- exercises/clippy/clippy2.rs | 4 +- exercises/clippy/clippy3.rs | 18 +- exercises/conversions/as_ref_mut.rs | 13 +- exercises/conversions/from_into.rs | 32 +++- exercises/conversions/from_str.rs | 25 ++- exercises/conversions/try_from_into.rs | 21 ++- exercises/conversions/using_as.rs | 4 +- exercises/enums/enums1.rs | 7 +- exercises/enums/enums2.rs | 7 +- exercises/enums/enums3.rs | 17 +- exercises/error_handling/errors1.rs | 8 +- exercises/error_handling/errors2.rs | 4 +- exercises/error_handling/errors3.rs | 5 +- exercises/error_handling/errors4.rs | 11 +- 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 | 6 +- exercises/hashmaps/hashmaps2.rs | 15 +- exercises/hashmaps/hashmaps3.rs | 15 +- exercises/iterators/iterators1.rs | 10 +- exercises/iterators/iterators2.rs | 8 +- exercises/iterators/iterators3.rs | 18 +- exercises/iterators/iterators4.rs | 3 +- exercises/iterators/iterators5.rs | 6 +- exercises/lifetimes/lifetimes1.rs | 4 +- exercises/lifetimes/lifetimes2.rs | 9 +- exercises/lifetimes/lifetimes3.rs | 8 +- exercises/macros/macros1.rs | 4 +- exercises/macros/macros2.rs | 10 +- exercises/macros/macros3.rs | 3 +- exercises/macros/macros4.rs | 4 +- exercises/modules/modules1.rs | 4 +- exercises/modules/modules2.rs | 6 +- exercises/modules/modules3.rs | 5 +- exercises/options/options1.rs | 12 +- exercises/options/options2.rs | 10 +- exercises/options/options3.rs | 4 +- exercises/quiz2.rs | 24 ++- exercises/quiz3.rs | 10 +- exercises/smart_pointers/arc1.rs | 6 +- exercises/smart_pointers/box1.rs | 8 +- exercises/smart_pointers/cow1.rs | 11 +- 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 | 21 ++- exercises/structs/structs2.rs | 10 +- exercises/structs/structs3.rs | 10 +- exercises/tests/Cargo.lock | 7 + exercises/tests/Cargo.toml | 7 + exercises/tests/build.rs | 9 +- exercises/tests/tests1.rs | 4 +- exercises/tests/tests2.rs | 4 +- exercises/tests/tests3.rs | 6 +- exercises/tests/tests4.rs | 8 +- exercises/tests/tests5.rs | 8 +- exercises/tests/tests6.rs | 8 +- exercises/tests/tests7.rs | 2 - exercises/tests/tests8.rs | 2 - exercises/tests/tests9.rs | 4 +- exercises/threads/threads1.rs | 4 +- exercises/threads/threads2.rs | 12 +- exercises/threads/threads3.rs | 5 +- exercises/traits/traits1.rs | 6 +- exercises/traits/traits2.rs | 8 +- exercises/traits/traits3.rs | 6 +- exercises/traits/traits4.rs | 4 +- exercises/traits/traits5.rs | 4 +- src/exercise.rs | 2 +- 84 files changed, 769 insertions(+), 586 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..10f4fa13e 100644 --- a/exercises/algorithm/algorithm1.rs +++ b/exercises/algorithm/algorithm1.rs @@ -1,9 +1,7 @@ /* - 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; use std::vec::*; @@ -16,10 +14,7 @@ struct Node { impl Node { fn new(t: T) -> Node { - Node { - val: t, - next: None, - } + Node { val: t, next: None } } } #[derive(Debug)] @@ -69,15 +64,36 @@ impl LinkedList { }, } } - pub fn merge(list_a:LinkedList,list_b:LinkedList) -> Self - { - //TODO - Self { - length: 0, - start: None, - end: None, + pub fn merge(mut list_a: LinkedList, mut list_b: LinkedList) -> Self + where + T: Ord + Clone, + { + let mut merged = LinkedList::new(); + let mut idx_a = 0; + let mut idx_b = 0; + while idx_a < list_a.length as i32 && idx_b < list_b.length as i32 { + let a_val = list_a.get(idx_a).unwrap(); + let b_val = list_b.get(idx_b).unwrap(); + if a_val <= b_val { + merged.add((*a_val).clone()); + idx_a += 1; + } else { + merged.add((*b_val).clone()); + idx_b += 1; + } } - } + while idx_a < list_a.length as i32 { + let a_val = list_a.get(idx_a).unwrap(); + merged.add((*a_val).clone()); + idx_a += 1; + } + while idx_b < list_b.length as i32 { + let b_val = list_b.get(idx_b).unwrap(); + merged.add((*b_val).clone()); + idx_b += 1; + } + merged + } } impl Display for LinkedList @@ -130,44 +146,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]; + 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()); - } - } -} \ No newline at end of file + 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..46c0f8f75 100644 --- a/exercises/algorithm/algorithm10.rs +++ b/exercises/algorithm/algorithm10.rs @@ -2,8 +2,6 @@ graph This problem requires you to implement a basic graph functio */ -// I AM NOT DONE - use std::collections::{HashMap, HashSet}; use std::fmt; #[derive(Debug, Clone)] @@ -29,7 +27,23 @@ impl Graph for UndirectedGraph { &self.adjacency_table } fn add_edge(&mut self, edge: (&str, &str, i32)) { - //TODO + let (from, to, weight) = edge; + self.add_node(from); + self.add_node(to); + + { + let table = self.adjacency_table_mutable(); + if let Some(neighbors) = table.get_mut(from) { + neighbors.push((to.to_string(), weight)); + } + } + + { + let table = self.adjacency_table_mutable(); + if let Some(neighbors) = table.get_mut(to) { + neighbors.push((from.to_string(), weight)); + } + } } } pub trait Graph { @@ -37,11 +51,26 @@ pub trait Graph { fn adjacency_table_mutable(&mut self) -> &mut HashMap>; fn adjacency_table(&self) -> &HashMap>; fn add_node(&mut self, node: &str) -> bool { - //TODO - true + if self.contains(node) { + false + } else { + self + .adjacency_table_mutable() + .insert(node.to_string(), Vec::new()); + true + } } fn add_edge(&mut self, edge: (&str, &str, i32)) { - //TODO + let (from, to, weight) = edge; + if !self.contains(from) { + self.add_node(from); + } + if !self.contains(to) { + self.add_node(to); + } + if let Some(neighbors) = self.adjacency_table_mutable().get_mut(from) { + neighbors.push((to.to_string(), weight)); + } } fn contains(&self, node: &str) -> bool { self.adjacency_table().get(node).is_some() diff --git a/exercises/algorithm/algorithm2.rs b/exercises/algorithm/algorithm2.rs index 08720ff44..b45597df0 100644 --- a/exercises/algorithm/algorithm2.rs +++ b/exercises/algorithm/algorithm2.rs @@ -1,12 +1,9 @@ /* - 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; -use std::vec::*; #[derive(Debug)] struct Node { @@ -72,9 +69,19 @@ impl LinkedList { }, } } - pub fn reverse(&mut self){ - // TODO - } + pub fn reverse(&mut self) { + let mut current = self.start; + while let Some(mut node_ptr) = current { + unsafe { + let node = node_ptr.as_mut(); + let next = node.next; + node.next = node.prev; + node.prev = next; + current = next; + } + } + core::mem::swap(&mut self.start, &mut self.end); + } } impl Display for LinkedList @@ -127,33 +134,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..94807e0af 100644 --- a/exercises/algorithm/algorithm3.rs +++ b/exercises/algorithm/algorithm3.rs @@ -1,12 +1,17 @@ /* - 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]) { + let len = array.len(); + for i in 1..len { + let mut j = i; + while j > 0 && array[j - 1] > array[j] { + array.swap(j - 1, j); + j -= 1; + } + } } #[cfg(test)] mod tests { @@ -18,16 +23,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..aafe606d1 100644 --- a/exercises/algorithm/algorithm4.rs +++ b/exercises/algorithm/algorithm4.rs @@ -1,13 +1,11 @@ /* - 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,20 +41,32 @@ impl BinarySearchTree where T: Ord, { - fn new() -> Self { BinarySearchTree { root: None } } // Insert a value into the BST fn insert(&mut self, value: T) { - //TODO + match self.root { + Some(ref mut node) => node.insert(value), + None => self.root = Some(Box::new(TreeNode::new(value))), + } } // Search for a value in the BST fn search(&self, value: T) -> bool { - //TODO - true + Self::search_node(self.root.as_ref(), &value) + } + + fn search_node(node: Option<&Box>>, value: &T) -> bool { + match node { + Some(n) => match value.cmp(&n.value) { + Ordering::Less => Self::search_node(n.left.as_ref(), value), + Ordering::Greater => Self::search_node(n.right.as_ref(), value), + Ordering::Equal => true, + }, + None => false, + } } } @@ -66,11 +76,20 @@ where { // Insert a node into the tree fn insert(&mut self, value: T) { - //TODO + match value.cmp(&self.value) { + Ordering::Less => match self.left { + Some(ref mut node) => node.insert(value), + None => self.left = Some(Box::new(TreeNode::new(value))), + }, + Ordering::Greater => match self.right { + Some(ref mut node) => node.insert(value), + None => self.right = Some(Box::new(TreeNode::new(value))), + }, + Ordering::Equal => {} + } } } - #[cfg(test)] mod tests { use super::*; @@ -79,24 +98,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 +120,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..f2f17040e 100644 --- a/exercises/algorithm/algorithm5.rs +++ b/exercises/algorithm/algorithm5.rs @@ -1,14 +1,13 @@ /* - 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 +20,35 @@ 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 { + let mut visited = vec![false; self.adj.len()]; + let mut queue = VecDeque::new(); + let mut visit_order = vec![]; + + visited[start] = true; + queue.push_back(start); + + - //TODO + while let Some(node) = queue.pop_front() { + visit_order.push(node); + for &neighbor in &self.adj[node] { + if !visited[neighbor] { + visited[neighbor] = true; + queue.push_back(neighbor); + } + } + } - let mut visit_order = vec![]; visit_order } } - #[cfg(test)] mod tests { use super::*; @@ -84,4 +97,3 @@ mod tests { assert_eq!(visited_order, vec![0]); } } - diff --git a/exercises/algorithm/algorithm6.rs b/exercises/algorithm/algorithm6.rs index 813146f7c..35837a07f 100644 --- a/exercises/algorithm/algorithm6.rs +++ b/exercises/algorithm/algorithm6.rs @@ -1,13 +1,12 @@ /* - 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 +18,26 @@ 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 + if visited.contains(&v) { + return; + } + visited.insert(v); + visit_order.push(v); + for &neighbor in &self.adj[v] { + if !visited.contains(&neighbor) { + self.dfs_util(neighbor, visited, visit_order); + } + } } // 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 +64,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 +75,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..c40416d6f 100644 --- a/exercises/algorithm/algorithm7.rs +++ b/exercises/algorithm/algorithm7.rs @@ -1,142 +1,152 @@ /* - 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 { + 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 { + let mut stack = Stack::new(); + for ch in bracket.chars() { + match ch { + '(' => stack.push(')'), + '{' => stack.push('}'), + '[' => stack.push(']'), + ')' | '}' | ']' => match stack.pop() { + Some(expected) if expected == ch => {} + _ => return false, + }, + _ => {} + } + } + stack.is_empty() } #[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..7849696b3 100644 --- a/exercises/algorithm/algorithm8.rs +++ b/exercises/algorithm/algorithm8.rs @@ -2,8 +2,6 @@ queue This question requires you to use queues to implement the functionality of the stac */ -// I AM NOT DONE - #[derive(Debug)] pub struct Queue { elements: Vec, @@ -54,28 +52,28 @@ impl Default for Queue { pub struct myStack { - //TODO - q1:Queue, - q2:Queue + q1:Queue, + q2:Queue } impl myStack { pub fn new() -> Self { Self { - //TODO - q1:Queue::::new(), - q2:Queue::::new() + q1:Queue::::new(), + q2:Queue::::new() } } pub fn push(&mut self, elem: T) { - //TODO + self.q2.enqueue(elem); + while let Ok(value) = self.q1.dequeue() { + self.q2.enqueue(value); + } + core::mem::swap(&mut self.q1, &mut self.q2); } pub fn pop(&mut self) -> Result { - //TODO - Err("Stack is empty") + self.q1.dequeue().map_err(|_| "Stack is empty") } pub fn is_empty(&self) -> bool { - //TODO - true + self.q1.is_empty() } } diff --git a/exercises/algorithm/algorithm9.rs b/exercises/algorithm/algorithm9.rs index 6c8021a4d..19e433f3b 100644 --- a/exercises/algorithm/algorithm9.rs +++ b/exercises/algorithm/algorithm9.rs @@ -2,8 +2,6 @@ heap This question requires you to implement a binary heap function */ -// I AM NOT DONE - use std::cmp::Ord; use std::default::Default; @@ -37,7 +35,18 @@ where } pub fn add(&mut self, value: T) { - //TODO + self.items.push(value); + self.count += 1; + let mut idx = self.count; + while idx > 1 { + let parent = self.parent_idx(idx); + if (self.comparator)(&self.items[idx], &self.items[parent]) { + self.items.swap(idx, parent); + idx = parent; + } else { + break; + } + } } fn parent_idx(&self, idx: usize) -> usize { @@ -57,8 +66,16 @@ where } fn smallest_child_idx(&self, idx: usize) -> usize { - //TODO - 0 + let left = self.left_child_idx(idx); + let right = self.right_child_idx(idx); + + if right > self.count { + left + } else if (self.comparator)(&self.items[left], &self.items[right]) { + left + } else { + right + } } } @@ -84,8 +101,34 @@ where type Item = T; fn next(&mut self) -> Option { - //TODO - None + if self.count == 0 { + return None; + } + + let result = self.items.swap_remove(1); + self.count -= 1; + + let mut idx = 1; + while self.children_present(idx) { + let child_idx = self.smallest_child_idx(idx); + if (self.comparator)(&self.items[child_idx], &self.items[idx]) { + self.items.swap(idx, child_idx); + idx = child_idx; + } else { + break; + } + } + + if self.count == 0 { + // Ensure placeholder remains when vector shrinks to index 0 only. + if self.items.len() == 0 { + self.items.push(T::default()); + } else if self.items.len() == 1 { + // already has placeholder + } + } + + Some(result) } } diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index 95c0141f4..e2b1ebf4b 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -9,12 +9,10 @@ // 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..79c5c9fec 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -3,12 +3,10 @@ // 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 { + if let Some(x) = option { res += x; } println!("{}", res); diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index 35021f841..1292ccb65 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -4,28 +4,26 @@ // // 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_option: Option<()> = Some(()); + if let Some(value) = my_option { + println!("I love numbers: {:?}", value); } let my_arr = &[ - -1, -2, -3 - -4, -5, -6 + -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); + let mut my_empty_vec = vec![1, 2, 3, 4, 5]; + my_empty_vec.clear(); println!("This Vec is empty, see? {:?}", my_empty_vec); 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..a31f5f6ad 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -7,25 +7,24 @@ // 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) { - // TODO: Implement the function body. - ??? +fn num_sq>(arg: &mut T) { + let value = arg.as_mut(); + let squared = *value * *value; + *value = squared; } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index aba471d92..a6e3ae6ed 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -40,10 +40,38 @@ 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.is_empty() { + return Person::default(); + } + + let mut parts = s.split(','); + let name_part = parts.next().unwrap_or("").trim(); + let age_part = parts.next().map(str::trim); + + // If there are more segments after age, input is invalid. + if parts.next().is_some() { + return Person::default(); + } + + if name_part.is_empty() { + return Person::default(); + } + + let age_str = match age_part { + Some(part) if !part.is_empty() => part, + _ => return Person::default(), + }; + + if let Ok(age) = age_str.parse::() { + Person { + name: name_part.to_string(), + age, + } + } else { + Person::default() + } } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32c..2f8d308b4 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -31,8 +31,6 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE - // Steps: // 1. If the length of the provided string is 0, an error should be returned // 2. Split the given string on the commas present in it @@ -52,6 +50,29 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(ParsePersonError::Empty); + } + + let parts: Vec<&str> = s.split(',').collect(); + + if parts.len() != 2 { + return Err(ParsePersonError::BadLen); + } + + let name = parts[0]; + if name.is_empty() { + return Err(ParsePersonError::NoName); + } + + let age = parts[1] + .parse::() + .map_err(ParsePersonError::ParseInt)?; + + Ok(Person { + name: name.to_string(), + age, + }) } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39e..b911f89b6 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -27,8 +27,6 @@ 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 // integers, an array of three integers, and a slice of integers. @@ -41,6 +39,20 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + fn convert_component(value: i16) -> Result { + if (0..=255).contains(&value) { + Ok(value as u8) + } else { + Err(IntoColorError::IntConversion) + } + } + + let (r, g, b) = tuple; + Ok(Color { + red: convert_component(r)?, + green: convert_component(g)?, + blue: convert_component(b)?, + }) } } @@ -48,6 +60,7 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + Color::try_from((arr[0], arr[1], arr[2])) } } @@ -55,6 +68,10 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + Color::try_from((slice[0], slice[1], slice[2])) } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 414cef3a0..a9f1e4496 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -10,11 +10,9 @@ // 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..de9b7d4d6 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -2,11 +2,12 @@ // // 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..e47522e02 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -3,11 +3,12 @@ // 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..ad3ebba89 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -5,10 +5,11 @@ // 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 { @@ -39,10 +40,12 @@ impl State { } fn process(&mut self, message: Message) { - // TODO: create a match expression to process the different message - // 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) => self.change_color((r, g, b)), + Message::Echo(s) => self.echo(s), + Message::Move(point) => self.move_position(point), + Message::Quit => self.quit(), + } } } diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 13d2724cb..595dc51db 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -9,14 +9,12 @@ // 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..ea093763a 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -19,14 +19,12 @@ // 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..8222ec43d 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -7,11 +7,9 @@ // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -23,6 +21,7 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + Ok(()) } pub fn total_cost(item_quantity: &str) -> Result { diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index e04bff77a..9b963f30c 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -16,8 +14,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { - // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + if value < 0 { + Err(CreationError::Negative) + } else if value == 0 { + Err(CreationError::Zero) + } else { + Ok(PositiveNonzeroInteger(value as u64)) + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 92461a7e0..797a60d45 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -22,14 +22,12 @@ // 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..45ca3cafc 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -9,8 +9,6 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::num::ParseIntError; // This is a custom error type that we will be using in `parse_pos_nonzero()`. @@ -26,12 +24,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: i64 = 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..1f4fa4ac7 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -6,9 +6,7 @@ // 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<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 074cd938c..b0cc651f5 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -6,14 +6,12 @@ // 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..ac71bb12d 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -11,17 +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(); // Two bananas are already given for you :) basket.insert(String::from("banana"), 2); // TODO: Put more fruits in your basket here. + basket.insert(String::from("apple"), 3); + basket.insert(String::from("orange"), 1); basket } diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a59256909..0426523d6 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -14,11 +14,9 @@ // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::collections::HashMap; -#[derive(Hash, PartialEq, Eq)] +#[derive(Hash, PartialEq, Eq, Clone, Copy)] enum Fruit { Apple, Banana, @@ -40,6 +38,17 @@ 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) { + continue; + } + + let amount = match fruit { + Fruit::Banana => 3, + Fruit::Pineapple => 2, + _ => continue, + }; + + basket.insert(fruit, amount); } } diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 08e977c33..378ed3341 100644 --- a/exercises/hashmaps/hashmaps3.rs +++ b/exercises/hashmaps/hashmaps3.rs @@ -14,8 +14,6 @@ // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::collections::HashMap; // A structure to store the goal details of a team. @@ -39,6 +37,19 @@ 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. + let team_1_entry = scores.entry(team_1_name).or_insert(Team { + goals_scored: 0, + goals_conceded: 0, + }); + team_1_entry.goals_scored += team_1_score; + team_1_entry.goals_conceded += team_2_score; + + let team_2_entry = scores.entry(team_2_name).or_insert(Team { + goals_scored: 0, + goals_conceded: 0, + }); + team_2_entry.goals_scored += team_2_score; + team_2_entry.goals_conceded += team_1_score; } scores } diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs index b3f698be3..2a89ae423 100644 --- a/exercises/iterators/iterators1.rs +++ b/exercises/iterators/iterators1.rs @@ -9,17 +9,15 @@ // 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..c376b1947 100644 --- a/exercises/iterators/iterators2.rs +++ b/exercises/iterators/iterators2.rs @@ -6,8 +6,6 @@ // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - // Step 1. // Complete the `capitalize_first` function. // "hello" -> "Hello" @@ -15,7 +13,7 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => first.to_uppercase().collect::() + c.as_str(), } } @@ -24,7 +22,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 +30,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).concat() } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index 29fa23a3e..e7f01aa37 100644 --- a/exercises/iterators/iterators3.rs +++ b/exercises/iterators/iterators3.rs @@ -9,8 +9,6 @@ // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { NotDivisible(NotDivisibleError), @@ -26,23 +24,33 @@ 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); + } + + if a % b != 0 { + return Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b })); + } + + 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)); + division_results.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)); + division_results.collect() } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index 79e1692ba..e7b2deba0 100644 --- a/exercises/iterators/iterators4.rs +++ b/exercises/iterators/iterators4.rs @@ -3,8 +3,6 @@ // 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 // Do not use: @@ -15,6 +13,7 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + (1..=num).product() } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index a062ee4c7..4e5df87c1 100644 --- a/exercises/iterators/iterators5.rs +++ b/exercises/iterators/iterators5.rs @@ -11,8 +11,6 @@ // Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Clone, Copy, PartialEq, Eq)] @@ -35,7 +33,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(|&&state| state == value).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -54,7 +52,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(|map| count_iterator(map, value)).sum() } #[cfg(test)] diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs index 87bde490c..5fe45ae0f 100644 --- a/exercises/lifetimes/lifetimes1.rs +++ b/exercises/lifetimes/lifetimes1.rs @@ -8,9 +8,7 @@ // 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..1009074d2 100644 --- a/exercises/lifetimes/lifetimes2.rs +++ b/exercises/lifetimes/lifetimes2.rs @@ -6,8 +6,6 @@ // 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() { x @@ -18,10 +16,7 @@ fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { fn main() { let string1 = String::from("long string is long"); - let result; - { - let string2 = String::from("xyz"); - result = longest(string1.as_str(), string2.as_str()); - } + let string2 = String::from("xyz"); + let result = longest(string1.as_str(), string2.as_str()); println!("The longest string is '{}'", result); } diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs index 9c59f9c02..aede10de3 100644 --- a/exercises/lifetimes/lifetimes3.rs +++ b/exercises/lifetimes/lifetimes3.rs @@ -5,11 +5,9 @@ // 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..9d0edee3c 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - macro_rules! my_macro { () => { println!("Check out my macro!"); @@ -12,5 +10,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..a87be198d 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -3,14 +3,12 @@ // 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..b5be9c391 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -5,8 +5,7 @@ // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - +#[macro_use] mod macros { macro_rules! my_macro { () => { diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 71b45a095..45d802359 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -3,13 +3,11 @@ // 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..a26f5c45d 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -3,15 +3,13 @@ // 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! fn get_secret_recipe() -> String { 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..f5bd7cc08 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -7,12 +7,10 @@ // 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..c51c1c7b0 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,10 +8,7 @@ // 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..65eb1a505 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -3,8 +3,6 @@ // 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 // all, so there'll be no more left :( @@ -13,7 +11,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! - ??? + if time_of_day > 23 { + None + } else if time_of_day < 22 { + Some(5) + } else { + Some(0) + } } #[cfg(test)] @@ -34,6 +38,6 @@ mod tests { // TODO: Fix this test. How do you get at the value contained in the // Option? let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); + assert_eq!(icecreams.unwrap(), 5); } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4d998e7d0..cbc1ad2da 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint options2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] @@ -12,8 +10,7 @@ mod tests { let target = "rustlings"; 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); } } @@ -29,10 +26,7 @@ mod tests { let mut cursor = range; - // 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() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, cursor); cursor -= 1; } diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 23c15eab8..bca3cff56 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint options3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - struct Point { x: i32, y: i32, @@ -14,7 +12,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..4759eb6fa 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -20,8 +20,6 @@ // // No hints this time! -// I AM NOT DONE - pub enum Command { Uppercase, Trim, @@ -32,11 +30,21 @@ mod my_module { use super::Command; // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { - // TODO: Complete the output declaration! - let mut output: ??? = vec![]; - for (string, command) in input.iter() { - // TODO: Complete the function body. You can do it! + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output: Vec = Vec::new(); + for (string, command) in input.into_iter() { + let transformed = match command { + Command::Uppercase => string.to_uppercase(), + Command::Trim => string.trim().to_string(), + Command::Append(times) => { + let mut result = string; + for _ in 0..times { + result.push_str("bar"); + } + result + } + }; + output.push(transformed); } output } @@ -45,7 +53,7 @@ mod my_module { #[cfg(test)] mod tests { // TODO: What do we need to import to have `transformer` in scope? - use ???; + use super::my_module::transformer; use super::Command; #[test] diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 3b01d3132..cf6efa5c0 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -16,15 +16,15 @@ // // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +use std::fmt::Display; -pub struct ReportCard { - pub grade: f32, +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) @@ -52,7 +52,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+".to_string(), 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..418616f79 100644 --- a/exercises/smart_pointers/arc1.rs +++ b/exercises/smart_pointers/arc1.rs @@ -21,19 +21,17 @@ // // 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; use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(numbers); let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = Arc::clone(&shared_numbers); 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..85256900b 100644 --- a/exercises/smart_pointers/box1.rs +++ b/exercises/smart_pointers/box1.rs @@ -18,11 +18,9 @@ // // 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 +33,11 @@ fn main() { } pub fn create_empty_list() -> List { - todo!() + List::Nil } pub fn create_non_empty_list() -> List { - todo!() + List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))) } #[cfg(test)] diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs index 7ca916866..8938bcc27 100644 --- a/exercises/smart_pointers/cow1.rs +++ b/exercises/smart_pointers/cow1.rs @@ -12,8 +12,6 @@ // // Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::borrow::Cow; fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { @@ -48,7 +46,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"), } } @@ -60,7 +59,8 @@ mod tests { let slice = vec![0, 1, 2]; let mut input = Cow::from(slice); match abs_all(&mut input) { - // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -72,7 +72,8 @@ mod tests { let slice = vec![-1, 0, 1]; 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..2ce1c54c5 100644 --- a/exercises/smart_pointers/rc1.rs +++ b/exercises/smart_pointers/rc1.rs @@ -10,8 +10,6 @@ // // Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::rc::Rc; #[derive(Debug)] @@ -60,17 +58,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 +90,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..c32129147 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -5,13 +5,11 @@ // Execute `rustlings hint strings1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - fn main() { let answer = current_favorite_color(); println!("My current favorite color is {}", answer); } fn current_favorite_color() -> String { - "blue" + String::from("blue") } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 4d95d16a1..ca16ea3d0 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -5,11 +5,9 @@ // 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..bb9cdc250 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -3,21 +3,19 @@ // 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! - ??? + input.trim().to_string() } fn compose_me(input: &str) -> String { // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? + format!("{} world!", input) } 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..9c2a0c720 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -7,8 +7,6 @@ // // No hints this time! -// I AM NOT DONE - fn string_slice(arg: &str) { println!("{}", arg); } @@ -17,14 +15,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..9cae9caca 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -5,13 +5,13 @@ // Execute `rustlings hint structs1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - struct ColorClassicStruct { - // TODO: Something goes here + red: i32, + green: i32, + blue: i32, } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct(i32, i32, i32); #[derive(Debug)] struct UnitLikeStruct; @@ -22,8 +22,11 @@ mod tests { #[test] 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); @@ -32,8 +35,7 @@ mod tests { #[test] 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); @@ -42,8 +44,7 @@ mod tests { #[test] 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..142741589 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -5,9 +5,7 @@ // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - -#[derive(Debug)] +#[derive(Debug, Clone)] struct Order { name: String, year: u32, @@ -38,7 +36,11 @@ mod tests { fn your_order() { 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.clone() + }; 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..266a32f08 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -7,8 +7,6 @@ // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(Debug)] struct Package { sender_country: String, @@ -29,12 +27,12 @@ impl Package { } } - fn is_international(&self) -> ??? { - // Something goes here... + fn is_international(&self) -> bool { + self.sender_country != self.recipient_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { - // Something goes here... + fn get_fees(&self, cents_per_gram: i32) -> i32 { + 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..92203081a 100644 --- a/exercises/tests/build.rs +++ b/exercises/tests/build.rs @@ -10,15 +10,10 @@ fn main() { .duration_since(std::time::UNIX_EPOCH) .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 - ); - println!("cargo:{}", your_command); + println!("cargo:rustc-env=TEST_FOO={}", timestamp); // 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); + println!("cargo:rustc-cfg=feature=\"pass\""); } diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 810277ac3..eab3ba7a2 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -10,12 +10,10 @@ // 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..b9624c13f 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -6,12 +6,10 @@ // 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!(2 + 2, 4); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 4013e3841..bbd3834f5 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -7,8 +7,6 @@ // 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 +17,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(4)); } #[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..032a179ef 100644 --- a/exercises/tests/tests4.rs +++ b/exercises/tests/tests4.rs @@ -5,8 +5,6 @@ // Execute `rustlings hint tests4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - struct Rectangle { width: i32, height: i32 @@ -30,17 +28,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(expected = "cannot be negative")] 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(expected = "cannot be negative")] 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..3e06ab438 100644 --- a/exercises/tests/tests5.rs +++ b/exercises/tests/tests5.rs @@ -22,8 +22,6 @@ // Execute `rustlings hint tests5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - /// # Safety /// /// The `address` must contain a mutable reference to a valid `u32` value. @@ -32,7 +30,11 @@ unsafe fn modify_by_address(address: usize) { // code's behavior and the contract of this function. You may use the // comment of the test below as your format reference. unsafe { - todo!("Your code goes here") + // SAFETY: `address` is documented to come from a valid mutable + // pointer to a `u32`, so casting it back to `*mut u32` and writing to + // it keeps all invariants intact. + let ptr = address as *mut u32; + *ptr = 0xAABBCCDD; } } diff --git a/exercises/tests/tests6.rs b/exercises/tests/tests6.rs index 4c913779d..4d7f88c8d 100644 --- a/exercises/tests/tests6.rs +++ b/exercises/tests/tests6.rs @@ -7,8 +7,6 @@ // Execute `rustlings hint tests6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - struct Foo { a: u128, b: Option, @@ -20,14 +18,14 @@ 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("hello".to_owned()); + ret } #[cfg(test)] mod tests { use super::*; - use std::time::Instant; #[test] fn test_success() { diff --git a/exercises/tests/tests7.rs b/exercises/tests/tests7.rs index 66b37b72d..79883a9b6 100644 --- a/exercises/tests/tests7.rs +++ b/exercises/tests/tests7.rs @@ -34,8 +34,6 @@ // Execute `rustlings hint tests7` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - fn main() {} #[cfg(test)] diff --git a/exercises/tests/tests8.rs b/exercises/tests/tests8.rs index ce7e35d8d..dfa37d7ac 100644 --- a/exercises/tests/tests8.rs +++ b/exercises/tests/tests8.rs @@ -7,8 +7,6 @@ // Execute `rustlings hint tests8` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - fn main() {} #[cfg(test)] diff --git a/exercises/tests/tests9.rs b/exercises/tests/tests9.rs index ea2a8ec02..951aaa26b 100644 --- a/exercises/tests/tests9.rs +++ b/exercises/tests/tests9.rs @@ -27,15 +27,15 @@ // // 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..a4c898547 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -8,8 +8,6 @@ // 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}; @@ -26,7 +24,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().unwrap()); } if results.len() != 10 { diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d6..0d9ccb769 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,9 +7,7 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; @@ -18,14 +16,15 @@ struct JobStatus { } 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 status = status_shared.lock().unwrap(); + status.jobs_completed += 1; }); handles.push(handle); } @@ -34,6 +33,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 status_guard = status.lock().unwrap(); + println!("jobs completed {}", status_guard.jobs_completed); } } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index db7d41ba6..16e1d3008 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -3,8 +3,6 @@ // 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; use std::thread; @@ -30,11 +28,12 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc = Arc::new(q); let qc1 = Arc::clone(&qc); let qc2 = Arc::clone(&qc); + let tx1 = 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)); } }); diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 37dfcbfe8..918ef732a 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -7,14 +7,16 @@ // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { // TODO: Implement `AppendBar` for type `String`. + fn append_bar(mut self) -> Self { + self.push_str("Bar"); + self + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 3e35f8e11..045dade4d 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -8,13 +8,17 @@ // // 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(mut self) -> Self { + self.push(String::from("Bar")); + self + } +} #[cfg(test)] mod tests { diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 4e2b06b0e..7b7587478 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -8,10 +8,10 @@ // 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..b11715d57 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -7,8 +7,6 @@ // 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 { "some information".to_string() @@ -23,7 +21,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: T, software_two: U) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index df1838054..327b109e2 100644 --- a/exercises/traits/traits5.rs +++ b/exercises/traits/traits5.rs @@ -7,8 +7,6 @@ // 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 { true @@ -30,7 +28,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: T) -> bool { item.some_function() && item.other_function() } diff --git a/src/exercise.rs b/src/exercise.rs index 6c4901dfa..cbc2fe8af 100644 --- a/src/exercise.rs +++ b/src/exercise.rs @@ -110,7 +110,7 @@ impl Drop for FileHandle { } impl Exercise { - pub fn compile(&self) -> Result { + pub fn compile(&self) -> Result, ExerciseOutput> { let cmd = match self.mode { Mode::Compile => Command::new("rustc") .args(&[self.path.to_str().unwrap(), "-o", &temp_file()]) From ed49fdf3f292238b88acdb6a781d71e90b909a0f Mon Sep 17 00:00:00 2001 From: ylwqf Date: Sat, 27 Sep 2025 15:50:07 +0800 Subject: [PATCH 2/2] 1.test --- 1.test | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 1.test diff --git a/1.test b/1.test new file mode 100644 index 000000000..e69de29bb