Skip to content

Commit

Permalink
finish iters && smart points
Browse files Browse the repository at this point in the history
  • Loading branch information
yangrudan committed Nov 28, 2024
1 parent b53d2f2 commit 23aeca8
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 34 deletions.
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
}
7 changes: 3 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,15 @@ 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()
words.iter().map(|&word| capitalize_first(word)).collect()
}

#[cfg(test)]
Expand Down
22 changes: 16 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,34 @@ 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 {
Ok(a / b)
} else {
Err(DivisionError::NotDivisible(NotDivisibleError {
dividend: a,
divisor: 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<i32>, DivisionError> = 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<i32, DivisionError>> = numbers.into_iter().map(|n| divide(n, 27)).collect();
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).product()
}

#[cfg(test)]
Expand Down
5 changes: 2 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,7 @@ 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!();
count_for(map, value)
}

fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
Expand All @@ -54,7 +53,7 @@ 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!();
collection.iter().map(|map| count_for(map, value)).sum()
}

#[cfg(test)]
Expand Down
5 changes: 2 additions & 3 deletions exercises/smart_pointers/arc1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,18 @@
//
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc;
use std::thread;

fn main() {
let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO
let shared_numbers = Arc::new(numbers);// TODO
let mut joinhandles = Vec::new();

for offset in 0..8 {
let child_numbers = // TODO
let child_numbers = shared_numbers.clone();// TODO
joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum);
Expand Down
7 changes: 3 additions & 4 deletions exercises/smart_pointers/box1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@
//
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[derive(PartialEq, Debug)]
pub enum List {
Cons(i32, List),
Cons(i32, Box<List>),
Nil,
}

Expand All @@ -35,11 +34,11 @@ fn main() {
}

pub fn create_empty_list() -> List {
todo!()
List::Nil
}

pub fn create_non_empty_list() -> List {
todo!()
List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))))
}

#[cfg(test)]
Expand Down
10 changes: 6 additions & 4 deletions exercises/smart_pointers/cow1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
//
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::borrow::Cow;

Expand Down Expand Up @@ -48,7 +47,8 @@ mod tests {
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
// TODO
Cow::Borrowed(_) => Ok(()),
_ => Err("Expected borrowed value"),
}
}

Expand All @@ -60,7 +60,8 @@ mod tests {
let slice = vec![0, 1, 2];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}

Expand All @@ -72,7 +73,8 @@ mod tests {
let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
}
10 changes: 6 additions & 4 deletions exercises/smart_pointers/rc1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
//
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::rc::Rc;

Expand Down Expand Up @@ -60,17 +59,17 @@ fn main() {
jupiter.details();

// TODO
let saturn = Planet::Saturn(Rc::new(Sun {}));
let saturn = Planet::Saturn(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details();

// TODO
let uranus = Planet::Uranus(Rc::new(Sun {}));
let uranus = Planet::Uranus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details();

// TODO
let neptune = Planet::Neptune(Rc::new(Sun {}));
let neptune = Planet::Neptune(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details();

Expand All @@ -92,12 +91,15 @@ fn main() {
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references

// TODO
drop(earth);
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references

// TODO
drop(venus);
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references

// TODO
drop(mercury);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference

assert_eq!(Rc::strong_count(&sun), 1);
Expand Down

0 comments on commit 23aeca8

Please sign in to comment.