Skip to content

Commit

Permalink
18 Iterators & collections
Browse files Browse the repository at this point in the history
  • Loading branch information
chiffonng committed Jun 22, 2024
1 parent b3b47f2 commit 1287d9d
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 30 deletions.
10 changes: 5 additions & 5 deletions exercises/18_iterators/iterators1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE
// Listing 13-12: https://doc.rust-lang.org/book/ch13-02-iterators.html#the-iterator-trait-and-the-next-method

#[test]
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();

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"));
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"));
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);
}
12 changes: 8 additions & 4 deletions exercises/18_iterators/iterators2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE
// https://doc.rust-lang.org/book/ch13-02-iterators.html#methods-that-produce-other-iterators

// Step 1.
// Complete the `capitalize_first` function.
Expand All @@ -15,7 +15,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().to_string() + c.as_str(),
}
}

Expand All @@ -24,15 +24,19 @@ 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::<Vec<String>>()
.join("")
}

#[cfg(test)]
Expand Down
40 changes: 26 additions & 14 deletions exercises/18_iterators/iterators3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE
// https://doc.rust-lang.org/stable/book/ch13-04-performance.html

#[derive(Debug, PartialEq, Eq)]
pub enum DivisionError {
Expand All @@ -23,26 +23,38 @@ pub struct NotDivisibleError {
divisor: i32,
}

// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
/// 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!();
match b {
0 => Err(DivisionError::DivideByZero),
_ if a % b != 0 => Err(DivisionError::NotDivisible(NotDivisibleError {
dividend: a,
divisor: b,
})),
_ => 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() -> () {
// 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() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));

// Force division_results to be a Result<Vec<i32>, DivisionError>
let division_results: Result<Vec<i32>, DivisionError> = numbers
.into_iter() // turns the numbers into an iterator
.map(|n| divide(n, 27)) // divides each number by 27
.collect(); // converts the iterator into a type as specified by the type annotation
return 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() -> () {
// 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() -> 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 = numbers.into_iter().map(|n| divide(n, 27)).collect();
return division_results;
}

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

// I AM NOT DONE
// https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold

pub fn factorial(num: u64) -> u64 {
// Complete this function to return the factorial of num
/// Return the factorial of num
// Do not use:
// - early returns (using the `return` keyword explicitly)
// Try not to use:
// - imperative style loops (for, while)
// - additional variables
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
// Fold is a higher order function that applies a function to each element of an iterator, passing the result of the function to the next element.
(1..=num).fold(1, |acc, x| acc * x)
}

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

// I AM NOT DONE

use std::collections::HashMap;

#[derive(Clone, Copy, PartialEq, Eq)]
Expand All @@ -22,6 +20,7 @@ enum Progress {
Complete,
}

/// Count the number of exercises with a given progress.
fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
let mut count = 0;
for val in map.values() {
Expand All @@ -32,12 +31,15 @@ fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
count
}

/// Count the number of exercises with a given progress using iterators.
/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter
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!();
map.values().filter(|&val| val == &value).count()
}

/// Count the number of exercises with a given progress in a collection of progress maps.
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
let mut count = 0;
for map in collection {
Expand All @@ -50,11 +52,15 @@ fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progres
count
}

/// Count the number of exercises with a given progress in a collection of progress maps using iterators.
fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
// collection is a slice of hashmaps.
// collection = [{ "variables1": Complete, "from_str": None, ... },
// { "variables2": Complete, ... }, ... ]
todo!();
collection
.iter() // iterate over the collection
.map(|map| count_iterator(map, value))
.sum()
}

#[cfg(test)]
Expand Down

0 comments on commit 1287d9d

Please sign in to comment.