Skip to content

Commit

Permalink
rustlings 80 done
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Jul 7, 2024
1 parent 36b925f commit f975674
Show file tree
Hide file tree
Showing 31 changed files with 160 additions and 103 deletions.
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(format!("`name` was empty; it must be nonempty."))
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}

Expand Down
12 changes: 8 additions & 4 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,20 @@
// 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>();
match qty {
Ok(qty) => Ok(qty * cost_per_item + processing_fee),
Err(e) => Err(e),
}*/
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)

}

#[cfg(test)]
Expand All @@ -38,7 +42,7 @@ mod tests {
#[test]
fn item_quantity_is_a_valid_number() {
assert_eq!(total_cost("34"), Ok(171));
}
}

#[test]
fn item_quantity_is_an_invalid_number() {
Expand Down
4 changes: 2 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,7 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
14 changes: 12 additions & 2 deletions 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,7 +16,18 @@ enum CreationError {
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
Ok(PositiveNonzeroInteger(value as u64))
/*if value > 0 {
Ok(PositiveNonzeroInteger(value as u64))
} else if (value < 0) {
Err(CreationError::Negative)
} else {
Err(CreationError::Zero)
}*/
match value {
n if n > 0 => Ok(PositiveNonzeroInteger(value as u64)),
n if n < 0 => Err(CreationError::Negative),
_ => Err(CreationError::Zero),
}
}
}

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
25 changes: 21 additions & 4 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 @@ -24,15 +23,33 @@ impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// 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();
// complex way
/*
let x : i64 = match s.parse() {
Ok(n) => n,
Err(err) => return Err(ParsePosNonzeroError::from_parseint(err)),
};
match PositiveNonzeroInteger::new(x) {
Ok(n) => Ok(n),
Err(err) => Err(ParsePosNonzeroError::from_creation(err)),
}
*/
// ?
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
// use closure fail to compile!!!!
/*
let x : i64 = s.parse().unwrap_or_else(|err| return Err(ParsePosNonzeroError::from_parseint(err)))?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
*/
}

// Don't change anything below this line.
Expand Down
2 changes: 1 addition & 1 deletion exercises/functions/functions3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


fn main() {
call_me(10000000);
call_me(1);
}

fn call_me(num: u32) {
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
3 changes: 2 additions & 1 deletion exercises/intro/intro2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
// hint.

fn main() {
println!("Hello word!");
let world = "world!";
println!("Hello {}", world);
}
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(); // 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")); // 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")); // 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); // Step 4
}
20 changes: 14 additions & 6 deletions exercises/iterators/iterators2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,41 @@
// 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"
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
let result = match c.next() {
None => String::new(),
Some(first) => ???,
}
Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
};
result
}

// Step 2.
// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![]
let mut s = vec![];
for word in words.iter() {
s.push(capitalize_first(word));
}
s
}

// 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()
let mut s = String::new();
for word in words.iter() {
s.push_str(&capitalize_first(word));
}
s
}

#[cfg(test)]
Expand Down
19 changes: 13 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,31 @@ 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!();
if b == 0 {
Err(DivisionError::DivideByZero)
} else if a % b != 0 {
Err(DivisionError::NotDivisible(NotDivisibleError {dividend:a, divisor:b}))
} else {
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 : Result<Vec<_>,_> = numbers.into_iter().map(|n| divide(n, 27)).collect();
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 : Vec<Result<_,_>> = numbers.into_iter().map(|n| divide(n, 27)).collect();
division_results
}

#[cfg(test)]
Expand Down
6 changes: 4 additions & 2 deletions exercises/iterators/iterators4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

pub fn factorial(num: u64) -> u64 {
pub fn factorial(n: u64) -> u64 {
// Complete this function to return the factorial of num
// Do not use:
// - return
Expand All @@ -15,6 +14,9 @@ pub fn factorial(num: u64) -> u64 {
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.

//(1..=n).product()
(1..=n).fold(1, |acc, x| acc * x)
}

#[cfg(test)]
Expand Down
19 changes: 16 additions & 3 deletions exercises/iterators/iterators5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

Expand All @@ -35,7 +34,13 @@ fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
// map is a hashmap with String keys and Progress values.
// map = { "variables1": Complete, "from_str": None, ... }
todo!();
let mut c = 0;
for (_, p) in map.iter() {
if p == &value {
c += 1;
}
}
c
}

fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
Expand All @@ -54,7 +59,15 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
// collection is a slice of hashmaps.
// collection = [{ "variables1": Complete, "from_str": None, ... },
// { "variables2": Complete, ... }, ... ]
todo!();
let mut c = 0;
for i in collection {
for (_, p) in i.iter() {
if p == & value {
c += 1;
}
}
}
c
}

#[cfg(test)]
Expand Down
3 changes: 1 addition & 2 deletions exercises/lifetimes/lifetimes1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
// 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 {
Expand Down
Loading

0 comments on commit f975674

Please sign in to comment.