Skip to content

Commit

Permalink
resolve: some exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
zk committed Jun 15, 2023
1 parent f2de12a commit 9792f00
Show file tree
Hide file tree
Showing 52 changed files with 158 additions and 184 deletions.
3 changes: 1 addition & 2 deletions exercises/enums/enums1.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// enums1.rs
// 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
3 changes: 1 addition & 2 deletions exercises/enums/enums2.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// enums2.rs
// 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
12 changes: 10 additions & 2 deletions exercises/enums/enums3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
// Address all the TODOs to make the tests pass!
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

enum Message {
// TODO: implement the message variant types based on their usage below
ChangeColor(u8, u8, u8),
Echo(String),
Move(Point),
Quit
}

struct Point {
Expand Down Expand Up @@ -39,6 +41,12 @@ impl State {
fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants
// Remember: When passing a tuple as a function argument, you'll need extra parentheses: fn function((t, u, p, l, e))
match message {
Message::ChangeColor(x, y, z) => self.change_color((x, y, z)),
Message::Quit => self.quit(),
Message::Echo(s) => self.echo(s),
Message::Move(p) => self.move_position(p)
}
}
}

Expand Down
8 changes: 3 additions & 5 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@
// construct to `Option` 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.

// 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.".to_string())
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}

Expand Down
8 changes: 4 additions & 4 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@
// one is a lot shorter!
// 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>();

Ok(qty * cost_per_item + processing_fee)
match qty {
Ok(qty) => Ok(qty * cost_per_item + processing_fee),
Err(e) => Err(e),
}
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion exercises/functions/functions1.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// functions1.rs
// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE
fn call_me() {}

fn main() {
call_me();
Expand Down
4 changes: 1 addition & 3 deletions exercises/functions/functions2.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
// functions2.rs
// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
call_me(3);
}

fn call_me(num:) {
fn call_me(num: i32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
Expand Down
4 changes: 1 addition & 3 deletions exercises/functions/functions3.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// functions3.rs
// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
call_me();
call_me(3);
}

fn call_me(num: u32) {
Expand Down
4 changes: 1 addition & 3 deletions exercises/functions/functions4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
// in the signatures for now. If anything, this is a good way to peek ahead
// to future exercises!)

// I AM NOT DONE

fn main() {
let original_price = 51;
println!("Your sale price is {}", sale_price(original_price));
}

fn sale_price(price: i32) -> {
fn sale_price(price: i32) -> i32{
if is_even(price) {
price - 10
} else {
Expand Down
4 changes: 1 addition & 3 deletions exercises/functions/functions5.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
// functions5.rs
// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}

fn square(num: i32) -> i32 {
num * num;
num * num
}
6 changes: 3 additions & 3 deletions exercises/hashmaps/hashmaps1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
//
// 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);
basket.insert(String::from("cucumber"), 2);
basket.insert(String::from("waterlemon"), 2);

// TODO: Put more fruits in your basket here.

Expand Down
3 changes: 1 addition & 2 deletions exercises/hashmaps/hashmaps2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::collections::HashMap;

#[derive(Hash, PartialEq, Eq)]
Expand All @@ -39,6 +37,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!
basket.entry(fruit).or_insert(1);
}
}

Expand Down
24 changes: 21 additions & 3 deletions exercises/hashmaps/hashmaps3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::collections::HashMap;

// A structure to store team name and its goal details.
Expand All @@ -25,21 +23,41 @@ struct Team {
goals_conceded: u8,
}

impl Team {
fn new(name: String) -> Team {
Team{
name: name,
goals_scored: 0,
goals_conceded: 0,
}
}
}

fn build_scores_table(results: String) -> HashMap<String, Team> {
// The name of the team is the key and its associated struct is the value.
let mut scores: HashMap<String, Team> = 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_1_score: u8 = v[2].parse().unwrap();
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.
scores.entry(team_1_name.clone()).or_insert(Team::new(team_1_name.clone()));
scores.entry(team_2_name.clone()).or_insert(Team::new(team_2_name.clone()));
scores
.entry(team_1_name.clone())
.and_modify(|team| team.goals_scored += team_1_score)
.and_modify(|team| team.goals_conceded += team_2_score);
scores
.entry(team_2_name.clone())
.and_modify(|team| team.goals_scored += team_2_score)
.and_modify(|team| team.goals_conceded += team_1_score);
}
scores
}
Expand Down
7 changes: 5 additions & 2 deletions exercises/if/if1.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// if1.rs
// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
if a > b {
a
} else {
b
}
}

// Don't mind this for now :)
Expand Down
6 changes: 3 additions & 3 deletions exercises/if/if2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
// Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else if fizzish == "fuzz" {
"bar"
} else {
1
"baz"
}
}

Expand Down
2 changes: 0 additions & 2 deletions exercises/intro/intro1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
// when you change one of the lines below! Try adding a `println!` line, or try changing
// what it outputs in your terminal. Try removing a semicolon and see what happens!

// I AM NOT DONE

fn main() {
println!("Hello and");
println!(r#" welcome to... "#);
Expand Down
4 changes: 1 addition & 3 deletions exercises/intro/intro2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// Make the code print a greeting to the world.
// Execute `rustlings hint intro2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
println!("Hello {}!");
println!("Hello {}!", "world");
}
4 changes: 1 addition & 3 deletions exercises/modules/modules1.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
// modules1.rs
// 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!");
}
Expand Down
6 changes: 2 additions & 4 deletions exercises/modules/modules2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
// '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.

// 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";
Expand Down
4 changes: 1 addition & 3 deletions exercises/modules/modules3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
// 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.

// 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) {
Expand Down
6 changes: 2 additions & 4 deletions exercises/move_semantics/move_semantics1.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
// move_semantics1.rs
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
let vec0 = Vec::new();
let mut vec0 = Vec::new();

let vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(vec0);

println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

Expand Down
13 changes: 6 additions & 7 deletions exercises/move_semantics/move_semantics2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,27 @@
// vec0 has length 3 content `[22, 44, 66]`
// vec1 has length 4 content `[22, 44, 66, 88]`

// I AM NOT DONE

fn main() {
let vec0 = Vec::new();
let mut vec0 = Vec::new();

// Do not move the following line!
let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(&mut vec0);

// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);

vec1.push(88);

println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
fn fill_vec(vec: &mut Vec<i32>) -> Vec<i32> {
// let mut vec = vec;

vec.push(22);
vec.push(44);
vec.push(66);

vec
vec.to_vec()
}

0 comments on commit 9792f00

Please sign in to comment.