diff --git a/..gitignore.un~ b/..gitignore.un~ new file mode 100644 index 000000000..fd7e113d9 Binary files /dev/null and b/..gitignore.un~ differ diff --git a/.gitignore b/.gitignore index 88bf2b6c7..3a99923ea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +*.rs~ +*.rs.un~ *.swp target/ **/*.rs.bk diff --git a/.gitignore~ b/.gitignore~ new file mode 100644 index 000000000..fd3c60ead --- /dev/null +++ b/.gitignore~ @@ -0,0 +1,18 @@ +*.rs~ +*.swp +target/ +**/*.rs.bk +.DS_Store +*.pdb +exercises/clippy/Cargo.toml +exercises/clippy/Cargo.lock +rust-project.json +.idea +.vscode/* +!.vscode/extensions.json +*.iml +*.o +public/ + +# Local Netlify folder +.netlify diff --git a/exercises/.quiz2.rs.un~ b/exercises/.quiz2.rs.un~ new file mode 100644 index 000000000..54e629a88 Binary files /dev/null and b/exercises/.quiz2.rs.un~ differ diff --git a/exercises/.quiz3.rs.un~ b/exercises/.quiz3.rs.un~ new file mode 100644 index 000000000..0a073a025 Binary files /dev/null and b/exercises/.quiz3.rs.un~ differ diff --git a/exercises/algorithm/.algorithm1.rs.un~ b/exercises/algorithm/.algorithm1.rs.un~ new file mode 100644 index 000000000..6c5e093f4 Binary files /dev/null and b/exercises/algorithm/.algorithm1.rs.un~ differ diff --git a/exercises/algorithm/.algorithm10.rs.un~ b/exercises/algorithm/.algorithm10.rs.un~ new file mode 100644 index 000000000..daee6b4da Binary files /dev/null and b/exercises/algorithm/.algorithm10.rs.un~ differ diff --git a/exercises/algorithm/.algorithm2.rs.un~ b/exercises/algorithm/.algorithm2.rs.un~ new file mode 100644 index 000000000..6685406fb Binary files /dev/null and b/exercises/algorithm/.algorithm2.rs.un~ differ diff --git a/exercises/algorithm/.algorithm3.rs.un~ b/exercises/algorithm/.algorithm3.rs.un~ new file mode 100644 index 000000000..76e7f6f28 Binary files /dev/null and b/exercises/algorithm/.algorithm3.rs.un~ differ diff --git a/exercises/algorithm/.algorithm4.rs.un~ b/exercises/algorithm/.algorithm4.rs.un~ new file mode 100644 index 000000000..9840d3bda Binary files /dev/null and b/exercises/algorithm/.algorithm4.rs.un~ differ diff --git a/exercises/algorithm/.algorithm5.rs.un~ b/exercises/algorithm/.algorithm5.rs.un~ new file mode 100644 index 000000000..2d679dd0d Binary files /dev/null and b/exercises/algorithm/.algorithm5.rs.un~ differ diff --git a/exercises/algorithm/.algorithm6.rs.un~ b/exercises/algorithm/.algorithm6.rs.un~ new file mode 100644 index 000000000..9cfc5fa70 Binary files /dev/null and b/exercises/algorithm/.algorithm6.rs.un~ differ diff --git a/exercises/algorithm/.algorithm7.rs.un~ b/exercises/algorithm/.algorithm7.rs.un~ new file mode 100644 index 000000000..eb1ff9af0 Binary files /dev/null and b/exercises/algorithm/.algorithm7.rs.un~ differ diff --git a/exercises/algorithm/.algorithm8.rs.un~ b/exercises/algorithm/.algorithm8.rs.un~ new file mode 100644 index 000000000..7ac9d9b6a Binary files /dev/null and b/exercises/algorithm/.algorithm8.rs.un~ differ diff --git a/exercises/algorithm/.algorithm9.rs.un~ b/exercises/algorithm/.algorithm9.rs.un~ new file mode 100644 index 000000000..a11bf023c Binary files /dev/null and b/exercises/algorithm/.algorithm9.rs.un~ differ diff --git a/exercises/algorithm/algorithm1.rs b/exercises/algorithm/algorithm1.rs index f7a99bf02..4e61f54f9 100644 --- a/exercises/algorithm/algorithm1.rs +++ b/exercises/algorithm/algorithm1.rs @@ -2,7 +2,6 @@ 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; @@ -69,17 +68,48 @@ impl LinkedList { }, } } - pub fn merge(list_a:LinkedList,list_b:LinkedList) -> Self - { - //TODO - Self { - length: 0, - start: None, - end: None, +} + +impl LinkedList { + pub fn merge(list_a: LinkedList, list_b: LinkedList) -> Self { + let mut merged_list = LinkedList::::new(); + + let mut curr_a = list_a.start; + let mut curr_b = list_b.start; + + while curr_a.is_some() && curr_b.is_some() { + let val_a = unsafe { curr_a.as_ref().unwrap().as_ref().val.clone() }; + let val_b = unsafe { curr_b.as_ref().unwrap().as_ref().val.clone() }; + + if val_a <= val_b { + merged_list.add(val_a); + curr_a = unsafe { curr_a.unwrap().as_ref().next }; + } else { + merged_list.add(val_b); + curr_b = unsafe { curr_b.unwrap().as_ref().next }; + } } - } + + // Append remaining elements from list_a if any + while let Some(node) = curr_a { + let val = unsafe { node.as_ref().val.clone() }; + merged_list.add(val); + curr_a = unsafe { node.as_ref().next }; + } + + // Append remaining elements from list_b if any + while let Some(node) = curr_b { + let val = unsafe { node.as_ref().val.clone() }; + merged_list.add(val); + curr_b = unsafe { node.as_ref().next }; + } + + merged_list + } } + + impl Display for LinkedList where T: Display, @@ -170,4 +200,4 @@ mod tests { assert_eq!(target_vec[i],*list_c.get(i as i32).unwrap()); } } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm1.rs~ b/exercises/algorithm/algorithm1.rs~ new file mode 100644 index 000000000..4e61f54f9 --- /dev/null +++ b/exercises/algorithm/algorithm1.rs~ @@ -0,0 +1,203 @@ +/* + single linked list merge + This problem requires you to merge two ordered singly linked lists into one ordered singly linked list +*/ + +use std::fmt::{self, Display, Formatter}; +use std::ptr::NonNull; +use std::vec::*; + +#[derive(Debug)] +struct Node { + val: T, + next: Option>>, +} + +impl Node { + fn new(t: T) -> Node { + Node { + val: t, + next: None, + } + } +} +#[derive(Debug)] +struct LinkedList { + length: u32, + start: Option>>, + end: Option>>, +} + +impl Default for LinkedList { + fn default() -> Self { + Self::new() + } +} + +impl LinkedList { + pub fn new() -> Self { + Self { + length: 0, + start: None, + end: None, + } + } + + pub fn add(&mut self, obj: T) { + let mut node = Box::new(Node::new(obj)); + node.next = None; + let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) }); + match self.end { + None => self.start = node_ptr, + Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr }, + } + self.end = node_ptr; + self.length += 1; + } + + pub fn get(&mut self, index: i32) -> Option<&T> { + self.get_ith_node(self.start, index) + } + + fn get_ith_node(&mut self, node: Option>>, index: i32) -> Option<&T> { + match node { + None => None, + Some(next_ptr) => match index { + 0 => Some(unsafe { &(*next_ptr.as_ptr()).val }), + _ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1), + }, + } + } +} + +impl LinkedList { + pub fn merge(list_a: LinkedList, list_b: LinkedList) -> Self { + let mut merged_list = LinkedList::::new(); + + let mut curr_a = list_a.start; + let mut curr_b = list_b.start; + + while curr_a.is_some() && curr_b.is_some() { + let val_a = unsafe { curr_a.as_ref().unwrap().as_ref().val.clone() }; + let val_b = unsafe { curr_b.as_ref().unwrap().as_ref().val.clone() }; + + if val_a <= val_b { + merged_list.add(val_a); + curr_a = unsafe { curr_a.unwrap().as_ref().next }; + } else { + merged_list.add(val_b); + curr_b = unsafe { curr_b.unwrap().as_ref().next }; + } + } + + // Append remaining elements from list_a if any + while let Some(node) = curr_a { + let val = unsafe { node.as_ref().val.clone() }; + merged_list.add(val); + curr_a = unsafe { node.as_ref().next }; + } + + // Append remaining elements from list_b if any + while let Some(node) = curr_b { + let val = unsafe { node.as_ref().val.clone() }; + merged_list.add(val); + curr_b = unsafe { node.as_ref().next }; + } + + merged_list + } +} + + + +impl Display for LinkedList +where + T: Display, +{ + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self.start { + Some(node) => write!(f, "{}", unsafe { node.as_ref() }), + None => Ok(()), + } + } +} + +impl Display for Node +where + T: Display, +{ + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self.next { + Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }), + None => write!(f, "{}", self.val), + } + } +} + +#[cfg(test)] +mod tests { + use super::LinkedList; + + #[test] + fn create_numeric_list() { + let mut list = LinkedList::::new(); + list.add(1); + list.add(2); + list.add(3); + println!("Linked List is {}", list); + assert_eq!(3, list.length); + } + + #[test] + fn create_string_list() { + let mut list_str = LinkedList::::new(); + list_str.add("A".to_string()); + list_str.add("B".to_string()); + list_str.add("C".to_string()); + println!("Linked List is {}", list_str); + assert_eq!(3, list_str.length); + } + + #[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()); + } + } +} diff --git a/exercises/algorithm/algorithm10.rs b/exercises/algorithm/algorithm10.rs index a2ad731d0..934e21146 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,22 @@ impl Graph for UndirectedGraph { &self.adjacency_table } fn add_edge(&mut self, edge: (&str, &str, i32)) { - //TODO + let (from_node, to_node, weight) = edge; + + // Add both nodes if they don't exist + self.add_node(from_node); + self.add_node(to_node); + + // Add edge to both nodes' adjacency lists + self.adjacency_table + .entry(from_node.to_string()) + .and_modify(|neighbors| neighbors.push((to_node.to_string(), weight))) + .or_insert_with(|| vec![(to_node.to_string(), weight)]); + + self.adjacency_table + .entry(to_node.to_string()) + .and_modify(|neighbors| neighbors.push((from_node.to_string(), weight))) + .or_insert_with(|| vec![(from_node.to_string(), weight)]); } } pub trait Graph { @@ -81,4 +94,4 @@ mod test_undirected_graph { assert_eq!(graph.edges().contains(edge), true); } } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm10.rs~ b/exercises/algorithm/algorithm10.rs~ new file mode 100644 index 000000000..0f32fe9ac --- /dev/null +++ b/exercises/algorithm/algorithm10.rs~ @@ -0,0 +1,82 @@ +/* + graph + This problem requires you to implement a basic graph functio +*/ +use std::collections::{HashMap, HashSet}; +use std::fmt; +#[derive(Debug, Clone)] +pub struct NodeNotInGraph; +impl fmt::Display for NodeNotInGraph { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "accessing a node that is not in the graph") + } +} +pub struct UndirectedGraph { + adjacency_table: HashMap>, +} +impl Graph for UndirectedGraph { + fn new() -> UndirectedGraph { + UndirectedGraph { + adjacency_table: HashMap::new(), + } + } + fn adjacency_table_mutable(&mut self) -> &mut HashMap> { + &mut self.adjacency_table + } + fn adjacency_table(&self) -> &HashMap> { + &self.adjacency_table + } + fn add_edge(&mut self, edge: (&str, &str, i32)) { + //TODO + } +} +pub trait Graph { + fn new() -> Self; + fn adjacency_table_mutable(&mut self) -> &mut HashMap>; + fn adjacency_table(&self) -> &HashMap>; + fn add_node(&mut self, node: &str) -> bool { + //TODO + true + } + fn add_edge(&mut self, edge: (&str, &str, i32)) { + //TODO + } + fn contains(&self, node: &str) -> bool { + self.adjacency_table().get(node).is_some() + } + fn nodes(&self) -> HashSet<&String> { + self.adjacency_table().keys().collect() + } + fn edges(&self) -> Vec<(&String, &String, i32)> { + let mut edges = Vec::new(); + for (from_node, from_node_neighbours) in self.adjacency_table() { + for (to_node, weight) in from_node_neighbours { + edges.push((from_node, to_node, *weight)); + } + } + edges + } +} +#[cfg(test)] +mod test_undirected_graph { + use super::Graph; + use super::UndirectedGraph; + #[test] + fn test_add_edge() { + let mut graph = UndirectedGraph::new(); + graph.add_edge(("a", "b", 5)); + graph.add_edge(("b", "c", 10)); + graph.add_edge(("c", "a", 7)); + let expected_edges = [ + (&String::from("a"), &String::from("b"), 5), + (&String::from("b"), &String::from("a"), 5), + (&String::from("c"), &String::from("a"), 7), + (&String::from("a"), &String::from("c"), 7), + (&String::from("b"), &String::from("c"), 10), + (&String::from("c"), &String::from("b"), 10), + ]; + for edge in expected_edges.iter() { + assert_eq!(graph.edges().contains(edge), true); + } + } +} diff --git a/exercises/algorithm/algorithm2.rs b/exercises/algorithm/algorithm2.rs index 08720ff44..a391ccd23 100644 --- a/exercises/algorithm/algorithm2.rs +++ b/exercises/algorithm/algorithm2.rs @@ -2,8 +2,6 @@ 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::*; @@ -73,7 +71,24 @@ impl LinkedList { } } pub fn reverse(&mut self){ - // TODO + let mut current = self.start; + let mut new_end = self.start; + + while let Some(mut curr_ptr) = current { + unsafe { + // Swap next and prev pointers of the current node + let next = (*curr_ptr.as_ptr()).next; + (*curr_ptr.as_mut()).next = (*curr_ptr.as_ptr()).prev; + (*curr_ptr.as_mut()).prev = next; + } + + new_end = current; // Update new_end to current node + current = unsafe { (*curr_ptr.as_ptr()).prev }; // Move current to the previous node + } + + // Swap start and end pointers + self.end = self.start; + self.start = new_end; } } @@ -156,4 +171,4 @@ mod tests { assert_eq!(reverse_vec[i],*list.get(i as i32).unwrap()); } } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm2.rs~ b/exercises/algorithm/algorithm2.rs~ new file mode 100644 index 000000000..a391ccd23 --- /dev/null +++ b/exercises/algorithm/algorithm2.rs~ @@ -0,0 +1,174 @@ +/* + double linked list reverse + This problem requires you to reverse a doubly linked list +*/ +use std::fmt::{self, Display, Formatter}; +use std::ptr::NonNull; +use std::vec::*; + +#[derive(Debug)] +struct Node { + val: T, + next: Option>>, + prev: Option>>, +} + +impl Node { + fn new(t: T) -> Node { + Node { + val: t, + prev: None, + next: None, + } + } +} +#[derive(Debug)] +struct LinkedList { + length: u32, + start: Option>>, + end: Option>>, +} + +impl Default for LinkedList { + fn default() -> Self { + Self::new() + } +} + +impl LinkedList { + pub fn new() -> Self { + Self { + length: 0, + start: None, + end: None, + } + } + + pub fn add(&mut self, obj: T) { + let mut node = Box::new(Node::new(obj)); + node.next = None; + node.prev = self.end; + let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) }); + match self.end { + None => self.start = node_ptr, + Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr }, + } + self.end = node_ptr; + self.length += 1; + } + + pub fn get(&mut self, index: i32) -> Option<&T> { + self.get_ith_node(self.start, index) + } + + fn get_ith_node(&mut self, node: Option>>, index: i32) -> Option<&T> { + match node { + None => None, + Some(next_ptr) => match index { + 0 => Some(unsafe { &(*next_ptr.as_ptr()).val }), + _ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1), + }, + } + } + pub fn reverse(&mut self){ + let mut current = self.start; + let mut new_end = self.start; + + while let Some(mut curr_ptr) = current { + unsafe { + // Swap next and prev pointers of the current node + let next = (*curr_ptr.as_ptr()).next; + (*curr_ptr.as_mut()).next = (*curr_ptr.as_ptr()).prev; + (*curr_ptr.as_mut()).prev = next; + } + + new_end = current; // Update new_end to current node + current = unsafe { (*curr_ptr.as_ptr()).prev }; // Move current to the previous node + } + + // Swap start and end pointers + self.end = self.start; + self.start = new_end; + } +} + +impl Display for LinkedList +where + T: Display, +{ + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self.start { + Some(node) => write!(f, "{}", unsafe { node.as_ref() }), + None => Ok(()), + } + } +} + +impl Display for Node +where + T: Display, +{ + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self.next { + Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }), + None => write!(f, "{}", self.val), + } + } +} + +#[cfg(test)] +mod tests { + use super::LinkedList; + + #[test] + fn create_numeric_list() { + let mut list = LinkedList::::new(); + list.add(1); + list.add(2); + list.add(3); + println!("Linked List is {}", list); + assert_eq!(3, list.length); + } + + #[test] + fn create_string_list() { + let mut list_str = LinkedList::::new(); + list_str.add("A".to_string()); + list_str.add("B".to_string()); + list_str.add("C".to_string()); + println!("Linked List is {}", list_str); + assert_eq!(3, list_str.length); + } + + #[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()); + } + } + + #[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..502a0f6a7 100644 --- a/exercises/algorithm/algorithm3.rs +++ b/exercises/algorithm/algorithm3.rs @@ -3,10 +3,17 @@ 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 0..len { + for j in 0..len - i - 1 { + if array[j] > array[j + 1] { + array.swap(j, j + 1); + } + } + } } #[cfg(test)] mod tests { @@ -30,4 +37,4 @@ mod tests { 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/algorithm3.rs~ b/exercises/algorithm/algorithm3.rs~ new file mode 100644 index 000000000..502a0f6a7 --- /dev/null +++ b/exercises/algorithm/algorithm3.rs~ @@ -0,0 +1,40 @@ +/* + sort + This problem requires you to implement a sorting algorithm + you can use bubble sorting, insertion sorting, heap sorting, etc. +*/ + +fn sort(array: &mut [T]){ + let len = array.len(); + + for i in 0..len { + for j in 0..len - i - 1 { + if array[j] > array[j + 1] { + array.swap(j, j + 1); + } + } + } +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sort_1() { + let mut vec = vec![37, 73, 57, 75, 91, 19, 46, 64]; + sort(&mut vec); + assert_eq!(vec, vec![19, 37, 46, 57, 64, 73, 75, 91]); + } + #[test] + fn test_sort_2() { + let mut vec = vec![1]; + sort(&mut vec); + assert_eq!(vec, vec![1]); + } + #[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]); + } +} diff --git a/exercises/algorithm/algorithm4.rs b/exercises/algorithm/algorithm4.rs index 271b772c5..06d313c70 100644 --- a/exercises/algorithm/algorithm4.rs +++ b/exercises/algorithm/algorithm4.rs @@ -2,12 +2,9 @@ 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 @@ -41,7 +38,7 @@ where impl BinarySearchTree where - T: Ord, + T: Ord + Debug, { fn new() -> Self { @@ -50,23 +47,72 @@ where // Insert a value into the BST fn insert(&mut self, value: T) { - //TODO + if let Some(ref mut root) = self.root { + root.insert(value); + } else { + self.root = Some(Box::new(TreeNode::new(value))); + } } // Search for a value in the BST fn search(&self, value: T) -> bool { - //TODO - true + if let Some(ref root) = self.root { + root.search(value) + } else { + false + } } } impl TreeNode where - T: Ord, + T: Ord + Debug, { // Insert a node into the tree fn insert(&mut self, value: T) { - //TODO + match value.cmp(&self.value) { + Ordering::Less => { + if let Some(ref mut left) = self.left { + left.insert(value); + } else { + self.left = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Greater => { + if let Some(ref mut right) = self.right { + right.insert(value); + } else { + self.right = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Equal => { + // Handle duplicate insertion if needed + // For this example, we won't allow duplicates + // So, we'll just ignore the insertion of duplicate values + println!("Value {:?} already exists in the tree", value); + } + } + } + + // Search for a value in the tree + fn search(&self, value: T) -> bool { + match value.cmp(&self.value) { + Ordering::Less => { + if let Some(ref left) = self.left { + left.search(value) + } else { + false + } + } + Ordering::Greater => { + if let Some(ref right) = self.right { + right.search(value) + } else { + false + } + } + Ordering::Equal => true, + } } } diff --git a/exercises/algorithm/algorithm4.rs~ b/exercises/algorithm/algorithm4.rs~ new file mode 100644 index 000000000..06d313c70 --- /dev/null +++ b/exercises/algorithm/algorithm4.rs~ @@ -0,0 +1,172 @@ +/* + binary_search tree + This problem requires you to implement a basic interface for a binary tree +*/ +use std::cmp::Ordering; +use std::fmt::Debug; + +#[derive(Debug)] +struct TreeNode +where + T: Ord, +{ + value: T, + left: Option>>, + right: Option>>, +} + +#[derive(Debug)] +struct BinarySearchTree +where + T: Ord, +{ + root: Option>>, +} + +impl TreeNode +where + T: Ord, +{ + fn new(value: T) -> Self { + TreeNode { + value, + left: None, + right: None, + } + } +} + +impl BinarySearchTree +where + T: Ord + Debug, +{ + + fn new() -> Self { + BinarySearchTree { root: None } + } + + // Insert a value into the BST + fn insert(&mut self, value: T) { + if let Some(ref mut root) = self.root { + root.insert(value); + } else { + self.root = Some(Box::new(TreeNode::new(value))); + } + } + + // Search for a value in the BST + fn search(&self, value: T) -> bool { + if let Some(ref root) = self.root { + root.search(value) + } else { + false + } + } +} + +impl TreeNode +where + T: Ord + Debug, +{ + // Insert a node into the tree + fn insert(&mut self, value: T) { + match value.cmp(&self.value) { + Ordering::Less => { + if let Some(ref mut left) = self.left { + left.insert(value); + } else { + self.left = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Greater => { + if let Some(ref mut right) = self.right { + right.insert(value); + } else { + self.right = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Equal => { + // Handle duplicate insertion if needed + // For this example, we won't allow duplicates + // So, we'll just ignore the insertion of duplicate values + println!("Value {:?} already exists in the tree", value); + } + } + } + + // Search for a value in the tree + fn search(&self, value: T) -> bool { + match value.cmp(&self.value) { + Ordering::Less => { + if let Some(ref left) = self.left { + left.search(value) + } else { + false + } + } + Ordering::Greater => { + if let Some(ref right) = self.right { + right.search(value) + } else { + false + } + } + Ordering::Equal => true, + } + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + 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); + } + + #[test] + 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..0520e70eb 100644 --- a/exercises/algorithm/algorithm5.rs +++ b/exercises/algorithm/algorithm5.rs @@ -2,8 +2,6 @@ bfs This problem requires you to implement a basic BFS algorithm */ - -//I AM NOT DONE use std::collections::VecDeque; // Define a graph @@ -27,10 +25,25 @@ impl Graph { // Perform a breadth-first search on the graph, return the order of visited nodes fn bfs_with_return(&self, start: usize) -> Vec { - - //TODO + let mut visited = vec![false; self.adj.len()]; // Mark all vertices as not visited + let mut visit_order = vec![]; // Store the order of visited nodes + let mut queue = VecDeque::new(); // Queue to store nodes to visit + + visited[start] = true; // Mark the start node as visited + queue.push_back(start); // Enqueue the start node + + while let Some(node) = queue.pop_front() { + visit_order.push(node); // Add the node to the visit order + + // Visit all neighbors of the current node + for &neighbor in &self.adj[node] { + if !visited[neighbor] { + visited[neighbor] = true; // Mark the neighbor as visited + queue.push_back(neighbor); // Enqueue the neighbor + } + } + } - let mut visit_order = vec![]; visit_order } } diff --git a/exercises/algorithm/algorithm5.rs~ b/exercises/algorithm/algorithm5.rs~ new file mode 100644 index 000000000..0520e70eb --- /dev/null +++ b/exercises/algorithm/algorithm5.rs~ @@ -0,0 +1,100 @@ +/* + bfs + This problem requires you to implement a basic BFS algorithm +*/ +use std::collections::VecDeque; + +// Define a graph +struct Graph { + adj: Vec>, +} + +impl Graph { + // Create a new graph with n vertices + fn new(n: usize) -> Self { + Graph { + adj: vec![vec![]; n], + } + } + + // 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); + } + + // 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()]; // Mark all vertices as not visited + let mut visit_order = vec![]; // Store the order of visited nodes + let mut queue = VecDeque::new(); // Queue to store nodes to visit + + visited[start] = true; // Mark the start node as visited + queue.push_back(start); // Enqueue the start node + + while let Some(node) = queue.pop_front() { + visit_order.push(node); // Add the node to the visit order + + // Visit all neighbors of the current node + for &neighbor in &self.adj[node] { + if !visited[neighbor] { + visited[neighbor] = true; // Mark the neighbor as visited + queue.push_back(neighbor); // Enqueue the neighbor + } + } + } + + visit_order + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_bfs_all_nodes_visited() { + let mut graph = Graph::new(5); + graph.add_edge(0, 1); + graph.add_edge(0, 4); + graph.add_edge(1, 2); + graph.add_edge(1, 3); + graph.add_edge(1, 4); + graph.add_edge(2, 3); + graph.add_edge(3, 4); + + let visited_order = graph.bfs_with_return(0); + assert_eq!(visited_order, vec![0, 1, 4, 2, 3]); + } + + #[test] + fn test_bfs_different_start() { + let mut graph = Graph::new(3); + graph.add_edge(0, 1); + graph.add_edge(1, 2); + + let visited_order = graph.bfs_with_return(2); + assert_eq!(visited_order, vec![2, 1, 0]); + } + + #[test] + fn test_bfs_with_cycle() { + let mut graph = Graph::new(3); + graph.add_edge(0, 1); + graph.add_edge(1, 2); + graph.add_edge(2, 0); + + let visited_order = graph.bfs_with_return(0); + assert_eq!(visited_order, vec![0, 1, 2]); + } + + #[test] + fn test_bfs_single_node() { + let mut graph = Graph::new(1); + + let visited_order = graph.bfs_with_return(0); + assert_eq!(visited_order, vec![0]); + } +} + diff --git a/exercises/algorithm/algorithm6.rs b/exercises/algorithm/algorithm6.rs index 813146f7c..7f7c69a31 100644 --- a/exercises/algorithm/algorithm6.rs +++ b/exercises/algorithm/algorithm6.rs @@ -2,8 +2,6 @@ dfs This problem requires you to implement a basic DFS traversal */ - -// I AM NOT DONE use std::collections::HashSet; struct Graph { @@ -23,7 +21,15 @@ impl Graph { } fn dfs_util(&self, v: usize, visited: &mut HashSet, visit_order: &mut Vec) { - //TODO + visited.insert(v); // Mark the current node as visited + visit_order.push(v); // Add the current node to the visit order + + // Visit all neighbors of the current node + for &neighbor in &self.adj[v] { + if !visited.contains(&neighbor) { + self.dfs_util(neighbor, visited, visit_order); // Recursive DFS call + } + } } // Perform a depth-first search on the graph, return the order of visited nodes diff --git a/exercises/algorithm/algorithm6.rs~ b/exercises/algorithm/algorithm6.rs~ new file mode 100644 index 000000000..7f7c69a31 --- /dev/null +++ b/exercises/algorithm/algorithm6.rs~ @@ -0,0 +1,84 @@ +/* + dfs + This problem requires you to implement a basic DFS traversal +*/ +use std::collections::HashSet; + +struct Graph { + adj: Vec>, +} + +impl Graph { + fn new(n: usize) -> Self { + Graph { + adj: vec![vec![]; n], + } + } + + fn add_edge(&mut self, src: usize, dest: usize) { + self.adj[src].push(dest); + self.adj[dest].push(src); + } + + fn dfs_util(&self, v: usize, visited: &mut HashSet, visit_order: &mut Vec) { + visited.insert(v); // Mark the current node as visited + visit_order.push(v); // Add the current node to the visit order + + // Visit all neighbors of the current node + for &neighbor in &self.adj[v] { + if !visited.contains(&neighbor) { + self.dfs_util(neighbor, visited, visit_order); // Recursive DFS call + } + } + } + + // 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(); + self.dfs_util(start, &mut visited, &mut visit_order); + visit_order + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_dfs_simple() { + let mut graph = Graph::new(3); + graph.add_edge(0, 1); + graph.add_edge(1, 2); + + let visit_order = graph.dfs(0); + assert_eq!(visit_order, vec![0, 1, 2]); + } + + #[test] + fn test_dfs_with_cycle() { + let mut graph = Graph::new(4); + graph.add_edge(0, 1); + graph.add_edge(0, 2); + graph.add_edge(1, 2); + graph.add_edge(2, 3); + graph.add_edge(3, 3); + + let visit_order = graph.dfs(0); + assert_eq!(visit_order, vec![0, 1, 2, 3]); + } + + #[test] + fn test_dfs_disconnected_graph() { + let mut graph = Graph::new(5); + graph.add_edge(0, 1); + graph.add_edge(0, 2); + graph.add_edge(3, 4); + + let visit_order = graph.dfs(0); + assert_eq!(visit_order, vec![0, 1, 2]); + let visit_order_disconnected = graph.dfs(3); + assert_eq!(visit_order_disconnected, vec![3, 4]); + } +} + diff --git a/exercises/algorithm/algorithm7.rs b/exercises/algorithm/algorithm7.rs index e0c3a5ab2..9413f5b7b 100644 --- a/exercises/algorithm/algorithm7.rs +++ b/exercises/algorithm/algorithm7.rs @@ -2,8 +2,6 @@ stack This question requires you to use a stack to achieve a bracket match */ - -// I AM NOT DONE #[derive(Debug)] struct Stack { size: usize, @@ -31,8 +29,11 @@ impl Stack { self.size += 1; } fn pop(&mut self) -> Option { - // TODO - None + if self.is_empty() { + return None; + } + self.size -= 1; + self.data.pop() } fn peek(&self) -> Option<&T> { if 0 == self.size { @@ -101,8 +102,33 @@ impl<'a, T> Iterator for IterMut<'a, T> { fn bracket_match(bracket: &str) -> bool { - //TODO - true + let mut stack = Stack::new(); + + for c in bracket.chars() { + match c { + '(' | '{' | '[' => { + stack.push(c); + } + ')' => { + if stack.pop() != Some('(') { + return false; + } + } + '}' => { + if stack.pop() != Some('{') { + return false; + } + } + ']' => { + if stack.pop() != Some('[') { + return false; + } + } + _ => {} // Ignore other characters + } + } + + stack.is_empty() } #[cfg(test)] @@ -139,4 +165,4 @@ mod tests { let s = ""; assert_eq!(bracket_match(s),true); } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm7.rs~ b/exercises/algorithm/algorithm7.rs~ new file mode 100644 index 000000000..9413f5b7b --- /dev/null +++ b/exercises/algorithm/algorithm7.rs~ @@ -0,0 +1,168 @@ +/* + stack + This question requires you to use a stack to achieve a bracket match +*/ +#[derive(Debug)] +struct Stack { + 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 { + if self.is_empty() { + return None; + } + 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 + } + } +} +struct Iter<'a, T: 'a> { + stack: Vec<&'a T>, +} +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { + self.stack.pop() + } +} +struct IterMut<'a, T: 'a> { + 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() + } +} + +fn bracket_match(bracket: &str) -> bool +{ + let mut stack = Stack::new(); + + for c in bracket.chars() { + match c { + '(' | '{' | '[' => { + stack.push(c); + } + ')' => { + if stack.pop() != Some('(') { + return false; + } + } + '}' => { + if stack.pop() != Some('{') { + return false; + } + } + ']' => { + if stack.pop() != Some('[') { + return false; + } + } + _ => {} // Ignore other characters + } + } + + 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); + } +} diff --git a/exercises/algorithm/algorithm8.rs b/exercises/algorithm/algorithm8.rs index d1d183b84..5b6d34999 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, @@ -62,20 +60,42 @@ 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 + // To implement push, we want to enqueue the element into the non-empty queue + // If both queues are empty, we'll enqueue into q1 by default + if !self.q1.is_empty() { + self.q1.enqueue(elem); + } else { + self.q2.enqueue(elem); + } } pub fn pop(&mut self) -> Result { - //TODO - Err("Stack is empty") + // To implement pop, we want to dequeue all elements from the non-empty queue + // and enqueue them into the other queue until only one element is left + // that last element is the one we want to pop + + let (src, dest) = if !self.q1.is_empty() { + (&mut self.q1, &mut self.q2) + } else if !self.q2.is_empty() { + (&mut self.q2, &mut self.q1) + } else { + return Err("Stack is empty"); + }; + + while src.size() > 1 { + if let Some(val) = src.dequeue().ok() { + dest.enqueue(val); + } + } + + src.dequeue().map_err(|_| "Stack is empty") } pub fn is_empty(&self) -> bool { - //TODO - true + self.q1.is_empty() && self.q2.is_empty() } } @@ -101,4 +121,4 @@ mod tests { assert_eq!(s.pop(), Err("Stack is empty")); assert_eq!(s.is_empty(), true); } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm8.rs~ b/exercises/algorithm/algorithm8.rs~ new file mode 100644 index 000000000..5b6d34999 --- /dev/null +++ b/exercises/algorithm/algorithm8.rs~ @@ -0,0 +1,124 @@ +/* + queue + This question requires you to use queues to implement the functionality of the stac +*/ +#[derive(Debug)] +pub struct Queue { + elements: Vec, +} + +impl Queue { + pub fn new() -> Queue { + Queue { + elements: Vec::new(), + } + } + + pub fn enqueue(&mut self, value: T) { + self.elements.push(value) + } + + pub fn dequeue(&mut self) -> Result { + if !self.elements.is_empty() { + Ok(self.elements.remove(0usize)) + } else { + Err("Queue is empty") + } + } + + pub fn peek(&self) -> Result<&T, &str> { + match self.elements.first() { + Some(value) => Ok(value), + None => Err("Queue is empty"), + } + } + + pub fn size(&self) -> usize { + self.elements.len() + } + + pub fn is_empty(&self) -> bool { + self.elements.is_empty() + } +} + +impl Default for Queue { + fn default() -> Queue { + Queue { + elements: Vec::new(), + } + } +} + +pub struct myStack +{ + //TODO + q1:Queue, + q2:Queue +} +impl myStack { + pub fn new() -> Self { + Self { + //TODO + q1:Queue::new(), + q2:Queue::new() + } + } + pub fn push(&mut self, elem: T) { + // To implement push, we want to enqueue the element into the non-empty queue + // If both queues are empty, we'll enqueue into q1 by default + if !self.q1.is_empty() { + self.q1.enqueue(elem); + } else { + self.q2.enqueue(elem); + } + } + pub fn pop(&mut self) -> Result { + // To implement pop, we want to dequeue all elements from the non-empty queue + // and enqueue them into the other queue until only one element is left + // that last element is the one we want to pop + + let (src, dest) = if !self.q1.is_empty() { + (&mut self.q1, &mut self.q2) + } else if !self.q2.is_empty() { + (&mut self.q2, &mut self.q1) + } else { + return Err("Stack is empty"); + }; + + while src.size() > 1 { + if let Some(val) = src.dequeue().ok() { + dest.enqueue(val); + } + } + + src.dequeue().map_err(|_| "Stack is empty") + } + pub fn is_empty(&self) -> bool { + self.q1.is_empty() && self.q2.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_queue(){ + let mut s = myStack::::new(); + assert_eq!(s.pop(), Err("Stack is empty")); + s.push(1); + s.push(2); + s.push(3); + assert_eq!(s.pop(), Ok(3)); + assert_eq!(s.pop(), Ok(2)); + s.push(4); + s.push(5); + assert_eq!(s.is_empty(), false); + assert_eq!(s.pop(), Ok(5)); + assert_eq!(s.pop(), Ok(4)); + assert_eq!(s.pop(), Ok(1)); + assert_eq!(s.pop(), Err("Stack is empty")); + assert_eq!(s.is_empty(), true); + } +} diff --git a/exercises/algorithm/algorithm9.rs b/exercises/algorithm/algorithm9.rs index 6c8021a4d..bfd40e26b 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,10 @@ where } pub fn add(&mut self, value: T) { - //TODO + self.count += 1; + self.items.push(value); + let idx = self.count; + self.bubble_up(idx); } fn parent_idx(&self, idx: usize) -> usize { @@ -57,8 +58,38 @@ where } fn smallest_child_idx(&self, idx: usize) -> usize { - //TODO - 0 + let left_idx = self.left_child_idx(idx); + let right_idx = self.right_child_idx(idx); + + if right_idx <= self.count && (self.comparator)(&self.items[right_idx], &self.items[left_idx]) { + right_idx + } else { + left_idx + } + } + + + fn bubble_up(&mut self, idx: usize) { + let mut idx = idx; // Make a mutable copy of idx + while idx > 1 && (self.comparator)(&self.items[idx], &self.items[self.parent_idx(idx)]) { + let parent_idx = self.parent_idx(idx); // Borrow self here + self.items.swap(idx, parent_idx); // Now we're borrowing self.items mutably + idx = parent_idx; + } + } + fn bubble_down(&mut self, mut idx: usize) { + loop { + let smallest_child = self.smallest_child_idx(idx); + if smallest_child > self.count { + break; + } + if (self.comparator)(&self.items[smallest_child], &self.items[idx]) { + self.items.swap(smallest_child, idx); + idx = smallest_child; + } else { + break; + } + } } } @@ -84,8 +115,16 @@ where type Item = T; fn next(&mut self) -> Option { - //TODO - None + if self.is_empty() { + return None; + } + let result = self.items.swap_remove(1); + self.count -= 1; + if self.count > 0 { + self.items.swap(1, self.count ); + self.bubble_down(1); + } + Some(result) } } @@ -151,4 +190,4 @@ mod tests { heap.add(1); assert_eq!(heap.next(), Some(2)); } -} \ No newline at end of file +} diff --git a/exercises/algorithm/algorithm9.rs~ b/exercises/algorithm/algorithm9.rs~ new file mode 100644 index 000000000..bfd40e26b --- /dev/null +++ b/exercises/algorithm/algorithm9.rs~ @@ -0,0 +1,193 @@ +/* + heap + This question requires you to implement a binary heap function +*/ +use std::cmp::Ord; +use std::default::Default; + +pub struct Heap +where + T: Default, +{ + count: usize, + items: Vec, + comparator: fn(&T, &T) -> bool, +} + +impl Heap +where + T: Default, +{ + pub fn new(comparator: fn(&T, &T) -> bool) -> Self { + Self { + count: 0, + items: vec![T::default()], + comparator, + } + } + + pub fn len(&self) -> usize { + self.count + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn add(&mut self, value: T) { + self.count += 1; + self.items.push(value); + let idx = self.count; + self.bubble_up(idx); + } + + fn parent_idx(&self, idx: usize) -> usize { + idx / 2 + } + + fn children_present(&self, idx: usize) -> bool { + self.left_child_idx(idx) <= self.count + } + + fn left_child_idx(&self, idx: usize) -> usize { + idx * 2 + } + + fn right_child_idx(&self, idx: usize) -> usize { + self.left_child_idx(idx) + 1 + } + + fn smallest_child_idx(&self, idx: usize) -> usize { + let left_idx = self.left_child_idx(idx); + let right_idx = self.right_child_idx(idx); + + if right_idx <= self.count && (self.comparator)(&self.items[right_idx], &self.items[left_idx]) { + right_idx + } else { + left_idx + } + } + + + fn bubble_up(&mut self, idx: usize) { + let mut idx = idx; // Make a mutable copy of idx + while idx > 1 && (self.comparator)(&self.items[idx], &self.items[self.parent_idx(idx)]) { + let parent_idx = self.parent_idx(idx); // Borrow self here + self.items.swap(idx, parent_idx); // Now we're borrowing self.items mutably + idx = parent_idx; + } + } + fn bubble_down(&mut self, mut idx: usize) { + loop { + let smallest_child = self.smallest_child_idx(idx); + if smallest_child > self.count { + break; + } + if (self.comparator)(&self.items[smallest_child], &self.items[idx]) { + self.items.swap(smallest_child, idx); + idx = smallest_child; + } else { + break; + } + } + } +} + +impl Heap +where + T: Default + Ord, +{ + /// Create a new MinHeap + pub fn new_min() -> Self { + Self::new(|a, b| a < b) + } + + /// Create a new MaxHeap + pub fn new_max() -> Self { + Self::new(|a, b| a > b) + } +} + +impl Iterator for Heap +where + T: Default, +{ + type Item = T; + + fn next(&mut self) -> Option { + if self.is_empty() { + return None; + } + let result = self.items.swap_remove(1); + self.count -= 1; + if self.count > 0 { + self.items.swap(1, self.count ); + self.bubble_down(1); + } + Some(result) + } +} + +pub struct MinHeap; + +impl MinHeap { + #[allow(clippy::new_ret_no_self)] + pub fn new() -> Heap + where + T: Default + Ord, + { + Heap::new(|a, b| a < b) + } +} + +pub struct MaxHeap; + +impl MaxHeap { + #[allow(clippy::new_ret_no_self)] + pub fn new() -> Heap + where + T: Default + Ord, + { + Heap::new(|a, b| a > b) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_empty_heap() { + let mut heap = MaxHeap::new::(); + assert_eq!(heap.next(), None); + } + + #[test] + fn test_min_heap() { + let mut heap = MinHeap::new(); + heap.add(4); + heap.add(2); + heap.add(9); + heap.add(11); + assert_eq!(heap.len(), 4); + assert_eq!(heap.next(), Some(2)); + assert_eq!(heap.next(), Some(4)); + assert_eq!(heap.next(), Some(9)); + heap.add(1); + assert_eq!(heap.next(), Some(1)); + } + + #[test] + fn test_max_heap() { + let mut heap = MaxHeap::new(); + heap.add(4); + heap.add(2); + heap.add(9); + heap.add(11); + assert_eq!(heap.len(), 4); + assert_eq!(heap.next(), Some(11)); + assert_eq!(heap.next(), Some(9)); + assert_eq!(heap.next(), Some(4)); + heap.add(1); + assert_eq!(heap.next(), Some(2)); + } +} diff --git a/exercises/clippy/.clippy1.rs.un~ b/exercises/clippy/.clippy1.rs.un~ new file mode 100644 index 000000000..38abcf7fc Binary files /dev/null and b/exercises/clippy/.clippy1.rs.un~ differ diff --git a/exercises/clippy/.clippy2.rs.un~ b/exercises/clippy/.clippy2.rs.un~ new file mode 100644 index 000000000..2d83e75e6 Binary files /dev/null and b/exercises/clippy/.clippy2.rs.un~ differ diff --git a/exercises/clippy/.clippy3.rs.un~ b/exercises/clippy/.clippy3.rs.un~ new file mode 100644 index 000000000..b3a9e38e8 Binary files /dev/null and b/exercises/clippy/.clippy3.rs.un~ differ 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/clippy1.rs~ b/exercises/clippy/clippy1.rs~ new file mode 100644 index 000000000..e2b1ebf4b --- /dev/null +++ b/exercises/clippy/clippy1.rs~ @@ -0,0 +1,24 @@ +// clippy1.rs +// +// The Clippy tool is a collection of lints to analyze your code so you can +// catch common mistakes and improve your Rust code. +// +// For these exercises the code will fail to compile when there are clippy +// warnings check clippy's suggestions from the output to solve the exercise. +// +// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a +// hint. + +use std::f32; + +fn main() { + let pi = f32::consts::PI; + let radius = 5.00f32; + + let area = pi * f32::powi(radius, 2); + + println!( + "The area of a circle with radius {:.2} is {:.5}!", + radius, area + ) +} 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/clippy2.rs~ b/exercises/clippy/clippy2.rs~ new file mode 100644 index 000000000..79c5c9fec --- /dev/null +++ b/exercises/clippy/clippy2.rs~ @@ -0,0 +1,13 @@ +// clippy2.rs +// +// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a +// hint. + +fn main() { + let mut res = 42; + let option = Some(12); + if let Some(x) = option { + res += x; + } + println!("{}", res); +} diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index 35021f841..0bd6a733e 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -4,28 +4,25 @@ // // 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(); + println!("{my_option:?}"); } let my_arr = &[ - -1, -2, -3 + -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? {:?}", ()); 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/clippy/clippy3.rs~ b/exercises/clippy/clippy3.rs~ new file mode 100644 index 000000000..0bd6a733e --- /dev/null +++ b/exercises/clippy/clippy3.rs~ @@ -0,0 +1,28 @@ +// 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. + +#[allow(unused_variables, unused_assignments)] +fn main() { + let my_option: Option<()> = None; + if my_option.is_none() { + println!("{my_option:?}"); + } + + let my_arr = &[ + -1, -2, -3, + -4, -5, -6 + ]; + println!("My array! Here it is: {:?}", my_arr); + + vec![1, 2, 3, 4, 5].resize(0, 5); + println!("This Vec is empty, see? {:?}", ()); + + let mut value_a = 45; + let mut value_b = 66; + // Let's swap these two! + 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.un~ b/exercises/conversions/.as_ref_mut.rs.un~ new file mode 100644 index 000000000..51ce445e6 Binary files /dev/null and b/exercises/conversions/.as_ref_mut.rs.un~ differ diff --git a/exercises/conversions/.from_into.rs.un~ b/exercises/conversions/.from_into.rs.un~ new file mode 100644 index 000000000..f2dc3a090 Binary files /dev/null and b/exercises/conversions/.from_into.rs.un~ differ diff --git a/exercises/conversions/.from_str.rs.un~ b/exercises/conversions/.from_str.rs.un~ new file mode 100644 index 000000000..b42605588 Binary files /dev/null and b/exercises/conversions/.from_str.rs.un~ differ diff --git a/exercises/conversions/.try_from_into.rs.un~ b/exercises/conversions/.try_from_into.rs.un~ new file mode 100644 index 000000000..329ca099f Binary files /dev/null and b/exercises/conversions/.try_from_into.rs.un~ differ diff --git a/exercises/conversions/.using_as.rs.un~ b/exercises/conversions/.using_as.rs.un~ new file mode 100644 index 000000000..0eddb8617 Binary files /dev/null and b/exercises/conversions/.using_as.rs.un~ differ diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index 626a36c45..a8df8caaa 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -7,25 +7,25 @@ // 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>(arg: &mut T) { // TODO: Implement the function body. - ??? + let a = *arg.as_mut(); + *arg.as_mut() = a * a; + } #[cfg(test)] diff --git a/exercises/conversions/as_ref_mut.rs~ b/exercises/conversions/as_ref_mut.rs~ new file mode 100644 index 000000000..a8df8caaa --- /dev/null +++ b/exercises/conversions/as_ref_mut.rs~ @@ -0,0 +1,65 @@ +// as_ref_mut.rs +// +// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more +// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and +// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. +// +// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a +// hint. + +// 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 { + 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 { + 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. + let a = *arg.as_mut(); + *arg.as_mut() = a * a; + +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn different_counts() { + let s = "Café au lait"; + assert_ne!(char_counter(s), byte_counter(s)); + } + + #[test] + fn same_counts() { + let s = "Cafe au lait"; + assert_eq!(char_counter(s), byte_counter(s)); + } + + #[test] + fn different_counts_using_string() { + let s = String::from("Café au lait"); + assert_ne!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn same_counts_using_string() { + let s = String::from("Cafe au lait"); + assert_eq!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn mult_box() { + let mut num: Box = Box::new(3); + num_sq(&mut num); + assert_eq!(*num, 9); + } +} diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index aba471d92..192456f66 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -40,13 +40,35 @@ 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 { + let l: Vec<_> = s.matches(",").collect(); + if s.len() == 0 || s.find(',').is_none() || l.len() > 1 { + Person::default() + } else { + let a: Vec<_> = s.split(',').collect(); + let (name, age) = (a[0], a[1]); + if name.is_empty() { + Person::default() + + } else if age.to_string().parse::().is_ok() { + Person { + name: name.to_string(), + age: age.to_string().parse::().unwrap(), + } + } else { + Person::default() + } + } + } } + + fn main() { // Use the `from` function let p1 = Person::from("Mark,20"); diff --git a/exercises/conversions/from_into.rs~ b/exercises/conversions/from_into.rs~ new file mode 100644 index 000000000..192456f66 --- /dev/null +++ b/exercises/conversions/from_into.rs~ @@ -0,0 +1,162 @@ +// from_into.rs +// +// The From trait is used for value-to-value conversions. If From is implemented +// correctly for a type, the Into trait should work conversely. You can read +// more about it at https://doc.rust-lang.org/std/convert/trait.From.html +// +// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a +// hint. + +#[derive(Debug)] +struct Person { + name: String, + age: usize, +} + +// We implement the Default trait to use it as a fallback +// when the provided string is not convertible into a Person object +impl Default for Person { + fn default() -> Person { + Person { + name: String::from("John"), + age: 30, + } + } +} + +// Your task is to complete this implementation in order for the line `let p = +// Person::from("Mark,20")` to compile Please note that you'll need to parse the +// age component into a `usize` with something like `"4".parse::()`. The +// outcome of this needs to be handled appropriately. +// +// Steps: +// 1. If the length of the provided string is 0, then return the default of +// Person. +// 2. Split the given string on the commas present in it. +// 3. Extract the first element from the split operation and use it as the name. +// 4. If the name is empty, then return the default of Person. +// 5. Extract the other element from the split operation and parse it into a +// `usize` as the age. +// If while parsing the age, something goes wrong, then return the default of +// Person Otherwise, then return an instantiated Person object with the results + + + + +impl From<&str> for Person { + fn from(s: &str) -> Person { + let l: Vec<_> = s.matches(",").collect(); + if s.len() == 0 || s.find(',').is_none() || l.len() > 1 { + Person::default() + } else { + let a: Vec<_> = s.split(',').collect(); + let (name, age) = (a[0], a[1]); + if name.is_empty() { + Person::default() + + } else if age.to_string().parse::().is_ok() { + Person { + name: name.to_string(), + age: age.to_string().parse::().unwrap(), + } + } else { + Person::default() + } + } + + } +} + + + +fn main() { + // Use the `from` function + let p1 = Person::from("Mark,20"); + // Since From is implemented for Person, we should be able to use Into + let p2: Person = "Gerald,70".into(); + println!("{:?}", p1); + println!("{:?}", p2); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_default() { + // Test that the default person is 30 year old John + let dp = Person::default(); + assert_eq!(dp.name, "John"); + assert_eq!(dp.age, 30); + } + #[test] + fn test_bad_convert() { + // Test that John is returned when bad string is provided + let p = Person::from(""); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + #[test] + fn test_good_convert() { + // Test that "Mark,20" works + let p = Person::from("Mark,20"); + assert_eq!(p.name, "Mark"); + assert_eq!(p.age, 20); + } + #[test] + fn test_bad_age() { + // Test that "Mark,twenty" will return the default person due to an + // error in parsing age + let p = Person::from("Mark,twenty"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_comma_and_age() { + let p: Person = Person::from("Mark"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_age() { + let p: Person = Person::from("Mark,"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name() { + let p: Person = Person::from(",1"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_age() { + let p: Person = Person::from(","); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_invalid_age() { + let p: Person = Person::from(",one"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma() { + let p: Person = Person::from("Mike,32,"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma_and_some_string() { + let p: Person = Person::from("Mike,32,man"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } +} diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32c..cd0457fa8 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,26 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(ParsePersonError::Empty); + } + + let l: Vec<&str> = s.split(',').collect(); + if l.len() != 2 { + return Err(ParsePersonError::BadLen); + } + + let (name, age) = (l[0], l[1]); + if name.is_empty() { + return Err(ParsePersonError::NoName); + } + + let age = age.parse::().map_err(ParsePersonError::ParseInt)?; + + Ok(Person { + name: name.to_string(), + age: age, + }) } } diff --git a/exercises/conversions/from_str.rs~ b/exercises/conversions/from_str.rs~ new file mode 100644 index 000000000..cd0457fa8 --- /dev/null +++ b/exercises/conversions/from_str.rs~ @@ -0,0 +1,151 @@ +// from_str.rs +// +// This is similar to from_into.rs, but this time we'll implement `FromStr` and +// return errors instead of falling back to a default value. Additionally, upon +// implementing FromStr, you can use the `parse` method on strings to generate +// an object of the implementor type. You can read more about it at +// https://doc.rust-lang.org/std/str/trait.FromStr.html +// +// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a +// hint. + +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug, PartialEq)] +struct Person { + name: String, + age: usize, +} + +// We will use this error type for the `FromStr` implementation. +#[derive(Debug, PartialEq)] +enum ParsePersonError { + // Empty input string + Empty, + // Incorrect number of fields + BadLen, + // Empty name field + NoName, + // Wrapped error from parse::() + ParseInt(ParseIntError), +} + +// 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 +// 3. Only 2 elements should be returned from the split, otherwise return an +// error +// 4. Extract the first element from the split operation and use it as the name +// 5. Extract the other element from the split operation and parse it into a +// `usize` as the age with something like `"4".parse::()` +// 6. If while extracting the name and the age something goes wrong, an error +// should be returned +// If everything goes well, then return a Result of a Person object +// +// As an aside: `Box` implements `From<&'_ str>`. This means that if +// you want to return a string error message, you can do so via just using +// return `Err("my error message".into())`. + +impl FromStr for Person { + type Err = ParsePersonError; + fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(ParsePersonError::Empty); + } + + let l: Vec<&str> = s.split(',').collect(); + if l.len() != 2 { + return Err(ParsePersonError::BadLen); + } + + let (name, age) = (l[0], l[1]); + if name.is_empty() { + return Err(ParsePersonError::NoName); + } + + let age = age.parse::().map_err(ParsePersonError::ParseInt)?; + + Ok(Person { + name: name.to_string(), + age: age, + }) + } +} + +fn main() { + let p = "Mark,20".parse::().unwrap(); + println!("{:?}", p); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_input() { + assert_eq!("".parse::(), Err(ParsePersonError::Empty)); + } + #[test] + fn good_input() { + let p = "John,32".parse::(); + assert!(p.is_ok()); + let p = p.unwrap(); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 32); + } + #[test] + fn missing_age() { + assert!(matches!( + "John,".parse::(), + Err(ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn invalid_age() { + assert!(matches!( + "John,twenty".parse::(), + Err(ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn missing_comma_and_age() { + assert_eq!("John".parse::(), Err(ParsePersonError::BadLen)); + } + + #[test] + fn missing_name() { + assert_eq!(",1".parse::(), Err(ParsePersonError::NoName)); + } + + #[test] + fn missing_name_and_age() { + assert!(matches!( + ",".parse::(), + Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn missing_name_and_invalid_age() { + assert!(matches!( + ",one".parse::(), + Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn trailing_comma() { + assert_eq!("John,32,".parse::(), Err(ParsePersonError::BadLen)); + } + + #[test] + fn trailing_comma_and_some_string() { + assert_eq!( + "John,32,man".parse::(), + Err(ParsePersonError::BadLen) + ); + } +} diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39e..fd13f6a26 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. @@ -37,27 +35,58 @@ enum IntoColorError { // time, but the slice implementation needs to check the slice length! Also note // that correct RGB color values must be integers in the 0..=255 range. + + + +fn check_and_convert_to_u8>(value: T) -> Result { + let value = value.into(); + if value < 0 || value > 255 { + return Err(IntoColorError::IntConversion); + } + Ok(value as u8) +} + // Tuple implementation -impl TryFrom<(i16, i16, i16)> for Color { +impl TryFrom<(i32, i32, i32)> for Color { type Error = IntoColorError; - fn try_from(tuple: (i16, i16, i16)) -> Result { + fn try_from(tuple: (i32, i32, i32)) -> Result { + let red = check_and_convert_to_u8(tuple.0)?; + let green = check_and_convert_to_u8(tuple.1)?; + let blue = check_and_convert_to_u8(tuple.2)?; + + Ok(Color { red, green, blue }) } } // Array implementation -impl TryFrom<[i16; 3]> for Color { +impl TryFrom<[i32; 3]> for Color { type Error = IntoColorError; - fn try_from(arr: [i16; 3]) -> Result { + fn try_from(arr: [i32; 3]) -> Result { + let red = check_and_convert_to_u8(arr[0])?; + let green = check_and_convert_to_u8(arr[1])?; + let blue = check_and_convert_to_u8(arr[2])?; + + Ok(Color { red, green, blue }) } } // Slice implementation -impl TryFrom<&[i16]> for Color { +impl TryFrom<&[i32]> for Color { type Error = IntoColorError; - fn try_from(slice: &[i16]) -> Result { + fn try_from(slice: &[i32]) -> Result { + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + + let red = check_and_convert_to_u8(slice[0])?; + let green = check_and_convert_to_u8(slice[1])?; + let blue = check_and_convert_to_u8(slice[2])?; + + Ok(Color { red, green, blue }) } } + fn main() { // Use the `try_from` function let c1 = Color::try_from((183, 65, 14)); diff --git a/exercises/conversions/try_from_into.rs~ b/exercises/conversions/try_from_into.rs~ new file mode 100644 index 000000000..fd13f6a26 --- /dev/null +++ b/exercises/conversions/try_from_into.rs~ @@ -0,0 +1,222 @@ +// try_from_into.rs +// +// TryFrom is a simple and safe type conversion that may fail in a controlled +// way under some circumstances. Basically, this is the same as From. The main +// difference is that this should return a Result type instead of the target +// type itself. You can read more about it at +// https://doc.rust-lang.org/std/convert/trait.TryFrom.html +// +// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for +// a hint. + +use std::convert::{TryFrom, TryInto}; + +#[derive(Debug, PartialEq)] +struct Color { + red: u8, + green: u8, + blue: u8, +} + +// We will use this error type for these `TryFrom` conversions. +#[derive(Debug, PartialEq)] +enum IntoColorError { + // Incorrect length of slice + BadLen, + // Integer conversion error + IntConversion, +} + +// 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. +// +// Note that the implementation for tuple and array will be checked at compile +// time, but the slice implementation needs to check the slice length! Also note +// that correct RGB color values must be integers in the 0..=255 range. + + + + +fn check_and_convert_to_u8>(value: T) -> Result { + let value = value.into(); + if value < 0 || value > 255 { + return Err(IntoColorError::IntConversion); + } + Ok(value as u8) +} + +// Tuple implementation +impl TryFrom<(i32, i32, i32)> for Color { + type Error = IntoColorError; + fn try_from(tuple: (i32, i32, i32)) -> Result { + let red = check_and_convert_to_u8(tuple.0)?; + let green = check_and_convert_to_u8(tuple.1)?; + let blue = check_and_convert_to_u8(tuple.2)?; + + Ok(Color { red, green, blue }) + } +} + +// Array implementation +impl TryFrom<[i32; 3]> for Color { + type Error = IntoColorError; + fn try_from(arr: [i32; 3]) -> Result { + let red = check_and_convert_to_u8(arr[0])?; + let green = check_and_convert_to_u8(arr[1])?; + let blue = check_and_convert_to_u8(arr[2])?; + + Ok(Color { red, green, blue }) + } +} + +// Slice implementation +impl TryFrom<&[i32]> for Color { + type Error = IntoColorError; + fn try_from(slice: &[i32]) -> Result { + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + + let red = check_and_convert_to_u8(slice[0])?; + let green = check_and_convert_to_u8(slice[1])?; + let blue = check_and_convert_to_u8(slice[2])?; + + Ok(Color { red, green, blue }) + } +} + + +fn main() { + // Use the `try_from` function + let c1 = Color::try_from((183, 65, 14)); + println!("{:?}", c1); + + // Since TryFrom is implemented for Color, we should be able to use TryInto + let c2: Result = [183, 65, 14].try_into(); + println!("{:?}", c2); + + let v = vec![183, 65, 14]; + // With slice we should use `try_from` function + let c3 = Color::try_from(&v[..]); + println!("{:?}", c3); + // or take slice within round brackets and use TryInto + let c4: Result = (&v[..]).try_into(); + println!("{:?}", c4); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tuple_out_of_range_positive() { + assert_eq!( + Color::try_from((256, 1000, 10000)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_out_of_range_negative() { + assert_eq!( + Color::try_from((-1, -10, -256)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_sum() { + assert_eq!( + Color::try_from((-1, 255, 255)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_correct() { + let c: Result = (183, 65, 14).try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_array_out_of_range_positive() { + let c: Result = [1000, 10000, 256].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_out_of_range_negative() { + let c: Result = [-10, -256, -1].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_sum() { + let c: Result = [-1, 255, 255].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_correct() { + let c: Result = [183, 65, 14].try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_slice_out_of_range_positive() { + let arr = [10000, 256, 1000]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_out_of_range_negative() { + let arr = [-256, -1, -10]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_sum() { + let arr = [-1, 255, 255]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_correct() { + let v = vec![183, 65, 14]; + let c: Result = Color::try_from(&v[..]); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_slice_excess_length() { + let v = vec![0, 0, 0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + } + #[test] + fn test_slice_insufficient_length() { + let v = vec![0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + } +} 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/conversions/using_as.rs~ b/exercises/conversions/using_as.rs~ new file mode 100644 index 000000000..a9f1e4496 --- /dev/null +++ b/exercises/conversions/using_as.rs~ @@ -0,0 +1,31 @@ +// using_as.rs +// +// Type casting in Rust is done via the usage of the `as` operator. Please note +// that the `as` operator is not only used when type casting. It also helps with +// renaming imports. +// +// The goal is to make sure that the division does not fail to compile and +// returns the proper type. +// +// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a +// hint. + +fn average(values: &[f64]) -> f64 { + let total = values.iter().sum::(); + total / values.len() as f64 +} + +fn main() { + let values = [3.5, 0.3, 13.0, 11.7]; + println!("{}", average(&values)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn returns_proper_type_and_value() { + assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125); + } +} diff --git a/exercises/enums/.enums1.rs.un~ b/exercises/enums/.enums1.rs.un~ new file mode 100644 index 000000000..4bbf07437 Binary files /dev/null and b/exercises/enums/.enums1.rs.un~ differ diff --git a/exercises/enums/.enums2.rs.un~ b/exercises/enums/.enums2.rs.un~ new file mode 100644 index 000000000..468d42bb4 Binary files /dev/null and b/exercises/enums/.enums2.rs.un~ differ diff --git a/exercises/enums/.enums3.rs.un~ b/exercises/enums/.enums3.rs.un~ new file mode 100644 index 000000000..d1d16205a Binary files /dev/null and b/exercises/enums/.enums3.rs.un~ differ diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index 25525b252..bd0aebf03 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -2,11 +2,14 @@ // // 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/enums1.rs~ b/exercises/enums/enums1.rs~ new file mode 100644 index 000000000..bd0aebf03 --- /dev/null +++ b/exercises/enums/enums1.rs~ @@ -0,0 +1,20 @@ +// enums1.rs +// +// No hints this time! ;) + +#[derive(Debug)] +enum Message { + // TODO: define a few types of messages as used below + + Quit, + Echo, + Move, + ChangeColor, +} + +fn main() { + println!("{:?}", Message::Quit); + println!("{:?}", Message::Echo); + println!("{:?}", Message::Move); + println!("{:?}", Message::ChangeColor); +} diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index df93fe0f1..75479ded2 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -3,11 +3,14 @@ // 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: u8, y: u8}, + Echo(String), + ChangeColor(u8, u8, u8), + Quit, } impl Message { diff --git a/exercises/enums/enums2.rs~ b/exercises/enums/enums2.rs~ new file mode 100644 index 000000000..75479ded2 --- /dev/null +++ b/exercises/enums/enums2.rs~ @@ -0,0 +1,33 @@ +// enums2.rs +// +// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a +// hint. + + +#[derive(Debug)] +enum Message { + // TODO: define the different variants used below + Move {x: u8, y: u8}, + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +impl Message { + fn call(&self) { + println!("{:?}", self); + } +} + +fn main() { + let messages = [ + Message::Move { x: 10, y: 30 }, + Message::Echo(String::from("hello world")), + Message::ChangeColor(200, 255, 255), + Message::Quit, + ]; + + for message in &messages { + message.call(); + } +} diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index 5d284417e..7e3f8a5e2 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -5,10 +5,12 @@ // 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 + Quit, + ChangeColor(u8, u8, u8), + Echo(String), + Move(Point), } struct Point { @@ -43,6 +45,12 @@ 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(a, b, c) => self.change_color((a, b, c)), + Message::Quit => self.quit(), + Message::Echo(String) => self.echo(String), + Message::Move(Point) => self.move_position(Point), + } } } diff --git a/exercises/enums/enums3.rs~ b/exercises/enums/enums3.rs~ new file mode 100644 index 000000000..7e3f8a5e2 --- /dev/null +++ b/exercises/enums/enums3.rs~ @@ -0,0 +1,80 @@ +// enums3.rs +// +// Address all the TODOs to make the tests pass! +// +// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a +// hint. + +enum Message { + // TODO: implement the message variant types based on their usage below + Quit, + ChangeColor(u8, u8, u8), + Echo(String), + Move(Point), +} + +struct Point { + x: u8, + y: u8, +} + +struct State { + color: (u8, u8, u8), + position: Point, + quit: bool, + message: String +} + +impl State { + fn change_color(&mut self, color: (u8, u8, u8)) { + self.color = color; + } + + fn quit(&mut self) { + self.quit = true; + } + + fn echo(&mut self, s: String) { self.message = s } + + fn move_position(&mut self, p: Point) { + self.position = p; + } + + 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(a, b, c) => self.change_color((a, b, c)), + Message::Quit => self.quit(), + Message::Echo(String) => self.echo(String), + Message::Move(Point) => self.move_position(Point), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + quit: false, + position: Point { x: 0, y: 0 }, + color: (0, 0, 0), + message: "hello world".to_string(), + }; + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Echo(String::from("hello world"))); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Quit); + + assert_eq!(state.color, (255, 0, 255)); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.quit, true); + assert_eq!(state.message, "hello world"); + } +} diff --git a/exercises/error_handling/.errors1.rs.un~ b/exercises/error_handling/.errors1.rs.un~ new file mode 100644 index 000000000..77ae747e0 Binary files /dev/null and b/exercises/error_handling/.errors1.rs.un~ differ diff --git a/exercises/error_handling/.errors2.rs.un~ b/exercises/error_handling/.errors2.rs.un~ new file mode 100644 index 000000000..3295662df Binary files /dev/null and b/exercises/error_handling/.errors2.rs.un~ differ diff --git a/exercises/error_handling/.errors3.rs.un~ b/exercises/error_handling/.errors3.rs.un~ new file mode 100644 index 000000000..4af895aeb Binary files /dev/null and b/exercises/error_handling/.errors3.rs.un~ differ diff --git a/exercises/error_handling/.errors4.rs.un~ b/exercises/error_handling/.errors4.rs.un~ new file mode 100644 index 000000000..473f4e054 Binary files /dev/null and b/exercises/error_handling/.errors4.rs.un~ differ diff --git a/exercises/error_handling/.errors5.rs.un~ b/exercises/error_handling/.errors5.rs.un~ new file mode 100644 index 000000000..f440bc7c2 Binary files /dev/null and b/exercises/error_handling/.errors5.rs.un~ differ diff --git a/exercises/error_handling/.errors6.rs.un~ b/exercises/error_handling/.errors6.rs.un~ new file mode 100644 index 000000000..687096e17 Binary files /dev/null and b/exercises/error_handling/.errors6.rs.un~ differ diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 13d2724cb..783a501e6 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/errors1.rs~ b/exercises/error_handling/errors1.rs~ new file mode 100644 index 000000000..783a501e6 --- /dev/null +++ b/exercises/error_handling/errors1.rs~ @@ -0,0 +1,41 @@ +// errors1.rs +// +// This function refuses to generate text to be printed on a nametag if you pass +// it an empty string. It'd be nicer if it explained what the problem was, +// instead of just sometimes returning `None`. Thankfully, Rust has a similar +// construct to `Result` that can be used to express error conditions. Let's use +// it! +// +// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a +// hint. + +pub fn generate_nametag_text(name: String) -> Result { + if name.is_empty() { + // Empty names aren't allowed. + Err("`name` was empty; it must be nonempty.".into()) + } else { + Ok(format!("Hi! My name is {}", name)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".into()), + Ok("Hi! My name is Beyoncé".into()) + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text("".into()), + // Don't change this line + Err("`name` was empty; it must be nonempty.".into()) + ); + } +} diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index d86f326d0..bd239a70d 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -19,16 +19,15 @@ // 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) + } #[cfg(test)] diff --git a/exercises/error_handling/errors2.rs~ b/exercises/error_handling/errors2.rs~ new file mode 100644 index 000000000..bd239a70d --- /dev/null +++ b/exercises/error_handling/errors2.rs~ @@ -0,0 +1,49 @@ +// errors2.rs +// +// Say we're writing a game where you can buy items with tokens. All items cost +// 5 tokens, and whenever you purchase items there is a processing fee of 1 +// token. A player of the game will type in how many items they want to buy, and +// the `total_cost` function will calculate the total cost of the tokens. Since +// the player typed in the quantity, though, we get it as a string-- and they +// might have typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all (and isn't +// handling the success case properly either). What we want to do is: if we call +// the `parse` function on a string that is not a number, that function will +// return a `ParseIntError`, and in that case, we want to immediately return +// that error from our function and not try to multiply and add. +// +// There are at least two ways to implement this that are both correct-- but one +// is a lot shorter! +// +// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a +// hint. + + +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::()?; + Ok(qty * cost_per_item + processing_fee) + +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn item_quantity_is_a_valid_number() { + assert_eq!(total_cost("34"), Ok(171)); + } + + #[test] + fn item_quantity_is_an_invalid_number() { + assert_eq!( + total_cost("beep boop").unwrap_err().to_string(), + "invalid digit found in string" + ); + } +} diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index d42d3b17c..634a7e164 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -7,7 +7,6 @@ // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::num::ParseIntError; @@ -15,7 +14,7 @@ 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).unwrap(); if cost > tokens { println!("You can't afford that many!"); diff --git a/exercises/error_handling/errors3.rs~ b/exercises/error_handling/errors3.rs~ new file mode 100644 index 000000000..634a7e164 --- /dev/null +++ b/exercises/error_handling/errors3.rs~ @@ -0,0 +1,33 @@ +// errors3.rs +// +// This is a program that is trying to use a completed version of the +// `total_cost` function from the previous exercise. It's not working though! +// Why not? What should we do to fix it? +// +// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a +// hint. + + +use std::num::ParseIntError; + +fn main() { + let mut tokens = 100; + let pretend_user_input = "8"; + + let cost = total_cost(pretend_user_input).unwrap(); + + if cost > tokens { + println!("You can't afford that many!"); + } else { + tokens -= cost; + println!("You now have {} tokens.", tokens); + } +} + +pub fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + let qty = item_quantity.parse::()?; + + Ok(qty * cost_per_item + processing_fee) +} diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index e04bff77a..7406bd6e2 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); @@ -17,7 +15,15 @@ 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 { + Ok(PositiveNonzeroInteger(value as u64)) + } else if value == 0 { + Err(CreationError::Zero) + + } else { + Err(CreationError::Negative) + + } } } diff --git a/exercises/error_handling/errors4.rs~ b/exercises/error_handling/errors4.rs~ new file mode 100644 index 000000000..7406bd6e2 --- /dev/null +++ b/exercises/error_handling/errors4.rs~ @@ -0,0 +1,38 @@ +// errors4.rs +// +// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a +// hint. + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + // Hmm...? Why is this only returning an Ok value? + if value > 0 { + Ok(PositiveNonzeroInteger(value as u64)) + } else if value == 0 { + Err(CreationError::Zero) + + } else { + Err(CreationError::Negative) + + } + } +} + +#[test] +fn test_creation() { + assert!(PositiveNonzeroInteger::new(10).is_ok()); + assert_eq!( + Err(CreationError::Negative), + PositiveNonzeroInteger::new(-10) + ); + assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0)); +} diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 92461a7e0..722c778de 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/errors5.rs~ b/exercises/error_handling/errors5.rs~ new file mode 100644 index 000000000..722c778de --- /dev/null +++ b/exercises/error_handling/errors5.rs~ @@ -0,0 +1,69 @@ +// errors5.rs +// +// This program uses an altered version of the code from errors4. +// +// This exercise uses some concepts that we won't get to until later in the +// course, like `Box` and the `From` trait. It's not important to understand +// them in detail right now, but you can read ahead if you like. For now, think +// of the `Box` type as an "I want anything that does ???" type, which, +// given Rust's usual standards for runtime safety, should strike you as +// somewhat lenient! +// +// In short, this particular use case for boxes is for when you want to own a +// value and you care only that it is a type which implements a particular +// trait. To do so, The Box is declared as of type Box where Trait is +// the trait the compiler looks for on any value used in that context. For this +// exercise, that context is the potential errors which can be returned in a +// Result. +// +// What can we use to describe both errors? In other words, is there a trait +// which both errors implement? +// +// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a +// hint. + +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> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} + +// Don't change anything below this line. + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + x if x == 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +// This is required so that `CreationError` can implement `error::Error`. +impl fmt::Display for CreationError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match *self { + CreationError::Negative => "number is negative", + CreationError::Zero => "number is zero", + }; + f.write_str(description) + } +} + +impl error::Error for CreationError {} diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index aaf0948ef..813ad006d 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/error_handling/errors6.rs~ b/exercises/error_handling/errors6.rs~ new file mode 100644 index 000000000..813ad006d --- /dev/null +++ b/exercises/error_handling/errors6.rs~ @@ -0,0 +1,95 @@ +// errors6.rs +// +// Using catch-all error types like `Box` isn't recommended +// for library code, where callers might want to make decisions based on the +// error content, instead of printing it out or propagating it further. Here, we +// define a custom error type to make it possible for callers to decide what to +// do next when our function returns an error. +// +// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a +// hint. + +use std::num::ParseIntError; + +// This is a custom error type that we will be using in `parse_pos_nonzero()`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> ParsePosNonzeroError { + ParsePosNonzeroError::Creation(err) + } + // 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().map_err(ParsePosNonzeroError::from_parseint)?; + PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) +} + +// Don't change anything below this line. + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + x if x == 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + // We can't construct a ParseIntError, so we have to pattern match. + assert!(matches!( + parse_pos_nonzero("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)) + )); + } + + #[test] + fn test_negative() { + assert_eq!( + parse_pos_nonzero("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)) + ); + } + + #[test] + fn test_zero() { + assert_eq!( + parse_pos_nonzero("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)) + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42); + assert!(x.is_ok()); + assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap())); + } +} diff --git a/exercises/generics/.generics1.rs.un~ b/exercises/generics/.generics1.rs.un~ new file mode 100644 index 000000000..aa19a7e39 Binary files /dev/null and b/exercises/generics/.generics1.rs.un~ differ diff --git a/exercises/generics/.generics2.rs.un~ b/exercises/generics/.generics2.rs.un~ new file mode 100644 index 000000000..d50fef17c Binary files /dev/null and b/exercises/generics/.generics2.rs.un~ differ 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/generics1.rs~ b/exercises/generics/generics1.rs~ new file mode 100644 index 000000000..1f4fa4ac7 --- /dev/null +++ b/exercises/generics/generics1.rs~ @@ -0,0 +1,12 @@ +// generics1.rs +// +// This shopping list program isn't compiling! Use your knowledge of generics to +// fix it. +// +// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a +// hint. + +fn main() { + 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/generics/generics2.rs~ b/exercises/generics/generics2.rs~ new file mode 100644 index 000000000..b0cc651f5 --- /dev/null +++ b/exercises/generics/generics2.rs~ @@ -0,0 +1,32 @@ +// generics2.rs +// +// This powerful wrapper provides the ability to store a positive integer value. +// Rewrite it using generics so that it supports wrapping ANY type. +// +// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a +// hint. + +struct Wrapper { + value: T, +} + +impl Wrapper { + pub fn new(value: T) -> Self { + Wrapper { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn store_u32_in_wrapper() { + assert_eq!(Wrapper::new(42).value, 42); + } + + #[test] + fn store_str_in_wrapper() { + assert_eq!(Wrapper::new("Foo").value, "Foo"); + } +} diff --git a/exercises/hashmaps/.hashmaps1.rs.un~ b/exercises/hashmaps/.hashmaps1.rs.un~ new file mode 100644 index 000000000..449b22971 Binary files /dev/null and b/exercises/hashmaps/.hashmaps1.rs.un~ differ diff --git a/exercises/hashmaps/.hashmaps2.rs.un~ b/exercises/hashmaps/.hashmaps2.rs.un~ new file mode 100644 index 000000000..0953b4cf4 Binary files /dev/null and b/exercises/hashmaps/.hashmaps2.rs.un~ differ diff --git a/exercises/hashmaps/.hashmaps3.rs.un~ b/exercises/hashmaps/.hashmaps3.rs.un~ new file mode 100644 index 000000000..8b43e8e0b Binary files /dev/null and b/exercises/hashmaps/.hashmaps3.rs.un~ differ diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index 80829eaa6..04e53dd28 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -11,17 +11,18 @@ // 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); // TODO: Put more fruits in your basket here. + basket.insert(String::from("apple"), 2); + basket.insert(String::from("mango"), 2); basket } diff --git a/exercises/hashmaps/hashmaps1.rs~ b/exercises/hashmaps/hashmaps1.rs~ new file mode 100644 index 000000000..04e53dd28 --- /dev/null +++ b/exercises/hashmaps/hashmaps1.rs~ @@ -0,0 +1,45 @@ +// hashmaps1.rs +// +// A basket of fruits in the form of a hash map needs to be defined. The key +// represents the name of the fruit and the value represents how many of that +// particular fruit is in the basket. You have to put at least three different +// types of fruits (e.g apple, banana, mango) in the basket and the total count +// of all the fruits should be at least five. +// +// Make me compile and pass the tests! +// +// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a +// hint. + + +use std::collections::HashMap; + +fn fruit_basket() -> HashMap { + let mut basket = HashMap::new(); // TODO: declare your hash map here. + + // 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"), 2); + basket.insert(String::from("mango"), 2); + + basket +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn at_least_three_types_of_fruits() { + let basket = fruit_basket(); + assert!(basket.len() >= 3); + } + + #[test] + fn at_least_five_fruits() { + let basket = fruit_basket(); + assert!(basket.values().sum::() >= 5); + } +} diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a59256909..589862c84 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -14,7 +14,6 @@ // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; @@ -40,6 +39,12 @@ 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! + match fruit { + Fruit::Banana => basket.insert(Fruit::Banana, 1), + Fruit::Pineapple => basket.insert(Fruit::Pineapple, 3), + _ => continue, + }; + } } diff --git a/exercises/hashmaps/hashmaps2.rs~ b/exercises/hashmaps/hashmaps2.rs~ new file mode 100644 index 000000000..589862c84 --- /dev/null +++ b/exercises/hashmaps/hashmaps2.rs~ @@ -0,0 +1,98 @@ +// hashmaps2.rs +// +// We're collecting different fruits to bake a delicious fruit cake. For this, +// we have a basket, which we'll represent in the form of a hash map. The key +// represents the name of each fruit we collect and the value represents how +// many of that particular fruit we have collected. Three types of fruits - +// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You +// must add fruit to the basket so that there is at least one of each kind and +// more than 11 in total - we have a lot of mouths to feed. You are not allowed +// to insert any more of these fruits! +// +// Make me pass the tests! +// +// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a +// hint. + + +use std::collections::HashMap; + +#[derive(Hash, PartialEq, Eq)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = vec![ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // 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! + match fruit { + Fruit::Banana => basket.insert(Fruit::Banana, 1), + Fruit::Pineapple => basket.insert(Fruit::Pineapple, 3), + _ => continue, + }; + + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let mut basket = HashMap::::new(); + basket.insert(Fruit::Apple, 4); + basket.insert(Fruit::Mango, 2); + basket.insert(Fruit::Lychee, 5); + + basket + } + + #[test] + fn test_given_fruits_are_not_modified() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); + assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); + assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); + } + + #[test] + fn at_least_five_types_of_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count_fruit_kinds = basket.len(); + assert!(count_fruit_kinds >= 5); + } + + #[test] + fn greater_than_eleven_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count = basket.values().sum::(); + assert!(count > 11); + } + + #[test] + fn all_fruit_types_in_basket() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + for amount in basket.values() { + assert_ne!(amount, &0); + } + } +} diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 08e977c33..bfbc17ce0 100644 --- a/exercises/hashmaps/hashmaps3.rs +++ b/exercises/hashmaps/hashmaps3.rs @@ -14,7 +14,6 @@ // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; @@ -39,6 +38,29 @@ 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 !scores.contains_key(&team_1_name) && !scores.contains_key(&team_2_name) { + scores.insert(team_1_name, Team{goals_scored: team_1_score, goals_conceded: team_2_score}); + scores.insert(team_2_name, Team{goals_scored: team_2_score, goals_conceded: team_1_score}); + + } else if scores.contains_key(&team_1_name) && scores.contains_key(&team_2_name) { + scores.insert(team_1_name.clone(), Team{ goals_scored: scores.get(&team_1_name).unwrap().goals_scored + team_1_score , + goals_conceded: scores.get(&team_1_name).unwrap().goals_conceded + team_2_score ,}); + scores.insert(team_2_name.clone(), Team{ goals_scored: scores.get(&team_2_name).unwrap().goals_scored + team_2_score , + goals_conceded: scores.get(&team_2_name).unwrap().goals_conceded + team_1_score ,}); + } else if scores.contains_key(&team_1_name) && !scores.contains_key(&team_2_name) { + scores.insert(team_1_name.clone(), Team{ goals_scored: scores.get(&team_1_name).unwrap().goals_scored + team_1_score , + goals_conceded: scores.get(&team_1_name).unwrap().goals_conceded + team_2_score ,}); + scores.insert(team_2_name, Team{goals_scored: team_2_score, goals_conceded: team_1_score}); + + } else if scores.contains_key(&team_2_name) && !scores.contains_key(&team_1_name) { + scores.insert(team_2_name.clone(), Team{ goals_scored: scores.get(&team_2_name).unwrap().goals_scored + team_2_score , + goals_conceded: scores.get(&team_2_name).unwrap().goals_conceded + team_1_score ,}); + scores.insert(team_1_name, Team{goals_scored: team_1_score, goals_conceded: team_2_score}); + + } + } scores } diff --git a/exercises/hashmaps/hashmaps3.rs~ b/exercises/hashmaps/hashmaps3.rs~ new file mode 100644 index 000000000..1147bcc4b --- /dev/null +++ b/exercises/hashmaps/hashmaps3.rs~ @@ -0,0 +1,109 @@ +// hashmaps3.rs +// +// A list of scores (one per line) of a soccer match is given. Each line is of +// the form : ",,," +// Example: England,France,4,2 (England scored 4 goals, France 2). +// +// You have to build a scores table containing the name of the team, goals the +// team scored, and goals the team conceded. One approach to build the scores +// table is to use a Hashmap. The solution is partially written to use a +// Hashmap, complete it to pass the test. +// +// Make me pass the tests! +// +// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a +// hint. + + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +struct Team { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: String) -> HashMap { + // The name of the team is the key and its associated struct is the value. + let mut scores: HashMap = HashMap::new(); + let mut tmp_scores: HashMap = HashMap::new(); + + for r in results.lines() { + let v: Vec<&str> = r.split(',').collect(); + let team_1_name = v[0].to_string(); + let team_1_score: u8 = v[2].parse().unwrap(); + let team_2_name = v[1].to_string(); + let team_2_score: u8 = v[3].parse().unwrap(); + // TODO: Populate the scores table with details extracted from the + // current line. Keep in mind that goals scored by team_1 + // 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 !scores.contains_key(&team_1_name) && !scores.contains_key(&team_2_name) { + scores.insert(team_1_name, Team{goals_scored: team_1_score, goals_conceded: team_2_score}); + scores.insert(team_2_name, Team{goals_scored: team_2_score, goals_conceded: team_1_score}); + + } else if scores.contains_key(&team_1_name) && scores.contains_key(&team_2_name) { + scores.insert(team_1_name.clone(), Team{ goals_scored: scores.get(&team_1_name).unwrap().goals_scored + team_1_score , + goals_conceded: scores.get(&team_1_name).unwrap().goals_conceded + team_2_score ,}); + scores.insert(team_2_name.clone(), Team{ goals_scored: scores.get(&team_2_name).unwrap().goals_scored + team_2_score , + goals_conceded: scores.get(&team_2_name).unwrap().goals_conceded + team_1_score ,}); + } else if scores.contains_key(&team_1_name) && !scores.contains_key(&team_2_name) { + scores.insert(team_1_name.clone(), Team{ goals_scored: scores.get(&team_1_name).unwrap().goals_scored + team_1_score , + goals_conceded: scores.get(&team_1_name).unwrap().goals_conceded + team_2_score ,}); + scores.insert(team_2_name, Team{goals_scored: team_2_score, goals_conceded: team_1_score}); + + } else if scores.contains_key(&team_2_name) && !scores.contains_key(&team_1_name) { + scores.insert(team_2_name.clone(), Team{ goals_scored: scores.get(&team_2_name).unwrap().goals_scored + team_2_score , + goals_conceded: scores.get(&team_2_name).unwrap().goals_conceded + team_1_score ,}); + scores.insert(team_1_name, Team{goals_scored: team_1_score, goals_conceded: team_2_score}); + + } + + } + scores +} + +#[cfg(test)] +mod tests { + use super::*; + + fn get_results() -> String { + let results = "".to_string() + + "England,France,4,2\n" + + "France,Italy,3,1\n" + + "Poland,Spain,2,0\n" + + "Germany,England,2,1\n"; + results + } + + #[test] + fn build_scores() { + let scores = build_scores_table(get_results()); + + let mut keys: Vec<&String> = scores.keys().collect(); + keys.sort(); + assert_eq!( + keys, + vec!["England", "France", "Germany", "Italy", "Poland", "Spain"] + ); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(get_results()); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 5); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(get_results()); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 2); + } +} diff --git a/exercises/iterators/.iterators1.rs.un~ b/exercises/iterators/.iterators1.rs.un~ new file mode 100644 index 000000000..7c5764337 Binary files /dev/null and b/exercises/iterators/.iterators1.rs.un~ differ diff --git a/exercises/iterators/.iterators2.rs.un~ b/exercises/iterators/.iterators2.rs.un~ new file mode 100644 index 000000000..0305c0545 Binary files /dev/null and b/exercises/iterators/.iterators2.rs.un~ differ diff --git a/exercises/iterators/.iterators3.rs.un~ b/exercises/iterators/.iterators3.rs.un~ new file mode 100644 index 000000000..0e25a0ca6 Binary files /dev/null and b/exercises/iterators/.iterators3.rs.un~ differ diff --git a/exercises/iterators/.iterators4.rs.un~ b/exercises/iterators/.iterators4.rs.un~ new file mode 100644 index 000000000..80c776c6d Binary files /dev/null and b/exercises/iterators/.iterators4.rs.un~ differ diff --git a/exercises/iterators/.iterators5.rs.un~ b/exercises/iterators/.iterators5.rs.un~ new file mode 100644 index 000000000..f551bdb30 Binary files /dev/null and b/exercises/iterators/.iterators5.rs.un~ differ 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/iterators1.rs~ b/exercises/iterators/iterators1.rs~ new file mode 100644 index 000000000..2a89ae423 --- /dev/null +++ b/exercises/iterators/iterators1.rs~ @@ -0,0 +1,23 @@ +// iterators1.rs +// +// When performing operations on elements within a collection, iterators are +// essential. This module helps you get familiar with the structure of using an +// iterator and how to go through elements within an iterable collection. +// +// Make me compile by filling in the `???`s +// +// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a +// hint. + +fn main() { + let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; + + 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(), Some(&"custard apple")); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); + 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(), None); // TODO: Step 4 +} diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs index dda82a085..c1bd6c302 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,15 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => { + let mut s: String = String::new(); + let b = first.to_uppercase().to_string(); + s.push_str(&b); + let d = c.as_str(); + s.push_str(d); + s + + } } } @@ -24,7 +30,12 @@ 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![] + let mut s: Vec = Vec::new(); + for w in words { + let re = capitalize_first(w); + s.push(re); + } + s } // Step 3. @@ -32,7 +43,12 @@ 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() + let mut s: String = String::new(); + for w in words { + let re = capitalize_first(w); + s.push_str(&re); + } + s } #[cfg(test)] diff --git a/exercises/iterators/iterators2.rs~ b/exercises/iterators/iterators2.rs~ new file mode 100644 index 000000000..c1bd6c302 --- /dev/null +++ b/exercises/iterators/iterators2.rs~ @@ -0,0 +1,79 @@ +// iterators2.rs +// +// In this exercise, you'll learn some of the unique advantages that iterators +// can offer. Follow the steps to complete the exercise. +// +// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a +// hint. + +// Step 1. +// Complete the `capitalize_first` function. +// "hello" -> "Hello" +pub fn capitalize_first(input: &str) -> String { + let mut c = input.chars(); + match c.next() { + None => String::new(), + Some(first) => { + let mut s: String = String::new(); + let b = first.to_uppercase().to_string(); + s.push_str(&b); + let d = c.as_str(); + s.push_str(d); + s + + } + } +} + +// Step 2. +// Apply the `capitalize_first` function to a slice of string slices. +// Return a vector of strings. +// ["hello", "world"] -> ["Hello", "World"] +pub fn capitalize_words_vector(words: &[&str]) -> Vec { + let mut s: Vec = Vec::new(); + for w in words { + let re = capitalize_first(w); + s.push(re); + } + s +} + +// Step 3. +// Apply the `capitalize_first` function again to a slice of string slices. +// Return a single string. +// ["hello", " ", "world"] -> "Hello World" +pub fn capitalize_words_string(words: &[&str]) -> String { + let mut s: String = String::new(); + for w in words { + let re = capitalize_first(w); + s.push_str(&re); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(capitalize_first("hello"), "Hello"); + } + + #[test] + fn test_empty() { + assert_eq!(capitalize_first(""), ""); + } + + #[test] + fn test_iterate_string_vec() { + let words = vec!["hello", "world"]; + assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]); + } + + #[test] + fn test_iterate_into_string() { + let words = vec!["hello", " ", "world"]; + assert_eq!(capitalize_words_string(&words), "Hello World"); + } +} diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index 29fa23a3e..b008d7dc3 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,34 @@ 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 && a%b == 0 { + Ok(a/b) + } else if b == 0 { + Err(DivisionError::DivideByZero) + } else { + Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: a, + divisor: 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)); + let division_results: Result, DivisionError> = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results } // 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)); + let division_results: Vec<_> = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs~ b/exercises/iterators/iterators3.rs~ new file mode 100644 index 000000000..b008d7dc3 --- /dev/null +++ b/exercises/iterators/iterators3.rs~ @@ -0,0 +1,99 @@ +// iterators3.rs +// +// This is a bigger exercise than most of the others! You can do it! Here is +// your mission, should you choose to accept it: +// 1. Complete the divide function to get the first four tests to pass. +// 2. Get the remaining tests to pass by completing the result_with_list and +// list_of_results functions. +// +// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a +// hint. + +#[derive(Debug, PartialEq, Eq)] +pub enum DivisionError { + NotDivisible(NotDivisibleError), + DivideByZero, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct NotDivisibleError { + dividend: i32, + divisor: i32, +} + +// 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 { + if b != 0 && a%b == 0 { + Ok(a/b) + } else if b == 0 { + Err(DivisionError::DivideByZero) + } else { + Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: a, + divisor: 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() ->Result, DivisionError> { + let numbers = vec![27, 297, 38502, 81]; + let division_results: Result, DivisionError> = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results +} + +// 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() -> Vec> { + let numbers = vec![27, 297, 38502, 81]; + let division_results: Vec<_> = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + } + + #[test] + fn test_not_divisible() { + assert_eq!( + divide(81, 6), + Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: 81, + divisor: 6 + })) + ); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(format!("{:?}", result_with_list()), "Ok([1, 11, 1426, 3])"); + } + + #[test] + fn test_list_of_results() { + assert_eq!( + format!("{:?}", list_of_results()), + "[Ok(1), Ok(11), Ok(1426), Ok(3)]" + ); + } +} diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index 79e1692ba..30aaef155 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,20 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + if num == 0 { + 1 + } else if num == 1 { + 1 + } else if num == 2 { + 2 + } else { + let mut a: Vec = vec![]; + for n in 1..=num { + a.push(n.try_into().unwrap()); + } + let m = a.iter().fold(1, |acc, x| acc * x); + m.try_into().unwrap() + } } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs~ b/exercises/iterators/iterators4.rs~ new file mode 100644 index 000000000..30aaef155 --- /dev/null +++ b/exercises/iterators/iterators4.rs~ @@ -0,0 +1,54 @@ +// iterators4.rs +// +// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a +// hint. + +pub fn factorial(num: u64) -> u64 { + // Complete this function to return the factorial of num + // Do not use: + // - return + // Try not to use: + // - imperative style loops (for, while) + // - additional variables + // For an extra challenge, don't use: + // - recursion + // Execute `rustlings hint iterators4` for hints. + if num == 0 { + 1 + } else if num == 1 { + 1 + } else if num == 2 { + 2 + } else { + let mut a: Vec = vec![]; + for n in 1..=num { + a.push(n.try_into().unwrap()); + } + let m = a.iter().fold(1, |acc, x| acc * x); + m.try_into().unwrap() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(1, factorial(0)); + } + + #[test] + fn factorial_of_1() { + assert_eq!(1, factorial(1)); + } + #[test] + fn factorial_of_2() { + assert_eq!(2, factorial(2)); + } + + #[test] + fn factorial_of_4() { + assert_eq!(24, factorial(4)); + } +} diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index a062ee4c7..d471d92dc 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,23 @@ 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!(); + let mut complete_num = 0; + let mut some_num = 0; + let mut none_num = 0; + match value { + Progress::Complete => { + let _complete: Vec<_> = map.values().map(|x| if *x == Progress::Complete { complete_num += 1}).collect(); + complete_num + }, + Progress::Some => { + let _some: Vec<_> = map.values().map(|x| if *x == Progress::Some { some_num += 1}).collect(); + some_num + }, + Progress::None => { + let _none: Vec<_> = map.values().map(|x| if *x == Progress::None { none_num += 1}).collect(); + none_num + }, + } } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -54,7 +68,29 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + let mut complete_num = 0; + let mut some_num = 0; + let mut none_num = 0; + match value { + Progress::Complete => { + let complete: Vec<_> = collection.iter().map(|x| { + complete_num += count_iterator(x, Progress::Complete); + } ).collect(); + complete_num + }, + Progress::Some => { + let some: Vec<_> = collection.iter().map(|x| { + some_num += count_iterator(x, Progress::Some); + } ).collect(); + some_num + }, + Progress::None => { + let none: Vec<_> = collection.iter().map(|x| { + none_num += count_iterator(x, Progress::None); + } ).collect(); + none_num + }, + } } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs~ b/exercises/iterators/iterators5.rs~ new file mode 100644 index 000000000..d471d92dc --- /dev/null +++ b/exercises/iterators/iterators5.rs~ @@ -0,0 +1,192 @@ +// iterators5.rs +// +// Let's define a simple model to track Rustlings exercise progress. Progress +// will be modelled using a hash map. The name of the exercise is the key and +// the progress is the value. Two counting functions were created to count the +// number of exercises with a given progress. Recreate this counting +// functionality using iterators. Try not to use imperative loops (for, while). +// Only the two iterator methods (count_iterator and count_collection_iterator) +// need to be modified. +// +// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a +// hint. + +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Progress { + None, + Some, + Complete, +} + +fn count_for(map: &HashMap, value: Progress) -> usize { + let mut count = 0; + for val in map.values() { + if val == &value { + count += 1; + } + } + count +} + +fn count_iterator(map: &HashMap, value: Progress) -> usize { + // map is a hashmap with String keys and Progress values. + // map = { "variables1": Complete, "from_str": None, ... } + let mut complete_num = 0; + let mut some_num = 0; + let mut none_num = 0; + match value { + Progress::Complete => { + let _complete: Vec<_> = map.values().map(|x| if *x == Progress::Complete { complete_num += 1}).collect(); + complete_num + }, + Progress::Some => { + let _some: Vec<_> = map.values().map(|x| if *x == Progress::Some { some_num += 1}).collect(); + some_num + }, + Progress::None => { + let _none: Vec<_> = map.values().map(|x| if *x == Progress::None { none_num += 1}).collect(); + none_num + }, + } +} + +fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { + let mut count = 0; + for map in collection { + for val in map.values() { + if val == &value { + count += 1; + } + } + } + count +} + +fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { + // collection is a slice of hashmaps. + // collection = [{ "variables1": Complete, "from_str": None, ... }, + // { "variables2": Complete, ... }, ... ] + let mut complete_num = 0; + let mut some_num = 0; + let mut none_num = 0; + match value { + Progress::Complete => { + let complete: Vec<_> = collection.iter().map(|x| { + complete_num += count_iterator(x, Progress::Complete); + } ).collect(); + complete_num + }, + Progress::Some => { + let some: Vec<_> = collection.iter().map(|x| { + some_num += count_iterator(x, Progress::Some); + } ).collect(); + some_num + }, + Progress::None => { + let none: Vec<_> = collection.iter().map(|x| { + none_num += count_iterator(x, Progress::None); + } ).collect(); + none_num + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(3, count_iterator(&map, Progress::Complete)); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(1, count_iterator(&map, Progress::Some)); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(2, count_iterator(&map, Progress::None)); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; + for progress_state in progress_states { + assert_eq!( + count_for(&map, progress_state), + count_iterator(&map, progress_state) + ); + } + } + + #[test] + fn count_collection_complete() { + let collection = get_vec_map(); + assert_eq!( + 6, + count_collection_iterator(&collection, Progress::Complete) + ); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(1, count_collection_iterator(&collection, Progress::Some)); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(4, count_collection_iterator(&collection, Progress::None)); + } + + #[test] + fn count_collection_equals_for() { + let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; + let collection = get_vec_map(); + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state) + ); + } + } + + fn get_map() -> HashMap { + use Progress::*; + + let mut map = HashMap::new(); + map.insert(String::from("variables1"), Complete); + map.insert(String::from("functions1"), Complete); + map.insert(String::from("hashmap1"), Complete); + map.insert(String::from("arc1"), Some); + map.insert(String::from("as_ref_mut"), None); + map.insert(String::from("from_str"), None); + + map + } + + fn get_vec_map() -> Vec> { + use Progress::*; + + let map = get_map(); + + let mut other = HashMap::new(); + other.insert(String::from("variables2"), Complete); + other.insert(String::from("functions2"), Complete); + other.insert(String::from("if1"), Complete); + other.insert(String::from("from_into"), None); + other.insert(String::from("try_from_into"), None); + + vec![map, other] + } +} diff --git a/exercises/lifetimes/.lifetimes1.rs.un~ b/exercises/lifetimes/.lifetimes1.rs.un~ new file mode 100644 index 000000000..1bcf94821 Binary files /dev/null and b/exercises/lifetimes/.lifetimes1.rs.un~ differ diff --git a/exercises/lifetimes/.lifetimes2.rs.un~ b/exercises/lifetimes/.lifetimes2.rs.un~ new file mode 100644 index 000000000..51c9b4e0f Binary files /dev/null and b/exercises/lifetimes/.lifetimes2.rs.un~ differ diff --git a/exercises/lifetimes/.lifetimes3.rs.un~ b/exercises/lifetimes/.lifetimes3.rs.un~ new file mode 100644 index 000000000..eb4be0764 Binary files /dev/null and b/exercises/lifetimes/.lifetimes3.rs.un~ differ 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/lifetimes1.rs~ b/exercises/lifetimes/lifetimes1.rs~ new file mode 100644 index 000000000..5fe45ae0f --- /dev/null +++ b/exercises/lifetimes/lifetimes1.rs~ @@ -0,0 +1,25 @@ +// lifetimes1.rs +// +// The Rust compiler needs to know how to check whether supplied references are +// valid, so that it can let the programmer know if a reference is at risk of +// going out of scope before it is used. Remember, references are borrows and do +// not own their own data. What if their owner goes out of scope? +// +// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a +// hint. + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is '{}'", result); +} diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs index 4f3d8c185..b0dcb74ef 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 @@ -19,8 +17,8 @@ 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"); { - let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); } println!("The longest string is '{}'", result); diff --git a/exercises/lifetimes/lifetimes2.rs~ b/exercises/lifetimes/lifetimes2.rs~ new file mode 100644 index 000000000..33b5565fb --- /dev/null +++ b/exercises/lifetimes/lifetimes2.rs~ @@ -0,0 +1,25 @@ +// lifetimes2.rs +// +// So if the compiler is just validating the references passed to the annotated +// parameters and the return type, what do we need to change? +// +// Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a +// hint. + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +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()); + } + 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/lifetimes/lifetimes3.rs~ b/exercises/lifetimes/lifetimes3.rs~ new file mode 100644 index 000000000..aede10de3 --- /dev/null +++ b/exercises/lifetimes/lifetimes3.rs~ @@ -0,0 +1,19 @@ +// lifetimes3.rs +// +// Lifetimes are also needed when structs hold references. +// +// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a +// hint. + +struct Book<'a> { + author: &'a str, + title: &'a str, +} + +fn main() { + let name = String::from("Jill Smith"); + let title = String::from("Fish Flying"); + let book = Book { author: &name, title: &title }; + + println!("{} by {}", book.title, book.author); +} diff --git a/exercises/macros/.macros1.rs.un~ b/exercises/macros/.macros1.rs.un~ new file mode 100644 index 000000000..5499d62bf Binary files /dev/null and b/exercises/macros/.macros1.rs.un~ differ diff --git a/exercises/macros/.macros2.rs.un~ b/exercises/macros/.macros2.rs.un~ new file mode 100644 index 000000000..569c60502 Binary files /dev/null and b/exercises/macros/.macros2.rs.un~ differ diff --git a/exercises/macros/.macros3.rs.un~ b/exercises/macros/.macros3.rs.un~ new file mode 100644 index 000000000..88a1e2a06 Binary files /dev/null and b/exercises/macros/.macros3.rs.un~ differ diff --git a/exercises/macros/.macros4.rs.un~ b/exercises/macros/.macros4.rs.un~ new file mode 100644 index 000000000..926a50389 Binary files /dev/null and b/exercises/macros/.macros4.rs.un~ differ 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/macros1.rs~ b/exercises/macros/macros1.rs~ new file mode 100644 index 000000000..9d0edee3c --- /dev/null +++ b/exercises/macros/macros1.rs~ @@ -0,0 +1,14 @@ +// macros1.rs +// +// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a +// hint. + +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; +} + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index 788fc16a9..2d1ceb35a 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/macros2.rs~ b/exercises/macros/macros2.rs~ new file mode 100644 index 000000000..2d1ceb35a --- /dev/null +++ b/exercises/macros/macros2.rs~ @@ -0,0 +1,14 @@ +// macros2.rs +// +// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a +// hint. + +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..97a3d9806 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -5,14 +5,14 @@ // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - +use crate::macros::my_macro; mod macros { macro_rules! my_macro { () => { println!("Check out my macro!"); }; } + pub(crate) use my_macro; } fn main() { diff --git a/exercises/macros/macros3.rs~ b/exercises/macros/macros3.rs~ new file mode 100644 index 000000000..97a3d9806 --- /dev/null +++ b/exercises/macros/macros3.rs~ @@ -0,0 +1,20 @@ +// macros3.rs +// +// Make me compile, without taking the macro out of the module! +// +// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a +// hint. + +use crate::macros::my_macro; +mod macros { + macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + } + pub(crate) use my_macro; +} + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 71b45a095..a07a9ca53 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -3,16 +3,14 @@ // 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); - } + }; } fn main() { diff --git a/exercises/macros/macros4.rs~ b/exercises/macros/macros4.rs~ new file mode 100644 index 000000000..a07a9ca53 --- /dev/null +++ b/exercises/macros/macros4.rs~ @@ -0,0 +1,19 @@ +// macros4.rs +// +// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a +// hint. + +#[rustfmt::skip] +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + ($val:expr) => { + println!("Look at this other macro: {}", $val); + }; +} + +fn main() { + my_macro!(); + my_macro!(7777); +} diff --git a/exercises/modules/.modules1.rs.un~ b/exercises/modules/.modules1.rs.un~ new file mode 100644 index 000000000..b25f3db2a Binary files /dev/null and b/exercises/modules/.modules1.rs.un~ differ diff --git a/exercises/modules/.modules2.rs.un~ b/exercises/modules/.modules2.rs.un~ new file mode 100644 index 000000000..5bdefcc14 Binary files /dev/null and b/exercises/modules/.modules2.rs.un~ differ diff --git a/exercises/modules/.modules3.rs.un~ b/exercises/modules/.modules3.rs.un~ new file mode 100644 index 000000000..6c6814230 Binary files /dev/null and b/exercises/modules/.modules3.rs.un~ differ 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/modules1.rs~ b/exercises/modules/modules1.rs~ new file mode 100644 index 000000000..a26f5c45d --- /dev/null +++ b/exercises/modules/modules1.rs~ @@ -0,0 +1,20 @@ +// modules1.rs +// +// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a +// hint. + +mod sausage_factory { + // Don't let anybody outside of this module see this! + fn get_secret_recipe() -> String { + String::from("Ginger") + } + + pub fn make_sausage() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_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/modules2.rs~ b/exercises/modules/modules2.rs~ new file mode 100644 index 000000000..f5bd7cc08 --- /dev/null +++ b/exercises/modules/modules2.rs~ @@ -0,0 +1,32 @@ +// modules2.rs +// +// You can bring module paths into scopes and provide new names for them with +// the 'use' and 'as' keywords. Fix these 'use' statements to make the code +// compile. +// +// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a +// hint. + +mod delicious_snacks { + // TODO: Fix these use statements + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; + + mod fruits { + pub const PEAR: &'static str = "Pear"; + pub const APPLE: &'static str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &'static str = "Cucumber"; + pub const CARROT: &'static str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie + ); +} diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index f2bb05038..d216c7b58 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,10 +8,9 @@ // 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/modules/modules3.rs~ b/exercises/modules/modules3.rs~ new file mode 100644 index 000000000..d216c7b58 --- /dev/null +++ b/exercises/modules/modules3.rs~ @@ -0,0 +1,20 @@ +// modules3.rs +// +// You can use the 'use' keyword to bring module paths from modules from +// anywhere and especially from the Rust standard library into your scope. Bring +// SystemTime and UNIX_EPOCH from the std::time module. Bonus style points if +// you can do it with one line! +// +// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a +// hint. + + +// TODO: Complete this use statement +use std::time::{SystemTime, UNIX_EPOCH}; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/exercises/options/.options1.rs.un~ b/exercises/options/.options1.rs.un~ new file mode 100644 index 000000000..54c09713c Binary files /dev/null and b/exercises/options/.options1.rs.un~ differ diff --git a/exercises/options/.options2.rs.un~ b/exercises/options/.options2.rs.un~ new file mode 100644 index 000000000..5d90d23bc Binary files /dev/null and b/exercises/options/.options2.rs.un~ differ diff --git a/exercises/options/.options3.rs.un~ b/exercises/options/.options3.rs.un~ new file mode 100644 index 000000000..9eeb35189 Binary files /dev/null and b/exercises/options/.options3.rs.un~ differ diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs index e131b48b9..e004f60d8 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 >=0 && time_of_day < 22 { + Some(5) + } else if time_of_day >= 22 && time_of_day < 24 { + Some(0) + } else { + None + } } #[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, Some(5)); } } diff --git a/exercises/options/options1.rs~ b/exercises/options/options1.rs~ new file mode 100644 index 000000000..e004f60d8 --- /dev/null +++ b/exercises/options/options1.rs~ @@ -0,0 +1,43 @@ +// options1.rs +// +// Execute `rustlings hint options1` or use the `hint` watch subcommand for a +// hint. + +// 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 :( +fn maybe_icecream(time_of_day: u16) -> Option { + // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a + // 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 >=0 && time_of_day < 22 { + Some(5) + } else if time_of_day >= 22 && time_of_day < 24 { + Some(0) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_icecream() { + assert_eq!(maybe_icecream(9), Some(5)); + assert_eq!(maybe_icecream(10), Some(5)); + assert_eq!(maybe_icecream(23), Some(0)); + assert_eq!(maybe_icecream(22), Some(0)); + assert_eq!(maybe_icecream(25), None); + } + + #[test] + fn raw_value() { + // TODO: Fix this test. How do you get at the value contained in the + // Option? + let icecreams = maybe_icecream(12); + assert_eq!(icecreams, Some(5)); + } +} diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4d998e7d0..0d7147756 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -3,7 +3,6 @@ // Execute `rustlings hint options2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE #[cfg(test)] mod tests { @@ -13,8 +12,8 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { - assert_eq!(word, target); + if let word = optional_target { + assert_eq!(word, Some(target)); } } @@ -32,9 +31,12 @@ 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); + while let integer = optional_integers.pop() { + assert_eq!(integer, Some(Some(cursor))); cursor -= 1; + if cursor == 0 { + break; + } } assert_eq!(cursor, 0); diff --git a/exercises/options/options2.rs~ b/exercises/options/options2.rs~ new file mode 100644 index 000000000..0d7147756 --- /dev/null +++ b/exercises/options/options2.rs~ @@ -0,0 +1,44 @@ +// options2.rs +// +// Execute `rustlings hint options2` or use the `hint` watch subcommand for a +// hint. + + +#[cfg(test)] +mod tests { + #[test] + fn simple_option() { + let target = "rustlings"; + let optional_target = Some(target); + + // TODO: Make this an if let statement whose value is "Some" type + if let word = optional_target { + assert_eq!(word, Some(target)); + } + } + + #[test] + fn layered_option() { + let range = 10; + let mut optional_integers: Vec> = vec![None]; + + for i in 1..(range + 1) { + optional_integers.push(Some(i)); + } + + 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. + while let integer = optional_integers.pop() { + assert_eq!(integer, Some(Some(cursor))); + cursor -= 1; + if cursor == 0 { + break; + } + } + + assert_eq!(cursor, 0); + } +} 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/options/options3.rs~ b/exercises/options/options3.rs~ new file mode 100644 index 000000000..bca3cff56 --- /dev/null +++ b/exercises/options/options3.rs~ @@ -0,0 +1,19 @@ +// options3.rs +// +// Execute `rustlings hint options3` or use the `hint` watch subcommand for a +// hint. + +struct Point { + x: i32, + y: i32, +} + +fn main() { + let y: Option = Some(Point { x: 100, y: 200 }); + + match 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..54ded8b52 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -20,7 +20,6 @@ // // No hints this time! -// I AM NOT DONE pub enum Command { Uppercase, @@ -32,11 +31,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 = vec![]; for (string, command) in input.iter() { // TODO: Complete the function body. You can do it! + match command { + Command::Uppercase => { + let a = string.to_uppercase(); + output.push(a) + }, + Command::Trim => { + let b = string.trim().to_string(); + output.push(b) + }, + Command::Append(x) => { + let mut c: String = string.to_string(); + c.push_str(&"bar".repeat(*x)); + output.push(c.to_string()) + }, + } } output } @@ -45,7 +59,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/quiz2.rs~ b/exercises/quiz2.rs~ new file mode 100644 index 000000000..54ded8b52 --- /dev/null +++ b/exercises/quiz2.rs~ @@ -0,0 +1,78 @@ +// quiz2.rs +// +// This is a quiz for the following sections: +// - Strings +// - Vecs +// - Move semantics +// - Modules +// - Enums +// +// Let's build a little machine in the form of a function. As input, we're going +// to give a list of strings and commands. These commands determine what action +// is going to be applied to the string. It can either be: +// - Uppercase the string +// - Trim the string +// - Append "bar" to the string a specified amount of times +// The exact form of this will be: +// - The input is going to be a Vector of a 2-length tuple, +// the first element is the string, the second one is the command. +// - The output element is going to be a Vector of strings. +// +// No hints this time! + + +pub enum Command { + Uppercase, + Trim, + Append(usize), +} + +mod my_module { + use super::Command; + + // TODO: Complete the function signature! + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + // TODO: Complete the output declaration! + let mut output: Vec = vec![]; + for (string, command) in input.iter() { + // TODO: Complete the function body. You can do it! + match command { + Command::Uppercase => { + let a = string.to_uppercase(); + output.push(a) + }, + Command::Trim => { + let b = string.trim().to_string(); + output.push(b) + }, + Command::Append(x) => { + let mut c: String = string.to_string(); + c.push_str(&"bar".repeat(*x)); + output.push(c.to_string()) + }, + } + } + output + } +} + +#[cfg(test)] +mod tests { + // TODO: What do we need to import to have `transformer` in scope? + use super::my_module::transformer; + use super::Command; + + #[test] + fn it_works() { + let output = transformer(vec![ + ("hello".into(), Command::Uppercase), + (" all roads lead to rome! ".into(), Command::Trim), + ("foo".into(), Command::Append(1)), + ("bar".into(), Command::Append(5)), + ]); + assert_eq!(output[0], "HELLO"); + assert_eq!(output[1], "all roads lead to rome!"); + assert_eq!(output[2], "foobar"); + assert_eq!(output[3], "barbarbarbarbarbar"); + } +} diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 3b01d3132..d9cb974cd 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -16,15 +16,13 @@ // // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -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 +50,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/quiz3.rs~ b/exercises/quiz3.rs~ new file mode 100644 index 000000000..d9cb974cd --- /dev/null +++ b/exercises/quiz3.rs~ @@ -0,0 +1,62 @@ +// quiz3.rs +// +// This quiz tests: +// - Generics +// - Traits +// +// An imaginary magical school has a new report card generation system written +// in Rust! Currently the system only supports creating report cards where the +// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the +// school also issues alphabetical grades (A+ -> F-) and needs to be able to +// print both types of report card! +// +// Make the necessary code changes in the struct ReportCard and the impl block +// to support alphabetical report cards. Change the Grade in the second test to +// "A+" to show that your changes allow alphabetical grades. +// +// Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. + +pub struct ReportCard { + pub grade: T, + pub student_name: String, + pub student_age: u8, +} + +impl ReportCard { + pub fn print(&self) -> String { + format!("{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generate_numeric_report_card() { + let report_card = ReportCard { + grade: 2.1, + student_name: "Tom Wriggle".to_string(), + student_age: 12, + }; + assert_eq!( + report_card.print(), + "Tom Wriggle (12) - achieved a grade of 2.1" + ); + } + + #[test] + fn generate_alphabetic_report_card() { + // TODO: Make sure to change the grade here after you finish the exercise. + let report_card = ReportCard { + grade: "A+", + student_name: "Gary Plotter".to_string(), + student_age: 11, + }; + assert_eq!( + report_card.print(), + "Gary Plotter (11) - achieved a grade of A+" + ); + } +} diff --git a/exercises/smart_pointers/.arc1.rs.un~ b/exercises/smart_pointers/.arc1.rs.un~ new file mode 100644 index 000000000..bd76788c4 Binary files /dev/null and b/exercises/smart_pointers/.arc1.rs.un~ differ diff --git a/exercises/smart_pointers/.box1.rs.un~ b/exercises/smart_pointers/.box1.rs.un~ new file mode 100644 index 000000000..e75477f44 Binary files /dev/null and b/exercises/smart_pointers/.box1.rs.un~ differ diff --git a/exercises/smart_pointers/.cow1.rs.un~ b/exercises/smart_pointers/.cow1.rs.un~ new file mode 100644 index 000000000..ab783dfab Binary files /dev/null and b/exercises/smart_pointers/.cow1.rs.un~ differ diff --git a/exercises/smart_pointers/.rc1.rs.un~ b/exercises/smart_pointers/.rc1.rs.un~ new file mode 100644 index 000000000..23c54687d Binary files /dev/null and b/exercises/smart_pointers/.rc1.rs.un~ differ diff --git a/exercises/smart_pointers/arc1.rs b/exercises/smart_pointers/arc1.rs index 3526ddcb9..c7967d7c1 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(0); let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = Vec::new(); 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/arc1.rs~ b/exercises/smart_pointers/arc1.rs~ new file mode 100644 index 000000000..c7967d7c1 --- /dev/null +++ b/exercises/smart_pointers/arc1.rs~ @@ -0,0 +1,43 @@ +// arc1.rs +// +// In this exercise, we are given a Vec of u32 called "numbers" with values +// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this +// set of numbers within 8 different threads simultaneously. Each thread is +// going to get the sum of every eighth value, with an offset. +// +// The first thread (offset 0), will sum 0, 8, 16, ... +// The second thread (offset 1), will sum 1, 9, 17, ... +// The third thread (offset 2), will sum 2, 10, 18, ... +// ... +// The eighth thread (offset 7), will sum 7, 15, 23, ... +// +// Because we are using threads, our values need to be thread-safe. Therefore, +// we are using Arc. We need to make a change in each of the two TODOs. +// +// Make this code compile by filling in a value for `shared_numbers` where the +// first TODO comment is, and create an initial binding for `child_numbers` +// where the second TODO comment is. Try not to create any copies of the +// `numbers` Vec! +// +// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. + +#![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 = Arc::new(0); + let mut joinhandles = Vec::new(); + + for offset in 0..8 { + let child_numbers = Vec::new(); + joinhandles.push(thread::spawn(move || { + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); + println!("Sum of offset {} is {}", offset, sum); + })); + } + for handle in joinhandles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/exercises/smart_pointers/box1.rs b/exercises/smart_pointers/box1.rs index 513e7daa3..71733f612 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::Nil)) } #[cfg(test)] diff --git a/exercises/smart_pointers/box1.rs~ b/exercises/smart_pointers/box1.rs~ new file mode 100644 index 000000000..71733f612 --- /dev/null +++ b/exercises/smart_pointers/box1.rs~ @@ -0,0 +1,56 @@ +// box1.rs +// +// At compile time, Rust needs to know how much space a type takes up. This +// becomes problematic for recursive types, where a value can have as part of +// itself another value of the same type. To get around the issue, we can use a +// `Box` - a smart pointer used to store data on the heap, which also allows us +// to wrap a recursive type. +// +// The recursive type we're implementing in this exercise is the `cons list` - a +// data structure frequently found in functional programming languages. Each +// item in a cons list contains two elements: the value of the current item and +// the next item. The last item is a value called `Nil`. +// +// Step 1: use a `Box` in the enum definition to make the code compile +// Step 2: create both empty and non-empty cons lists by replacing `todo!()` +// +// Note: the tests should not be changed +// +// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. + +#[derive(PartialEq, Debug)] +pub enum List { + Cons(i32, Box), + Nil, +} + +fn main() { + println!("This is an empty cons list: {:?}", create_empty_list()); + println!( + "This is a non-empty cons list: {:?}", + create_non_empty_list() + ); +} + +pub fn create_empty_list() -> List { + List::Nil +} + +pub fn create_non_empty_list() -> List { + List::Cons(1, Box::new(List::Nil)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(List::Nil, create_empty_list()) + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()) + } +} diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs index 7ca916866..be901b888 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]> { @@ -49,6 +47,8 @@ mod tests { let mut input = Cow::from(&slice[..]); match abs_all(&mut input) { // TODO + Cow::Borrowed(_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -61,6 +61,8 @@ mod tests { let mut input = Cow::from(slice); match abs_all(&mut input) { // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -73,6 +75,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/cow1.rs~ b/exercises/smart_pointers/cow1.rs~ new file mode 100644 index 000000000..be901b888 --- /dev/null +++ b/exercises/smart_pointers/cow1.rs~ @@ -0,0 +1,82 @@ +// cow1.rs +// +// This exercise explores the Cow, or Clone-On-Write type. Cow is a +// clone-on-write smart pointer. It can enclose and provide immutable access to +// borrowed data, and clone the data lazily when mutation or ownership is +// required. The type is designed to work with general borrowed data via the +// Borrow trait. +// +// This exercise is meant to show you what to expect when passing data to Cow. +// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the +// TODO markers. +// +// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. + +use std::borrow::Cow; + +fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { + for i in 0..input.len() { + let v = input[i]; + if v < 0 { + // Clones into a vector if not already owned. + input.to_mut()[i] = -v; + } + } + input +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() -> Result<(), &'static str> { + // Clone occurs because `input` needs to be mutated. + let slice = [-1, 0, 1]; + let mut input = Cow::from(&slice[..]); + match abs_all(&mut input) { + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), + } + } + + #[test] + fn reference_no_mutation() -> Result<(), &'static str> { + // No clone occurs because `input` doesn't need to be mutated. + let slice = [0, 1, 2]; + let mut input = Cow::from(&slice[..]); + match abs_all(&mut input) { + // TODO + Cow::Borrowed(_) => Ok(()), + _ => Err("Expected owned value"), + } + } + + #[test] + fn owned_no_mutation() -> Result<(), &'static str> { + // We can also pass `slice` without `&` so Cow owns it directly. In this + // case no mutation occurs and thus also no clone, but the result is + // still owned because it was never borrowed or mutated. + 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"), + } + } + + #[test] + fn owned_mutation() -> Result<(), &'static str> { + // Of course this is also the case if a mutation does occur. In this + // case the call to `to_mut()` returns a reference to the same data as + // before. + 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/smart_pointers/rc1.rs~ b/exercises/smart_pointers/rc1.rs~ new file mode 100644 index 000000000..2ce1c54c5 --- /dev/null +++ b/exercises/smart_pointers/rc1.rs~ @@ -0,0 +1,105 @@ +// rc1.rs +// +// In this exercise, we want to express the concept of multiple owners via the +// Rc type. This is a model of our solar system - there is a Sun type and +// multiple Planets. The Planets take ownership of the sun, indicating that they +// revolve around the sun. +// +// Make this code compile by using the proper Rc primitives to express that the +// sun has multiple owners. +// +// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. + +use std::rc::Rc; + +#[derive(Debug)] +struct Sun {} + +#[derive(Debug)] +enum Planet { + Mercury(Rc), + Venus(Rc), + Earth(Rc), + Mars(Rc), + Jupiter(Rc), + Saturn(Rc), + Uranus(Rc), + Neptune(Rc), +} + +impl Planet { + fn details(&self) { + println!("Hi from {:?}!", self) + } +} + +fn main() { + let sun = Rc::new(Sun {}); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + let mercury = Planet::Mercury(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + mercury.details(); + + let venus = Planet::Venus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + venus.details(); + + let earth = Planet::Earth(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + earth.details(); + + let mars = Planet::Mars(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + mars.details(); + + let jupiter = Planet::Jupiter(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + jupiter.details(); + + // TODO + let saturn = Planet::Saturn(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + // TODO + let uranus = Planet::Uranus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + // TODO + let neptune = Planet::Neptune(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 9 references + neptune.details(); + + assert_eq!(Rc::strong_count(&sun), 9); + + drop(neptune); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + + drop(uranus); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + + drop(saturn); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + + drop(jupiter); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + + drop(mars); + 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.un~ b/exercises/strings/.strings1.rs.un~ new file mode 100644 index 000000000..0db528856 Binary files /dev/null and b/exercises/strings/.strings1.rs.un~ differ diff --git a/exercises/strings/.strings2.rs.un~ b/exercises/strings/.strings2.rs.un~ new file mode 100644 index 000000000..2a6a13306 Binary files /dev/null and b/exercises/strings/.strings2.rs.un~ differ diff --git a/exercises/strings/.strings3.rs.un~ b/exercises/strings/.strings3.rs.un~ new file mode 100644 index 000000000..969fa5b57 Binary files /dev/null and b/exercises/strings/.strings3.rs.un~ differ diff --git a/exercises/strings/.strings4.rs.un~ b/exercises/strings/.strings4.rs.un~ new file mode 100644 index 000000000..6a794376a Binary files /dev/null and b/exercises/strings/.strings4.rs.un~ differ diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index f50e1fa98..61f5fc4a9 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -5,7 +5,6 @@ // 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 +12,5 @@ fn main() { } fn current_favorite_color() -> String { - "blue" + String::from("blue") } diff --git a/exercises/strings/strings1.rs~ b/exercises/strings/strings1.rs~ new file mode 100644 index 000000000..7c0016f9c --- /dev/null +++ b/exercises/strings/strings1.rs~ @@ -0,0 +1,17 @@ +// strings1.rs +// +// Make me compile without changing the function signature! +// +// 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 { + String::from("blue") +} diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 4d95d16a1..10f0a73f2 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -5,11 +5,10 @@ // 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/strings2.rs~ b/exercises/strings/strings2.rs~ new file mode 100644 index 000000000..7b4d5ed15 --- /dev/null +++ b/exercises/strings/strings2.rs~ @@ -0,0 +1,20 @@ +// strings2.rs +// +// Make me compile without changing the function signature! +// +// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a +// hint. + + +fn main() { + let word = String::from("green"); // Try not changing this line :) + if is_a_color_word(word) { + println!("That is a color word I know!"); + } else { + println!("That is not a color word I know."); + } +} + +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs index b29f9325b..d96c373d5 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -3,21 +3,26 @@ // 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! - ??? + let a = input.trim(); + let b: String = String::from(a); + b + } fn compose_me(input: &str) -> String { // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? + let mut s = String::from(input); + s.push_str(" world!"); + s } fn replace_me(input: &str) -> String { // TODO: Replace "cars" in the string with "balloons"! - ??? + let b = input.replace("cars","balloons"); + b } #[cfg(test)] diff --git a/exercises/strings/strings3.rs~ b/exercises/strings/strings3.rs~ new file mode 100644 index 000000000..d96c373d5 --- /dev/null +++ b/exercises/strings/strings3.rs~ @@ -0,0 +1,50 @@ +// strings3.rs +// +// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a +// hint. + + +fn trim_me(input: &str) -> String { + // TODO: Remove whitespace from both ends of a string! + let a = input.trim(); + let b: String = String::from(a); + b + +} + +fn compose_me(input: &str) -> String { + // TODO: Add " world!" to the string! There's multiple ways to do this! + let mut s = String::from(input); + s.push_str(" world!"); + s +} + +fn replace_me(input: &str) -> String { + // TODO: Replace "cars" in the string with "balloons"! + let b = input.replace("cars","balloons"); + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_a_string() { + assert_eq!(trim_me("Hello! "), "Hello!"); + assert_eq!(trim_me(" What's up!"), "What's up!"); + assert_eq!(trim_me(" Hola! "), "Hola!"); + } + + #[test] + fn compose_a_string() { + assert_eq!(compose_me("Hello"), "Hello world!"); + assert_eq!(compose_me("Goodbye"), "Goodbye world!"); + } + + #[test] + fn replace_a_string() { + assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool"); + assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons"); + } +} diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index e8c54acc5..a368fa635 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -7,7 +7,6 @@ // // No hints this time! -// I AM NOT DONE fn string_slice(arg: &str) { println!("{}", arg); @@ -17,14 +16,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/strings/strings4.rs~ b/exercises/strings/strings4.rs~ new file mode 100644 index 000000000..a368fa635 --- /dev/null +++ b/exercises/strings/strings4.rs~ @@ -0,0 +1,29 @@ +// strings4.rs +// +// Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your +// task is to call one of these two functions on each value depending on what +// you think each value is. That is, add either `string_slice` or `string` +// before the parentheses on each line. If you're right, it will compile! +// +// No hints this time! + + +fn string_slice(arg: &str) { + println!("{}", arg); +} +fn string(arg: String) { + println!("{}", arg); +} + +fn main() { + 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.un~ b/exercises/structs/.structs1.rs.un~ new file mode 100644 index 000000000..335d61f79 Binary files /dev/null and b/exercises/structs/.structs1.rs.un~ differ diff --git a/exercises/structs/.structs2.rs.un~ b/exercises/structs/.structs2.rs.un~ new file mode 100644 index 000000000..562d4ece2 Binary files /dev/null and b/exercises/structs/.structs2.rs.un~ differ diff --git a/exercises/structs/.structs3.rs.un~ b/exercises/structs/.structs3.rs.un~ new file mode 100644 index 000000000..c1ff584ff Binary files /dev/null and b/exercises/structs/.structs3.rs.un~ differ diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs index 5fa5821c5..a8dd54a7a 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -5,10 +5,11 @@ // 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 */); @@ -23,7 +24,7 @@ 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); @@ -33,7 +34,7 @@ mod tests { #[test] fn tuple_structs() { // TODO: Instantiate a tuple struct! - // let green = + let green =(0, 255, 0); assert_eq!(green.0, 0); assert_eq!(green.1, 255); @@ -43,8 +44,8 @@ mod tests { #[test] fn unit_structs() { // TODO: Instantiate a unit-like struct! - // let unit_like_struct = - let message = format!("{:?}s are fun!", unit_like_struct); + let unit_like_struct = String::from("UnitLikeStruct"); + let message = format!("{}s are fun!", unit_like_struct); assert_eq!(message, "UnitLikeStructs are fun!"); } diff --git a/exercises/structs/structs1.rs~ b/exercises/structs/structs1.rs~ new file mode 100644 index 000000000..90f4e4fa2 --- /dev/null +++ b/exercises/structs/structs1.rs~ @@ -0,0 +1,54 @@ +// structs1.rs +// +// Address all the TODOs to make the tests pass! +// +// 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 */); + +#[derive(Debug)] +struct UnitLikeStruct; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classic_c_structs() { + // TODO: Instantiate a classic c struct! + let green = ColorClassicStruct{red: 0, green: 255, blue: 0}; + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + // TODO: Instantiate a tuple struct! + let green =(0, 255, 0); + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + // TODO: Instantiate a unit-like struct! + let unit_like_struct = String::from("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..38a856d66 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -5,8 +5,6 @@ // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(Debug)] struct Order { name: String, @@ -38,7 +36,15 @@ 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"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 1, + }; 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/structs2.rs~ b/exercises/structs/structs2.rs~ new file mode 100644 index 000000000..d0ef753af --- /dev/null +++ b/exercises/structs/structs2.rs~ @@ -0,0 +1,58 @@ +// structs2.rs +// +// Address all the TODOs to make the tests pass! +// +// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +#[derive(Debug)] +struct Order { + name: String, + year: u32, + made_by_phone: bool, + made_by_mobile: bool, + made_by_email: bool, + item_number: u32, + count: u32, +} + +fn create_order_template() -> Order { + Order { + name: String::from("Bob"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn your_order() { + let order_template = create_order_template(); + // TODO: Create your own order using the update syntax and template above! + let your_order = Order { + name: String::from("Hacker in Rust"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 1, + }; + 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); + assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile); + assert_eq!(your_order.made_by_email, order_template.made_by_email); + assert_eq!(your_order.item_number, order_template.item_number); + assert_eq!(your_order.count, 1); + } +} diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs index 4851317c5..ce8d131eb 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -7,7 +7,6 @@ // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE #[derive(Debug)] struct Package { @@ -29,12 +28,18 @@ impl Package { } } - fn is_international(&self) -> ??? { + fn is_international(&self) -> bool { // Something goes here... + if self.sender_country != self.recipient_country { + true + } else { + false + } } - fn get_fees(&self, cents_per_gram: i32) -> ??? { + fn get_fees(&self, cents_per_gram: i32) -> i32 { // Something goes here... + cents_per_gram * self.weight_in_grams } } diff --git a/exercises/structs/structs3.rs~ b/exercises/structs/structs3.rs~ new file mode 100644 index 000000000..f5241d5c0 --- /dev/null +++ b/exercises/structs/structs3.rs~ @@ -0,0 +1,92 @@ +// structs3.rs +// +// Structs contain data, but can also have logic. In this exercise we have +// defined the Package struct and we want to test some logic attached to it. +// Make the code compile and the tests pass! +// +// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +#[derive(Debug)] +struct Package { + sender_country: String, + recipient_country: String, + weight_in_grams: i32, +} + +impl Package { + fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package { + if weight_in_grams <= 0 { + panic!("Can not ship a weightless package.") + } else { + Package { + sender_country, + recipient_country, + weight_in_grams, + } + } + } + + fn is_international(&self) -> bool { + // Something goes here... + if self.sender_country != self.recipient_country { + true + } else { + false + } + } + + fn get_fees(&self, cents_per_gram: i32) -> i32 { + // Something goes here... + cents_per_gram * self.weight_in_grams + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn fail_creating_weightless_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Austria"); + + Package::new(sender_country, recipient_country, -2210); + } + + #[test] + fn create_international_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Russia"); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(package.is_international()); + } + + #[test] + fn create_local_package() { + let sender_country = String::from("Canada"); + let recipient_country = sender_country.clone(); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(!package.is_international()); + } + + #[test] + fn calculate_transport_fees() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Spain"); + + let cents_per_gram = 3; + + let package = Package::new(sender_country, recipient_country, 1500); + + assert_eq!(package.get_fees(cents_per_gram), 4500); + assert_eq!(package.get_fees(cents_per_gram * 2), 9000); + } +} diff --git a/exercises/tests/.build.rs.un~ b/exercises/tests/.build.rs.un~ new file mode 100644 index 000000000..94765ca7f Binary files /dev/null and b/exercises/tests/.build.rs.un~ differ diff --git a/exercises/tests/.tests1.rs.un~ b/exercises/tests/.tests1.rs.un~ new file mode 100644 index 000000000..4d1f31ee5 Binary files /dev/null and b/exercises/tests/.tests1.rs.un~ differ diff --git a/exercises/tests/.tests2.rs.un~ b/exercises/tests/.tests2.rs.un~ new file mode 100644 index 000000000..f07c71005 Binary files /dev/null and b/exercises/tests/.tests2.rs.un~ differ diff --git a/exercises/tests/.tests3.rs.un~ b/exercises/tests/.tests3.rs.un~ new file mode 100644 index 000000000..8e2c7ef63 Binary files /dev/null and b/exercises/tests/.tests3.rs.un~ differ diff --git a/exercises/tests/.tests4.rs.un~ b/exercises/tests/.tests4.rs.un~ new file mode 100644 index 000000000..400ee9a7f Binary files /dev/null and b/exercises/tests/.tests4.rs.un~ differ diff --git a/exercises/tests/.tests5.rs.un~ b/exercises/tests/.tests5.rs.un~ new file mode 100644 index 000000000..c7db33a77 Binary files /dev/null and b/exercises/tests/.tests5.rs.un~ differ diff --git a/exercises/tests/.tests6.rs.un~ b/exercises/tests/.tests6.rs.un~ new file mode 100644 index 000000000..c953db547 Binary files /dev/null and b/exercises/tests/.tests6.rs.un~ differ diff --git a/exercises/tests/.tests7.rs.un~ b/exercises/tests/.tests7.rs.un~ new file mode 100644 index 000000000..3093c279f Binary files /dev/null and b/exercises/tests/.tests7.rs.un~ differ diff --git a/exercises/tests/.tests8.rs.un~ b/exercises/tests/.tests8.rs.un~ new file mode 100644 index 000000000..f6232880b Binary files /dev/null and b/exercises/tests/.tests8.rs.un~ differ diff --git a/exercises/tests/.tests9.rs.un~ b/exercises/tests/.tests9.rs.un~ new file mode 100644 index 000000000..d404d955a Binary files /dev/null and b/exercises/tests/.tests9.rs.un~ differ 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..63efbd5e2 100644 --- a/exercises/tests/build.rs +++ b/exercises/tests/build.rs @@ -11,14 +11,13 @@ 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 +"{:?}", timestamp ); - println!("cargo:{}", your_command); + println!("cargo::rustc-env=TEST_FOO={}", 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 = "pass"; + println!("cargo::rustc-cfg=CFG=\"{}\"", your_command); } diff --git a/exercises/tests/build.rs~ b/exercises/tests/build.rs~ new file mode 100644 index 000000000..f4db107d4 --- /dev/null +++ b/exercises/tests/build.rs~ @@ -0,0 +1,23 @@ +//! This is the build script for both tests7 and tests8. +//! +//! You should modify this file to make both exercises pass. + +fn main() { + // In tests7, we should set up an environment variable + // called `TEST_FOO`. Print in the standard output to let + // Cargo do it. + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); // What's the use of this timestamp here? + let your_command = format!( +"{:?}", timestamp + ); + println!("cargo::rust-env=TEST_FOO={}", 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 = "pass"; + println!("cargo::rustc-cfg=CFG=\"{}\"", your_command); +} diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 810277ac3..79d91aabd 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!(1==1); } } diff --git a/exercises/tests/tests1.rs~ b/exercises/tests/tests1.rs~ new file mode 100644 index 000000000..79d91aabd --- /dev/null +++ b/exercises/tests/tests1.rs~ @@ -0,0 +1,19 @@ +// tests1.rs +// +// Tests are important to ensure that your code does what you think it should +// do. Tests can be run on this file with the following command: rustlings run +// tests1 +// +// This test has a problem with it -- make the test compile! Make the test pass! +// Make the test fail! +// +// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a +// hint. + +#[cfg(test)] +mod tests { + #[test] + fn you_can_assert() { + assert!(1==1); + } +} diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index f8024e9f2..ed6b4967f 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!(1, 1); } } diff --git a/exercises/tests/tests2.rs~ b/exercises/tests/tests2.rs~ new file mode 100644 index 000000000..ed6b4967f --- /dev/null +++ b/exercises/tests/tests2.rs~ @@ -0,0 +1,15 @@ +// tests2.rs +// +// This test has a problem with it -- make the test compile! Make the test pass! +// Make the test fail! +// +// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a +// hint. + +#[cfg(test)] +mod tests { + #[test] + fn you_can_assert_eq() { + assert_eq!(1, 1); + } +} 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/tests3.rs~ b/exercises/tests/tests3.rs~ new file mode 100644 index 000000000..bbd3834f5 --- /dev/null +++ b/exercises/tests/tests3.rs~ @@ -0,0 +1,27 @@ +// tests3.rs +// +// This test isn't testing our function -- make it do that in such a way that +// the test passes. Then write a second test that tests whether we get the +// result we expect to get when we call `is_even(5)`. +// +// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a +// hint. + +pub fn is_even(num: i32) -> bool { + num % 2 == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_true_when_even() { + assert!(is_even(4)); + } + + #[test] + fn is_false_when_odd() { + assert!(!is_even(5)); + } +} diff --git a/exercises/tests/tests4.rs b/exercises/tests/tests4.rs index 935d0db17..57dbc530b 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] 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/tests4.rs~ b/exercises/tests/tests4.rs~ new file mode 100644 index 000000000..57dbc530b --- /dev/null +++ b/exercises/tests/tests4.rs~ @@ -0,0 +1,48 @@ +// tests4.rs +// +// Make sure that we're testing for the correct conditions! +// +// Execute `rustlings hint tests4` or use the `hint` watch subcommand for a +// hint. + +struct Rectangle { + width: i32, + height: i32 +} + +impl Rectangle { + // Only change the test functions themselves + pub fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + panic!("Rectangle width and height cannot be negative!") + } + Rectangle {width, height} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + 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!(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..7847d6dc9 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,8 @@ 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") + let a = address as *mut u32; + *a = 0xAABBCCDD; } } diff --git a/exercises/tests/tests5.rs~ b/exercises/tests/tests5.rs~ new file mode 100644 index 000000000..7847d6dc9 --- /dev/null +++ b/exercises/tests/tests5.rs~ @@ -0,0 +1,50 @@ +// tests5.rs +// +// An `unsafe` in Rust serves as a contract. +// +// When `unsafe` is marked on an item declaration, such as a function, +// a trait or so on, it declares a contract alongside it. However, +// the content of the contract cannot be expressed only by a single keyword. +// Hence, its your responsibility to manually state it in the `# Safety` +// section of your documentation comment on the item. +// +// When `unsafe` is marked on a code block enclosed by curly braces, +// it declares an observance of some contract, such as the validity of some +// pointer parameter, the ownership of some memory address. However, like +// the text above, you still need to state how the contract is observed in +// the comment on the code block. +// +// NOTE: All the comments are for the readability and the maintainability of +// your code, while the Rust compiler hands its trust of soundness of your +// code to yourself! If you cannot prove the memory safety and soundness of +// your own code, take a step back and use safe code instead! +// +// Execute `rustlings hint tests5` or use the `hint` watch subcommand for a +// hint. + +/// # Safety +/// +/// The `address` must contain a mutable reference to a valid `u32` value. +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. + unsafe { + let a = address as *mut u32; + *a = 0xAABBCCDD; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + let mut t: u32 = 0x12345678; + // SAFETY: The address is guaranteed to be valid and contains + // a unique reference to a `u32` local variable. + unsafe { modify_by_address(&mut t as *mut u32 as usize) }; + assert!(t == 0xAABBCCDD); + } +} diff --git a/exercises/tests/tests6.rs b/exercises/tests/tests6.rs index 4c913779d..913e72d57 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,8 +18,8 @@ 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 } #[cfg(test)] @@ -31,7 +29,7 @@ mod tests { #[test] fn test_success() { - let data = Box::new(Foo { a: 1, b: None }); + let data = Box::new(Foo { a: 1, b: Some("hello".to_owned())}); let ptr_1 = &data.a as *const u128 as usize; // SAFETY: We pass an owned box of `Foo`. diff --git a/exercises/tests/tests6.rs~ b/exercises/tests/tests6.rs~ new file mode 100644 index 000000000..913e72d57 --- /dev/null +++ b/exercises/tests/tests6.rs~ @@ -0,0 +1,43 @@ +// tests6.rs +// +// In this example we take a shallow dive into the Rust standard library's +// unsafe functions. Fix all the question marks and todos to make the test +// pass. +// +// Execute `rustlings hint tests6` or use the `hint` watch subcommand for a +// hint. + +struct Foo { + a: u128, + b: Option, +} + +/// # Safety +/// +/// The `ptr` must contain an owned box of `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 { Box::from_raw(ptr) }; + ret +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + #[test] + fn test_success() { + let data = Box::new(Foo { a: 1, b: Some("hello".to_owned())}); + + let ptr_1 = &data.a as *const u128 as usize; + // SAFETY: We pass an owned box of `Foo`. + let ret = unsafe { raw_pointer_to_box(Box::into_raw(data)) }; + + let ptr_2 = &ret.a as *const u128 as usize; + + assert!(ptr_1 == ptr_2); + assert!(ret.b == Some("hello".to_owned())); + } +} 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/tests7.rs~ b/exercises/tests/tests7.rs~ new file mode 100644 index 000000000..02417a605 --- /dev/null +++ b/exercises/tests/tests7.rs~ @@ -0,0 +1,52 @@ +// tests7.rs +// +// When building packages, some dependencies can neither be imported in +// `Cargo.toml` nor be directly linked; some preprocesses varies from code +// generation to set-up package-specific configurations. +// +// Cargo does not aim to replace other build tools, but it does integrate +// with them with custom build scripts called `build.rs`. This file is +// usually placed in the root of the project, while in this case the same +// directory of this exercise. +// +// It can be used to: +// +// - Building a bundled C library. +// - Finding a C library on the host system. +// - Generating a Rust module from a specification. +// - Performing any platform-specific configuration needed for the crate. +// +// When setting up configurations, we can `println!` in the build script +// to tell Cargo to follow some instructions. The generic format is: +// +// println!("cargo:{}", your_command_in_string); +// +// Please see the official Cargo book about build scripts for more +// information: +// https://doc.rust-lang.org/cargo/reference/build-scripts.html +// +// In this exercise, we look for an environment variable and expect it to +// fall in a range. You can look into the testcase to find out the details. +// +// You should NOT modify this file. Modify `build.rs` in the same directory +// to pass this exercise. +// +// Execute `rustlings hint tests7` or use the `hint` watch subcommand for a +// hint. + +fn main() {} + +#[cfg(test)] +mod tests { + + #[test] + fn test_success() { + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let s = std::env::var("TEST_FOO").unwrap(); + let e: u64 = s.parse().unwrap(); + assert!(timestamp >= e && timestamp < e + 10); + } +} diff --git a/exercises/tests/tests8.rs b/exercises/tests/tests8.rs index ce7e35d8d..1f99e786d 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)] @@ -17,7 +15,6 @@ mod tests { #[test] fn test_success() { - #[cfg(feature = "pass")] return; panic!("no cfg set"); diff --git a/exercises/tests/tests8.rs~ b/exercises/tests/tests8.rs~ new file mode 100644 index 000000000..dfa37d7ac --- /dev/null +++ b/exercises/tests/tests8.rs~ @@ -0,0 +1,23 @@ +// tests8.rs +// +// This execrise shares `build.rs` with the previous exercise. +// You need to add some code to `build.rs` to make both this exercise and +// the previous one work. +// +// Execute `rustlings hint tests8` or use the `hint` watch subcommand for a +// hint. + +fn main() {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + #[cfg(feature = "pass")] + return; + + panic!("no cfg set"); + } +} diff --git a/exercises/tests/tests9.rs b/exercises/tests/tests9.rs index ea2a8ec02..3d67d2576 100644 --- a/exercises/tests/tests9.rs +++ b/exercises/tests/tests9.rs @@ -27,23 +27,24 @@ // // 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; 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 } + + use my_demo_function as my_demo_function_alias; } #[cfg(test)] mod tests { use super::*; + use my_demo_function as my_demo_function_alias; #[test] fn test_success() { diff --git a/exercises/tests/tests9.rs~ b/exercises/tests/tests9.rs~ new file mode 100644 index 000000000..dcccf9796 --- /dev/null +++ b/exercises/tests/tests9.rs~ @@ -0,0 +1,61 @@ +// tests9.rs +// +// Rust is highly capable of sharing FFI interfaces with C/C++ and other statically compiled +// languages, and it can even link within the code itself! It makes it through the extern +// block, just like the code below. +// +// The short string after the `extern` keyword indicates which ABI the externally imported +// function would follow. In this exercise, "Rust" is used, while other variants exists like +// "C" for standard C ABI, "stdcall" for the Windows ABI. +// +// The externally imported functions are declared in the extern blocks, with a semicolon to +// mark the end of signature instead of curly braces. Some attributes can be applied to those +// function declarations to modify the linking behavior, such as #[link_name = ".."] to +// modify the actual symbol names. +// +// If you want to export your symbol to the linking environment, the `extern` keyword can +// also be marked before a function definition with the same ABI string note. The default ABI +// for Rust functions is literally "Rust", so if you want to link against pure Rust functions, +// the whole extern term can be omitted. +// +// Rust mangles symbols by default, just like C++ does. To suppress this behavior and make +// those functions addressable by name, the attribute #[no_mangle] can be applied. +// +// In this exercise, your task is to make the testcase able to call the `my_demo_function` in +// module Foo. the `my_demo_function_alias` is an alias for `my_demo_function`, so the two +// line of code in the testcase should call the same function. +// +// You should NOT modify any existing code except for adding two lines of attributes. + +extern "Rust" { + fn my_demo_function(a: u32) -> u32; + 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 + } + + my_demo_function as my_demo_function_alias; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + // The externally imported functions are UNSAFE by default + // because of untrusted source of other languages. You may + // wrap them in safe Rust APIs to ease the burden of callers. + // + // SAFETY: We know those functions are aliases of a safe + // Rust function. + unsafe { + my_demo_function(123); + my_demo_function_alias(456); + } + } +} diff --git a/exercises/threads/.threads1.rs.un~ b/exercises/threads/.threads1.rs.un~ new file mode 100644 index 000000000..81862b923 Binary files /dev/null and b/exercises/threads/.threads1.rs.un~ differ diff --git a/exercises/threads/.threads2.rs.un~ b/exercises/threads/.threads2.rs.un~ new file mode 100644 index 000000000..e71abb472 Binary files /dev/null and b/exercises/threads/.threads2.rs.un~ differ diff --git a/exercises/threads/.threads3.rs.un~ b/exercises/threads/.threads3.rs.un~ new file mode 100644 index 000000000..2b71eaeed Binary files /dev/null and b/exercises/threads/.threads3.rs.un~ differ diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index 80b6def3e..47800da06 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}; @@ -27,6 +25,8 @@ fn main() { let mut results: Vec = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + let a = handle.join().unwrap(); + results.push(a) } if results.len() != 10 { diff --git a/exercises/threads/threads1.rs~ b/exercises/threads/threads1.rs~ new file mode 100644 index 000000000..47800da06 --- /dev/null +++ b/exercises/threads/threads1.rs~ @@ -0,0 +1,40 @@ +// threads1.rs +// +// This program spawns multiple threads that each run for at least 250ms, and +// each thread returns how much time they took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. +// +// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a +// hint. + +use std::thread; +use std::time::{Duration, Instant}; + +fn main() { + let mut handles = vec![]; + for i in 0..10 { + handles.push(thread::spawn(move || { + let start = Instant::now(); + thread::sleep(Duration::from_millis(250)); + println!("thread {} is complete", i); + start.elapsed().as_millis() + })); + } + + let mut results: Vec = vec![]; + for handle in handles { + // TODO: a struct is returned from thread::spawn, can you use it? + let a = handle.join().unwrap(); + results.push(a) + } + + if results.len() != 10 { + panic!("Oh no! All the spawned threads did not finish!"); + } + + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("thread {} took {}ms", i, result); + } +} diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d6..0a7eed564 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,24 +7,25 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::sync::Arc; +use std::sync::Mutex; use std::thread; use std::time::Duration; +#[derive(Debug)] 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 + let mut status_shared = status_shared.lock().unwrap(); status_shared.jobs_completed += 1; }); handles.push(handle); @@ -34,6 +35,6 @@ 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 {}", ???); } + println!("jobs completed {:?}", *status.lock().unwrap() ) ; } diff --git a/exercises/threads/threads2.rs~ b/exercises/threads/threads2.rs~ new file mode 100644 index 000000000..0a7eed564 --- /dev/null +++ b/exercises/threads/threads2.rs~ @@ -0,0 +1,40 @@ +// threads2.rs +// +// Building on the last exercise, we want all of the threads to complete their +// work but this time the spawned threads need to be in charge of updating a +// shared value: JobStatus.jobs_completed +// +// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a +// hint. + +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; +use std::time::Duration; + +#[derive(Debug)] +struct JobStatus { + jobs_completed: u32, +} + +fn main() { + 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 + let mut status_shared = status_shared.lock().unwrap(); + status_shared.jobs_completed += 1; + }); + handles.push(handle); + } + for handle in handles { + handle.join().unwrap(); + // 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 {:?}", *status.lock().unwrap() ) ; +} diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index db7d41ba6..ba34e64f7 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; @@ -31,10 +29,11 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { 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/threads/threads3.rs~ b/exercises/threads/threads3.rs~ new file mode 100644 index 000000000..ba34e64f7 --- /dev/null +++ b/exercises/threads/threads3.rs~ @@ -0,0 +1,65 @@ +// threads3.rs +// +// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a +// hint. + +use std::sync::mpsc; +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +struct Queue { + length: u32, + first_half: Vec, + second_half: Vec, +} + +impl Queue { + fn new() -> Self { + Queue { + length: 10, + first_half: vec![1, 2, 3, 4, 5], + second_half: vec![6, 7, 8, 9, 10], + } + } +} + +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); + tx1.send(*val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + for val in &qc2.second_half { + println!("sending {:?}", val); + tx.send(*val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); +} + +fn main() { + let (tx, rx) = mpsc::channel(); + let queue = Queue::new(); + let queue_length = queue.length; + + send_tx(queue, tx); + + let mut total_received: u32 = 0; + for received in rx { + println!("Got: {}", received); + total_received += 1; + } + + println!("total numbers received: {}", total_received); + assert_eq!(total_received, queue_length) +} diff --git a/exercises/traits/.traits1.rs.un~ b/exercises/traits/.traits1.rs.un~ new file mode 100644 index 000000000..6a58c703d Binary files /dev/null and b/exercises/traits/.traits1.rs.un~ differ diff --git a/exercises/traits/.traits2.rs.un~ b/exercises/traits/.traits2.rs.un~ new file mode 100644 index 000000000..6e8261803 Binary files /dev/null and b/exercises/traits/.traits2.rs.un~ differ diff --git a/exercises/traits/.traits3.rs.un~ b/exercises/traits/.traits3.rs.un~ new file mode 100644 index 000000000..59fad263c Binary files /dev/null and b/exercises/traits/.traits3.rs.un~ differ diff --git a/exercises/traits/.traits4.rs.un~ b/exercises/traits/.traits4.rs.un~ new file mode 100644 index 000000000..bd1c22fc2 Binary files /dev/null and b/exercises/traits/.traits4.rs.un~ differ diff --git a/exercises/traits/.traits5.rs.un~ b/exercises/traits/.traits5.rs.un~ new file mode 100644 index 000000000..bfa6abc36 Binary files /dev/null and b/exercises/traits/.traits5.rs.un~ differ diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 37dfcbfe8..f77c1fa0d 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -7,14 +7,17 @@ // 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(self) -> Self { + let mut a = self; + a.push_str("Bar"); + a + } } fn main() { diff --git a/exercises/traits/traits1.rs~ b/exercises/traits/traits1.rs~ new file mode 100644 index 000000000..f77c1fa0d --- /dev/null +++ b/exercises/traits/traits1.rs~ @@ -0,0 +1,45 @@ +// traits1.rs +// +// Time to implement some traits! Your task is to implement the trait +// `AppendBar` for the type `String`. The trait AppendBar has only one function, +// which appends "Bar" to any object implementing this trait. +// +// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a +// hint. + +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for String { + // TODO: Implement `AppendBar` for type `String`. + fn append_bar(self) -> Self { + let mut a = self; + a.push_str("Bar"); + a + } +} + +fn main() { + let s = String::from("Foo"); + let s = s.append_bar(); + println!("s: {}", s); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_foo_bar() { + assert_eq!(String::from("Foo").append_bar(), String::from("FooBar")); + } + + #[test] + fn is_bar_bar() { + assert_eq!( + String::from("").append_bar().append_bar(), + String::from("BarBar") + ); + } +} diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 3e35f8e11..6fc34222a 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 a = self; + let b = "Bar".to_string(); + a.push(b); + a + + } + +} #[cfg(test)] mod tests { diff --git a/exercises/traits/traits2.rs~ b/exercises/traits/traits2.rs~ new file mode 100644 index 000000000..6fc34222a --- /dev/null +++ b/exercises/traits/traits2.rs~ @@ -0,0 +1,37 @@ +// traits2.rs +// +// Your task is to implement the trait `AppendBar` for a vector of strings. To +// implement this trait, consider for a moment what it means to 'append "Bar"' +// to a vector of strings. +// +// No boiler plate code this time, you can do this! +// +// Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. + +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 a = self; + let b = "Bar".to_string(); + a.push(b); + a + + } + +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_vec_pop_eq_bar() { + let mut foo = vec![String::from("Foo")].append_bar(); + assert_eq!(foo.pop().unwrap(), String::from("Bar")); + assert_eq!(foo.pop().unwrap(), String::from("Foo")); + } +} diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 4e2b06b0e..2e0545427 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 { + "Some information".to_string() + } } struct SomeSoftware { diff --git a/exercises/traits/traits3.rs~ b/exercises/traits/traits3.rs~ new file mode 100644 index 000000000..2e0545427 --- /dev/null +++ b/exercises/traits/traits3.rs~ @@ -0,0 +1,42 @@ +// traits3.rs +// +// Your task is to implement the Licensed trait for both structures and have +// them return the same information without writing the same function twice. +// +// Consider what you can add to the Licensed trait. +// +// Execute `rustlings hint traits3` or use the `hint` watch subcommand for a +// hint. + +pub trait Licensed { + fn licensing_info(&self) -> String { + "Some information".to_string() + } +} + +struct SomeSoftware { + version_number: i32, +} + +struct OtherSoftware { + version_number: String, +} + +impl Licensed for SomeSoftware {} // Don't edit this line +impl Licensed for OtherSoftware {} // Don't edit this line + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_licensing_info_the_same() { + let licensing_info = String::from("Some information"); + let some_software = SomeSoftware { version_number: 1 }; + let other_software = OtherSoftware { + version_number: "v2.0.0".to_string(), + }; + assert_eq!(some_software.licensing_info(), licensing_info); + assert_eq!(other_software.licensing_info(), licensing_info); + } +} diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 4bda3e571..4f3e19dce 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: impl Licensed, software_two: impl Licensed) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits4.rs~ b/exercises/traits/traits4.rs~ new file mode 100644 index 000000000..4f3e19dce --- /dev/null +++ b/exercises/traits/traits4.rs~ @@ -0,0 +1,47 @@ +// traits4.rs +// +// Your task is to replace the '??' sections so the code compiles. +// +// Don't change any line other than the marked one. +// +// Execute `rustlings hint traits4` or use the `hint` watch subcommand for a +// hint. + +pub trait Licensed { + fn licensing_info(&self) -> String { + "some information".to_string() + } +} + +struct SomeSoftware {} + +struct OtherSoftware {} + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +// YOU MAY ONLY CHANGE THE NEXT LINE +fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool { + software.licensing_info() == software_two.licensing_info() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + let some_software = SomeSoftware {}; + let other_software = OtherSoftware {}; + + assert!(compare_license_types(some_software, other_software)); + } + + #[test] + fn compare_license_information_backwards() { + let some_software = SomeSoftware {}; + let other_software = OtherSoftware {}; + + assert!(compare_license_types(other_software, some_software)); + } +} diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index df1838054..07bb20682 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: impl SomeTrait + OtherTrait) -> bool { item.some_function() && item.other_function() } diff --git a/exercises/traits/traits5.rs~ b/exercises/traits/traits5.rs~ new file mode 100644 index 000000000..07bb20682 --- /dev/null +++ b/exercises/traits/traits5.rs~ @@ -0,0 +1,38 @@ +// traits5.rs +// +// Your task is to replace the '??' sections so the code compiles. +// +// Don't change any line other than the marked one. +// +// Execute `rustlings hint traits5` or use the `hint` watch subcommand for a +// hint. + +pub trait SomeTrait { + fn some_function(&self) -> bool { + true + } +} + +pub trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct {} +struct OtherStruct {} + +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +// YOU MAY ONLY CHANGE THE NEXT LINE +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { + item.some_function() && item.other_function() +} + +fn main() { + some_func(SomeStruct {}); + some_func(OtherStruct {}); +}