From b84ba2b903789630e6c9123504d2e0013077ba82 Mon Sep 17 00:00:00 2001 From: ben1009 Date: Fri, 17 Feb 2023 00:27:55 +0800 Subject: [PATCH] done till exercises/threads/threads1 --- exercises/error_handling/README.md | 2 +- exercises/iterators/iterators1.rs | 12 +++++------- exercises/iterators/iterators2.rs | 8 +++----- exercises/iterators/iterators3.rs | 25 +++++++++++++++++++++---- exercises/iterators/iterators4.rs | 5 +++-- exercises/iterators/iterators5.rs | 6 ++---- exercises/lifetimes/README.md | 6 +++--- exercises/lifetimes/lifetimes1.rs | 4 +--- exercises/lifetimes/lifetimes2.rs | 4 +--- exercises/lifetimes/lifetimes3.rs | 13 +++++++------ exercises/quiz3.rs | 16 +++++++++------- exercises/tests/tests1.rs | 4 +--- exercises/tests/tests2.rs | 4 +--- exercises/tests/tests3.rs | 6 ++---- 14 files changed, 60 insertions(+), 55 deletions(-) diff --git a/exercises/error_handling/README.md b/exercises/error_handling/README.md index a87a45f4..3b21f2b7 100644 --- a/exercises/error_handling/README.md +++ b/exercises/error_handling/README.md @@ -1,6 +1,6 @@ # Error handling -Most errors aren’t serious enough to require the program to stop entirely. +Most errors aren’t serious enough to require the program to stop entirely. Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process. diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs index 0379c6bb..626a8524 100644 --- a/exercises/iterators/iterators1.rs +++ b/exercises/iterators/iterators1.rs @@ -8,17 +8,15 @@ // // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -fn main () { +fn main() { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2 assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3 assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 + assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4 } diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs index 29c53afb..d9d5d07f 100644 --- a/exercises/iterators/iterators2.rs +++ b/exercises/iterators/iterators2.rs @@ -3,8 +3,6 @@ // can offer. Follow the steps to complete the exercise. // 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" @@ -12,7 +10,7 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => first.to_uppercase().to_string() + c.as_str(), } } @@ -21,7 +19,7 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + words.iter().map(|w| capitalize_first(w)).collect() } // Step 3. @@ -29,7 +27,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() + words.iter().map(|w| capitalize_first(w)).collect() } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index c97a6258..fa149ff8 100644 --- a/exercises/iterators/iterators3.rs +++ b/exercises/iterators/iterators3.rs @@ -6,7 +6,7 @@ // list_of_results functions. // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +use std::error::Error; #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { @@ -23,21 +23,38 @@ pub struct NotDivisibleError { // Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. pub fn divide(a: i32, b: i32) -> Result { - todo!(); + if b == 0 { + return Err(DivisionError::DivideByZero); + } + if a % b == 0 { + return Ok(a / b); + } + + 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)); + // https://doc.rust-lang.org/std/result/enum.Result.html#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E-for-Result%3CV%2C%20E%3E + division_results.collect() } // Complete the function and return a value of the correct type so the test passes. // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-FromIterator%3CT%3E-for-Vec%3CT%2C%20Global%3E + division_results.collect() + // let mut v = vec![]; + // division_results.for_each(|n| v.push(n)); + // v } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index a02470ec..59bd44aa 100644 --- a/exercises/iterators/iterators4.rs +++ b/exercises/iterators/iterators4.rs @@ -1,8 +1,6 @@ // iterators4.rs // 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: @@ -13,6 +11,9 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + + (1..=num).fold(1, |ret, n| ret * n) + // (1..=num).product() } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index 0593d123..f1852450 100644 --- a/exercises/iterators/iterators5.rs +++ b/exercises/iterators/iterators5.rs @@ -10,8 +10,6 @@ // // Make the code compile and the tests pass. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Clone, Copy, PartialEq, Eq)] @@ -34,7 +32,7 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + map.values().filter(|v| *v == &value).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -53,7 +51,7 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + collection.iter().map(|v| count_iterator(v, value)).sum() } #[cfg(test)] diff --git a/exercises/lifetimes/README.md b/exercises/lifetimes/README.md index 72befb3e..e7d8be9a 100644 --- a/exercises/lifetimes/README.md +++ b/exercises/lifetimes/README.md @@ -3,12 +3,12 @@ Lifetimes tell the compiler how to check whether references live long enough to be valid in any given situation. For example lifetimes say "make sure parameter 'a' lives as long as parameter 'b' so that the return -value is valid". +value is valid". -They are only necessary on borrows, i.e. references, +They are only necessary on borrows, i.e. references, since copied parameters or moves are owned in their scope and cannot be referenced outside. Lifetimes mean that calling code of e.g. functions -can be checked to make sure their arguments are valid. Lifetimes are +can be checked to make sure their arguments are valid. Lifetimes are restrictive of their callers. ## Further information diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs index 0236470d..a12d3f5b 100644 --- a/exercises/lifetimes/lifetimes1.rs +++ b/exercises/lifetimes/lifetimes1.rs @@ -7,9 +7,7 @@ // // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -fn longest(x: &str, y: &str) -> &str { +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs index b48feabc..1d739e35 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 @@ -22,6 +20,6 @@ fn main() { { let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); + println!("The longest string is '{}'", result); } - println!("The longest string is '{}'", result); } diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs index ea483708..c6f51998 100644 --- a/exercises/lifetimes/lifetimes3.rs +++ b/exercises/lifetimes/lifetimes3.rs @@ -4,17 +4,18 @@ // // 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() { let name = String::from("Jill Smith"); let title = String::from("Fish Flying"); - let book = Book { author: &name, title: &title }; + let book = Book { + author: &name, + title: &title, + }; println!("{} by {}", book.title, book.author); } diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 15dc4699..84d07901 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -14,18 +14,20 @@ // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +use std::fmt::Display; -pub struct ReportCard { - pub grade: f32, +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade + ) } } @@ -50,7 +52,7 @@ mod tests { fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+".to_string(), student_name: "Gary Plotter".to_string(), student_age: 11, }; diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 8b6ea374..479f182b 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -7,12 +7,10 @@ // pass! Make the test fail! // Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index a5ac15b1..e0d59256 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -3,12 +3,10 @@ // pass! Make the test fail! // Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1, 1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 196a81a0..82430358 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` or use the `hint` watch subcommand for a hint. -// 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(4)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(!is_even(5)); } }