Compare commits

...

6 commits

Author SHA1 Message Date
suzkiee 6b66ce8025
Merge 6b2ceb59eb into 8d0aa11a35 2024-02-01 21:27:41 +00:00
Suzie Kim 6b2ceb59eb
Complete options exercises 2024-02-01 16:27:28 -05:00
Suzie Kim ec6bd80f6a
Complete quiz 2 2024-02-01 15:40:18 -05:00
Suzie Kim 6f2ce95f6e
Complete hashmaps exercise 2024-02-01 11:08:03 -05:00
Suzie Kim e527943d84
Complete modules excersises 2024-01-31 17:36:58 -05:00
Suzie Kim b63f6a6a9e
Complete strings exercises 2024-01-31 17:17:44 -05:00
14 changed files with 98 additions and 51 deletions

View file

@ -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,6 @@ fn main() {
}
fn current_favorite_color() -> String {
"blue"
// "blue".to_string() // can be used to make strings from different types (aka integers, floats, chars, etc.)
String::from("blue") // can only be used to make strings from &string(string slices)
}

View file

@ -5,11 +5,12 @@
// 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) {
// This needs to be a string slice because the function is expecting a string slice.
if is_a_color_word(&word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");

View file

@ -3,21 +3,31 @@
// 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!
???
input.trim().to_string()
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There's multiple ways to do this!
???
// let mut new_string = String::new();
// new_string.push_str(input);
// new_string.push_str(" world!");
// new_string
format!("{input} {}", "world!")
// let a = input.to_string();
// let b = " world!".to_string();
// a + &b
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
???
input.replace("cars", "balloons")
}
#[cfg(test)]

View file

@ -7,8 +7,6 @@
//
// No hints this time!
// I AM NOT DONE
fn string_slice(arg: &str) {
println!("{}", arg);
}
@ -17,14 +15,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()); // this is cloning
string_slice("nice weather".into()); // calls it self
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());
}

View file

@ -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!");
}

View file

@ -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";

View file

@ -8,10 +8,12 @@
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
// TODO: Complete this use statement
use ???
// The * is a glob operator. It imports all public items from the module.
// use std::time::*;
// You can also write a nested path to specify the public items you want to pull in.
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {

View file

@ -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<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"), 3);
basket.insert(String::from("pear"), 5);
basket
}

View file

@ -14,8 +14,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)]
@ -40,6 +38,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);
}
}

View file

@ -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 the goal details of a team.
@ -30,6 +28,7 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
for r in results.lines() {
let v: Vec<&str> = r.split(',').collect();
println!("result { }", r);
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();
@ -39,7 +38,23 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
// will be the number of goals conceded by 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
}

View file

@ -3,7 +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
@ -13,7 +12,13 @@ fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// 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 > 23 {
None
} else if time_of_day >= 22 {
Some(0)
} else {
Some(5)
}
}
#[cfg(test)]
@ -34,6 +39,10 @@ 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.unwrap(), 5);
}
}
// Option has two variants: None and Some
// Some is a tuple struct that wraps a value with type T
// None indicates failure or lack of value

View file

@ -3,8 +3,6 @@
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
#[cfg(test)]
mod tests {
#[test]
@ -13,16 +11,21 @@ mod tests {
let optional_target = Some(target);
// TODO: Make this an if let statement whose value is "Some" type
word = optional_target {
// This block is checking whether or not optional_target is a typen of Some(T)
// Since it is, it's binding the value of Some(target) to word.
// The result is word = Some(Some(target))
if let Some(word) = optional_target {
assert_eq!(word, target);
}
}
}
#[test]
fn layered_option() {
let range = 10;
let mut optional_integers: Vec<Option<i8>> = vec![None];
// Range is inclusive of the start and exclusive of the end.
for i in 1..(range + 1) {
optional_integers.push(Some(i));
}
@ -32,7 +35,8 @@ mod tests {
// TODO: make this a while let statement - remember that vector.pop also
// adds another layer of Option<T>. You can stack `Option<T>`s into
// while let and if let.
integer = optional_integers.pop() {
while let Some(Some(integer)) = optional_integers.pop() {
// Removes the last character for the vector and return it
assert_eq!(integer, cursor);
cursor -= 1;
}

View file

@ -13,7 +13,8 @@ struct Point {
fn main() {
let y: Option<Point> = Some(Point { x: 100, y: 200 });
match y {
match y { // &y can also be used here to borrow instead of moving ownership of y to the match expression
// ref is used during pattern matching.
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => panic!("no match!"),
}

View file

@ -20,8 +20,6 @@
//
// No hints this time!
// I AM NOT DONE
pub enum Command {
Uppercase,
Trim,
@ -32,11 +30,24 @@ mod my_module {
use super::Command;
// TODO: Complete the function signature!
pub fn transformer(input: ???) -> ??? {
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
// TODO: Complete the output declaration!
let mut output: ??? = vec![];
let mut output: Vec<String> = vec![];
for (string, command) in input.iter() {
// TODO: Complete the function body. You can do it!
match command {
Command::Uppercase => output.push(string.to_uppercase()),
Command::Trim => output.push(string.trim().to_string()),
Command::Append(count) => {
let mut new_string = string.clone();
// The star in front of count dereferences the value of count.
// This is necessary because the append method expects a usize, not a &usize.
for _ in 0..*count {
new_string.push_str("bar");
}
output.push(new_string)
}
}
}
output
}
@ -45,7 +56,7 @@ mod my_module {
#[cfg(test)]
mod tests {
// TODO: What do we need to import to have `transformer` in scope?
use ???;
use crate::my_module::transformer;
use super::Command;
#[test]