From b8bedd224f724c0d3197ac8031be3eb31134b3dc Mon Sep 17 00:00:00 2001 From: Stanislav Pankrashin Date: Wed, 22 Jun 2022 16:55:10 +1200 Subject: [PATCH] did some more --- exercises/option/option1.rs | 10 ++++---- exercises/option/option2.rs | 10 ++++---- exercises/option/option3.rs | 4 +--- exercises/quiz3.rs | 6 ++--- exercises/standard_library_types/arc1.rs | 6 ++--- exercises/standard_library_types/box1.rs | 9 ++++---- .../standard_library_types/iterators1.rs | 10 ++++---- .../standard_library_types/iterators2.rs | 18 +++++++++++---- .../standard_library_types/iterators3.rs | 23 +++++++++++++------ .../standard_library_types/iterators4.rs | 6 +++-- exercises/tests/tests1.rs | 4 +--- exercises/tests/tests2.rs | 4 +--- exercises/tests/tests3.rs | 6 ++--- exercises/traits/traits1.rs | 7 +++--- exercises/traits/traits2.rs | 11 ++++++--- 15 files changed, 70 insertions(+), 64 deletions(-) diff --git a/exercises/option/option1.rs b/exercises/option/option1.rs index 17cf4f60..1401de99 100644 --- a/exercises/option/option1.rs +++ b/exercises/option/option1.rs @@ -1,23 +1,21 @@ // option1.rs // Make me compile! Execute `rustlings hint option1` for hints -// I AM NOT DONE - // you can modify anything EXCEPT for this function's signature fn print_number(maybe_number: Option) { println!("printing: {}", maybe_number.unwrap()); } fn main() { - print_number(13); - print_number(99); + print_number(Some(13)); + print_number(Some(99)); - let mut numbers: [Option; 5]; + let mut numbers: [Option; 5] = [Some(0); 5]; for iter in 0..5 { let number_to_add: u16 = { ((iter * 1235) + 2) / (4 * 16) }; - numbers[iter as usize] = number_to_add; + numbers[iter as usize] = Some(number_to_add); } } diff --git a/exercises/option/option2.rs b/exercises/option/option2.rs index c6b83ece..ebe53eb8 100644 --- a/exercises/option/option2.rs +++ b/exercises/option/option2.rs @@ -1,16 +1,14 @@ // option2.rs // Make me compile! Execute `rustlings hint option2` for hints -// I AM NOT DONE - fn main() { let optional_word = Some(String::from("rustlings")); // TODO: Make this an if let statement whose value is "Some" type - word = optional_word { + if let word = optional_word != None { println!("The word is: {}", word); } else { println!("The optional word doesn't contain anything"); - } + }; let mut optional_integers_vec: Vec> = Vec::new(); for x in 1..10 { @@ -19,7 +17,7 @@ fn main() { // 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_vec.pop() { - println!("current value: {}", integer); + while let Some(integer) = optional_integers_vec.pop() { + println!("current value: {:?}", integer); } } diff --git a/exercises/option/option3.rs b/exercises/option/option3.rs index 045d2acb..cb983ec4 100644 --- a/exercises/option/option3.rs +++ b/exercises/option/option3.rs @@ -1,8 +1,6 @@ // option3.rs // Make me compile! Execute `rustlings hint option3` for hints -// I AM NOT DONE - struct Point { x: i32, y: i32, @@ -12,7 +10,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), _ => println!("no match"), } y; // Fix without deleting this line. diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index fae0eedb..913197fd 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -7,8 +7,6 @@ // we expect to get when we call `times_two` with a negative number. // No hints, you can do this :) -// I AM NOT DONE - pub fn times_two(num: i32) -> i32 { num * 2 } @@ -19,12 +17,12 @@ mod tests { #[test] fn returns_twice_of_positive_numbers() { - assert_eq!(times_two(4), ???); + assert_eq!(times_two(4), 8); } #[test] fn returns_twice_of_negative_numbers() { // TODO replace unimplemented!() with an assert for `times_two(-4)` - unimplemented!() + assert_eq!(times_two(-4), -8); } } diff --git a/exercises/standard_library_types/arc1.rs b/exercises/standard_library_types/arc1.rs index f60061e7..a4271757 100644 --- a/exercises/standard_library_types/arc1.rs +++ b/exercises/standard_library_types/arc1.rs @@ -18,19 +18,17 @@ // where the second TODO comment is. Try not to create any copies of the `numbers` Vec! // Execute `rustlings hint arc1` for hints :) -// 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> = Arc::from(numbers);// TODO let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = Arc::clone(&shared_numbers);// TODO joinhandles.push(thread::spawn(move || { let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum(); println!("Sum of offset {} is {}", offset, sum); diff --git a/exercises/standard_library_types/box1.rs b/exercises/standard_library_types/box1.rs index f312f3d6..ead6ddf2 100644 --- a/exercises/standard_library_types/box1.rs +++ b/exercises/standard_library_types/box1.rs @@ -16,11 +16,9 @@ // // Execute `rustlings hint box1` for hints :) -// I AM NOT DONE - #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } @@ -33,11 +31,12 @@ fn main() { } pub fn create_empty_list() -> List { - unimplemented!() + List::Nil } pub fn create_non_empty_list() -> List { - unimplemented!() + use List::Cons; + List::Cons(0, Box::new(Cons(1, Box::new(List::Nil)))) } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators1.rs b/exercises/standard_library_types/iterators1.rs index 5aa49b64..98cc1c80 100644 --- a/exercises/standard_library_types/iterators1.rs +++ b/exercises/standard_library_types/iterators1.rs @@ -8,17 +8,15 @@ // // Execute `rustlings hint iterators1` for hints :D -// 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/standard_library_types/iterators2.rs b/exercises/standard_library_types/iterators2.rs index 87b4eaa1..13c0052c 100644 --- a/exercises/standard_library_types/iterators2.rs +++ b/exercises/standard_library_types/iterators2.rs @@ -3,8 +3,6 @@ // can offer. Follow the steps to complete the exercise. // As always, there are hints if you execute `rustlings hint iterators2`! -// I AM NOT DONE - // Step 1. // Complete the `capitalize_first` function. // "hello" -> "Hello" @@ -12,7 +10,12 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => { + let mut new_string = first.to_uppercase().to_string(); + let remaining_str = c.as_str(); + new_string.push_str(remaining_str); + new_string + } } } @@ -21,7 +24,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 result_vec: Vec = vec![]; + + for word in words { + result_vec.push(capitalize_first(word)); + } + result_vec } // Step 3. @@ -29,7 +37,7 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + capitalize_words_vector(words).join("") } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators3.rs b/exercises/standard_library_types/iterators3.rs index 8c66c05b..5a35ac25 100644 --- a/exercises/standard_library_types/iterators3.rs +++ b/exercises/standard_library_types/iterators3.rs @@ -6,8 +6,6 @@ // list_of_results functions. // Execute `rustlings hint iterators3` to get some hints! -// I AM NOT DONE - #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { NotDivisible(NotDivisibleError), @@ -22,20 +20,31 @@ 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 {} +pub fn divide(a: i32, b: i32) -> Result { + if b == 0 { + return Err(DivisionError::DivideByZero) + } else if a % b != 0 { + return Err(DivisionError::NotDivisible(NotDivisibleError {dividend: a, divisor: b})) + } + return Ok(a / b) +} // Complete the function and return a value of the correct type so the test passes. // Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { +fn result_with_list() -> Result, DivisionError> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + 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/standard_library_types/iterators4.rs b/exercises/standard_library_types/iterators4.rs index 88862838..a4546cb4 100644 --- a/exercises/standard_library_types/iterators4.rs +++ b/exercises/standard_library_types/iterators4.rs @@ -1,7 +1,5 @@ // iterators4.rs -// I AM NOT DONE - pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num // Do not use: @@ -12,6 +10,10 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + match (1..num + 1).map(|x| x).reduce(|a, b| a * b) { + Some(result) => result, + None => panic!("something went really wrong"), + } } #[cfg(test)] diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 50586a19..005731fd 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -6,12 +6,10 @@ // This test has a problem with it -- make the test compile! Make the test // pass! Make the test fail! Execute `rustlings hint tests1` for hints :) -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index 0d981ad1..6bfcd091 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -2,12 +2,10 @@ // This test has a problem with it -- make the test compile! Make the test // pass! Make the test fail! Execute `rustlings hint tests2` for hints :) -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1, 1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 3424f940..a108b9cd 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -4,8 +4,6 @@ // we expect to get when we call `is_even(5)`. // Execute `rustlings hint tests3` for hints :) -// I AM NOT DONE - pub fn is_even(num: i32) -> bool { num % 2 == 0 } @@ -16,11 +14,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(2)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(is_even(3) == false); } } diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 15e08f24..ad161947 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -8,14 +8,15 @@ // which appends "Bar" to any object // implementing this trait. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { - //Add your code here + fn append_bar(mut self) -> Self { + self.push_str("Bar"); + self + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 916c3c4b..4556534b 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -10,21 +10,26 @@ // No boiler plate code this time, // you can do this! -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } //TODO: Add your code here +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + self.push(String::from("Bar")); + self + } +} + #[cfg(test)] mod tests { use super::*; #[test] fn is_vec_pop_eq_bar() { - let mut foo = vec![String::from("Foo")].append_bar(); + let mut foo: Vec = vec![String::from("Foo")].append_bar(); assert_eq!(foo.pop().unwrap(), String::from("Bar")); assert_eq!(foo.pop().unwrap(), String::from("Foo")); }