More exercises

This commit is contained in:
Yuhua Mai 2020-05-16 00:13:23 -07:00
parent 0a7eaaf9d0
commit 58fc67525b
11 changed files with 34 additions and 30 deletions

2
.gitignore vendored
View file

@ -5,3 +5,5 @@ target/
*.pdb *.pdb
exercises/clippy/Cargo.toml exercises/clippy/Cargo.toml
exercises/clippy/Cargo.lock exercises/clippy/Cargo.lock
.idea

View file

@ -4,12 +4,11 @@
// //
// Execute `rustlings hint clippy1` for hints :) // Execute `rustlings hint clippy1` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let x = 1.2331f64; let x = 1.2331f64;
let y = 1.2332f64; let y = 1.2332f64;
if y != x { if (y - x).abs() > 0.0001 {
println!("Success!"); println!("Success!");
} }
} }

View file

@ -1,12 +1,11 @@
// clippy2.rs // clippy2.rs
// Make me compile! Execute `rustlings hint clippy2` for hints :) // Make me compile! Execute `rustlings hint clippy2` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let mut res = 42; let mut res = 42;
let option = Some(12); let option = Some(12);
for x in option { if let Some(x) = option {
res += x; res += x;
} }
println!("{}", res); println!("{}", res);

View file

@ -6,14 +6,13 @@
// this function to have. // this function to have.
// Execute `rustlings hint errors1` for hints! // Execute `rustlings hint errors1` for hints!
// 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.len() > 0 { if name.len() > 0 {
Some(format!("Hi! My name is {}", name)) Ok(format!("Hi! My name is {}", name))
} else { } else {
// Empty names aren't allowed. // Empty names aren't allowed.
None Err("`name` was empty; it must be nonempty.".to_string())
} }
} }
@ -28,7 +27,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() { fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!( assert_eq!(
generate_nametag_text("Beyoncé".into()), generate_nametag_text("Beyoncé".into()),
Some("Hi! My name is Beyoncé".into()) Ok("Hi! My name is Beyoncé".into())
); );
} }

View file

@ -16,14 +16,13 @@
// There are at least two ways to implement this that are both correct-- but // There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways. // one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1; let processing_fee = 1;
let cost_per_item = 5; let cost_per_item = 5;
let qty = item_quantity.parse::<i32>(); let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee) Ok(qty * cost_per_item + processing_fee)
} }

View file

@ -4,11 +4,10 @@
// Why not? What should we do to fix it? // Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints! // Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
fn main() { fn main() -> Result<(), ParseIntError> {
let mut tokens = 100; let mut tokens = 100;
let pretend_user_input = "8"; let pretend_user_input = "8";
@ -20,6 +19,8 @@ fn main() {
tokens -= cost; tokens -= cost;
println!("You now have {} tokens.", tokens); println!("You now have {} tokens.", tokens);
} }
Ok(())
} }
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {

View file

@ -15,19 +15,18 @@
// //
// Execute `rustlings hint errorsn` for hints :) // Execute `rustlings hint errorsn` for hints :)
// I AM NOT DONE
use std::error; use std::error;
use std::fmt; use std::fmt;
use std::io; use std::io;
// PositiveNonzeroInteger is a struct defined below the tests. // PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, ???> { fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> {
let mut line = String::new(); let mut line = String::new();
b.read_line(&mut line); b.read_line(&mut line)?;
let num: i64 = line.trim().parse(); let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num); let answer: PositiveNonzeroInteger = PositiveNonzeroInteger::new(num)?;
answer Ok(answer)
} }
// This is a test helper function that turns a &str into a BufReader. // This is a test helper function that turns a &str into a BufReader.

View file

@ -12,7 +12,10 @@ pub fn pop_too_much() -> bool {
let last = list.pop().unwrap(); let last = list.pop().unwrap();
println!("The last item in the list is {:?}", last); println!("The last item in the list is {:?}", last);
let second_to_last = list.pop().unwrap(); let second_to_last = match list.pop() {
Some(i) => i,
None => 0
};
println!( println!(
"The second-to-last item in the list is {:?}", "The second-to-last item in the list is {:?}",
second_to_last second_to_last

View file

@ -1,7 +1,6 @@
// result1.rs // result1.rs
// Make this test pass! Execute `rustlings hint result1` for hints :) // Make this test pass! Execute `rustlings hint result1` for hints :)
// I AM NOT DONE
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64); struct PositiveNonzeroInteger(u64);
@ -14,7 +13,13 @@ enum CreationError {
impl PositiveNonzeroInteger { impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> { fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
Ok(PositiveNonzeroInteger(value as u64)) if value == 0 {
Err(CreationError::Zero)
} else if value < 0 {
Err(CreationError::Negative)
} else {
Ok(PositiveNonzeroInteger(value as u64))
}
} }
} }

View file

@ -1,7 +1,6 @@
// option1.rs // option1.rs
// Make me compile! Execute `rustlings hint option1` for hints // Make me compile! Execute `rustlings hint option1` for hints
// I AM NOT DONE
// you can modify anything EXCEPT for this function's sig // you can modify anything EXCEPT for this function's sig
fn print_number(maybe_number: Option<u16>) { fn print_number(maybe_number: Option<u16>) {
@ -9,15 +8,15 @@ fn print_number(maybe_number: Option<u16>) {
} }
fn main() { fn main() {
print_number(13); print_number(Some(13));
print_number(99); print_number(Some(99));
let mut numbers: [Option<u16>; 5]; let mut numbers: [Option<u16>; 5] = [None; 5];
for iter in 0..5 { for iter in 0..5 {
let number_to_add: u16 = { let number_to_add: u16 = {
((iter * 5) + 2) / (4 * 16) ((iter * 5) + 2) / (4 * 16)
}; };
numbers[iter] = number_to_add; numbers[iter as usize] = Some(number_to_add);
} }
} }

View file

@ -1,12 +1,11 @@
// option2.rs // option2.rs
// Make me compile! Execute `rustlings hint option2` for hints // Make me compile! Execute `rustlings hint option2` for hints
// I AM NOT DONE
fn main() { fn main() {
let optional_value = Some(String::from("rustlings")); let optional_value = Some(String::from("rustlings"));
// Make this an if let statement whose value is "Some" type // Make this an if let statement whose value is "Some" type
value = optional_value { if let Some(value) = optional_value {
println!("the value of optional value is: {}", value); println!("the value of optional value is: {}", value);
} else { } else {
println!("The optional value doesn't contain anything!"); println!("The optional value doesn't contain anything!");
@ -19,7 +18,7 @@ fn main() {
// make this a while let statement - remember that vector.pop also adds another layer of Option<T> // 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 // You can stack `Option<T>`'s into while let and if let
value = optional_values_vec.pop() { while let Some(Some(value)) = optional_values_vec.pop() {
println!("current value: {}", value); println!("current value: {}", value);
} }
} }