Skip to content

Commit

Permalink
finish 30-80
Browse files Browse the repository at this point in the history
  • Loading branch information
陈羿华 committed Dec 9, 2024
1 parent c8e183f commit 77f31a4
Show file tree
Hide file tree
Showing 50 changed files with 187 additions and 134 deletions.
5 changes: 4 additions & 1 deletion exercises/enums/enums1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
5 changes: 4 additions & 1 deletion exercises/enums/enums2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: i32, y: i32},
Echo(String),
ChangeColor(i32, i32, i32),
Quit,
}

impl Message {
Expand Down
11 changes: 10 additions & 1 deletion exercises/enums/enums3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
// 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
Move(Point),
Echo(String),
ChangeColor(i32, i32, i32),
Quit,
}

struct Point {
Expand Down Expand Up @@ -43,6 +46,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(r, g, b) => self.change_color((r as u8, g as u8, b as u8)),
Message::Quit => self.quit(),
Message::Echo(s) => self.echo(s),
Message::Move(p) => self.move_position(p),
}
}
}

Expand Down
7 changes: 3 additions & 4 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@
// 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<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
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))
}
}

Expand Down
3 changes: 1 addition & 2 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@
// 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<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();
let qty = item_quantity.parse::<i32>()?;

Ok(qty * cost_per_item + processing_fee)
}
Expand Down
5 changes: 3 additions & 2 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::num::ParseIntError;

fn main() {
fn main() -> Result<(), ParseIntError> {
let mut tokens = 100;
let pretend_user_input = "8";

Expand All @@ -23,6 +22,8 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}

Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
6 changes: 5 additions & 1 deletion exercises/error_handling/errors4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +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);
Expand All @@ -17,6 +16,11 @@ enum CreationError {
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
if value < 0 {
return Err(CreationError::Negative);
} else if value == 0 {
return Err(CreationError::Zero);
}
Ok(PositiveNonzeroInteger(value as u64))
}
}
Expand Down
3 changes: 1 addition & 2 deletions exercises/error_handling/errors5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,13 @@
// 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<dyn ???>> {
fn main() -> Result<(), Box<dyn error::Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Expand Down
7 changes: 5 additions & 2 deletions exercises/error_handling/errors6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::num::ParseIntError;

Expand All @@ -26,12 +25,16 @@ 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<PositiveNonzeroInteger, ParsePosNonzeroError> {
// 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().unwrap();
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}

Expand Down
3 changes: 1 addition & 2 deletions exercises/generics/generics1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
// 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");
}
9 changes: 4 additions & 5 deletions exercises/generics/generics2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

struct Wrapper {
value: u32,
struct Wrapper<T> {
value: T,
}

impl Wrapper {
pub fn new(value: u32) -> Self {
impl <T> Wrapper<T> {
pub fn new(value: T) -> Self {
Wrapper { value }
}
}
Expand Down
6 changes: 4 additions & 2 deletions exercises/hashmaps/hashmaps1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@
// 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<String, u32> {
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"), 1);
basket.insert(String::from("orange"), 2);

basket
}

Expand Down
2 changes: 1 addition & 1 deletion exercises/hashmaps/hashmaps2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -40,6 +39,7 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
// 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!
let v = basket.entry(fruit).or_insert(1);
}
}

Expand Down
7 changes: 6 additions & 1 deletion exercises/hashmaps/hashmaps3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -39,6 +38,12 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
// will be the number of goals conceded from team_2, and similarly
// goals scored by team_2 will be the number of goals conceded by
// team_1.
let team_1 = scores.entry(team_1_name).or_insert(Team { goals_scored: 0, goals_conceded: 0 });
team_1.goals_scored += team_1_score;
team_1.goals_conceded += team_2_score;
let team_2 = scores.entry(team_2_name).or_insert(Team { goals_scored: 0, goals_conceded: 0 });
team_2.goals_scored += team_2_score;
team_2.goals_conceded += team_1_score;
}
scores
}
Expand Down
9 changes: 4 additions & 5 deletions exercises/iterators/iterators1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@
// 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
}
8 changes: 4 additions & 4 deletions exercises/iterators/iterators2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +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.
Expand All @@ -15,7 +14,7 @@ pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => ???,
Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
}
}

Expand All @@ -24,15 +23,16 @@ pub fn capitalize_first(input: &str) -> String {
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![]
words.iter().map(|word| capitalize_first(word)).collect()
}

// 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 {
String::new()
// String::new()
words.iter().map(|word| capitalize_first(word)).collect::<Vec<String>>().join("")
}

#[cfg(test)]
Expand Down
20 changes: 14 additions & 6 deletions exercises/iterators/iterators3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +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 {
Expand All @@ -26,23 +25,32 @@ pub struct NotDivisibleError {
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
todo!();
// todo!();
if b == 0 {
return Err(DivisionError::DivideByZero);
}
if a % b != 0 {
return Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b }));
}
Ok(a / b)
}

// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> () {
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect::<Result<Vec<i32>, DivisionError>>();
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<Result<i32, DivisionError>> {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect::<Vec<Result<i32, DivisionError>>>();
division_results
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion exercises/iterators/iterators4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +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
Expand All @@ -15,6 +14,7 @@ pub fn factorial(num: u64) -> u64 {
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
(1..=num).fold(1, |acc, x| acc * x)
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 77f31a4

Please sign in to comment.