Compare commits

...

5 commits

Author SHA1 Message Date
Mo 4d9c346a17
Merge pull request #2019 from Nahor/iterator5
Add alternative solution for iterators5
2024-07-05 11:45:42 +02:00
Nahor deed9d3943 Add alternative solution for iterators5 2024-07-04 16:35:39 -07:00
mo8it 652f0c7676 Fix tests 2024-07-04 23:39:06 +02:00
Mo e479ec8fb6
Merge pull request #2018 from Nahor/iterators4
Unify fn signature in iterators4 exercise and solution
2024-07-04 23:37:38 +02:00
Nahor a33501e6a7 Unify fn signature in iterators4 exercise and solution
Since this is not about conversion, prefer the option that doesn't
require one.
2024-07-04 14:23:34 -07:00
3 changed files with 36 additions and 1 deletions

View file

@ -1,4 +1,4 @@
fn factorial(num: u8) -> u64 {
fn factorial(num: u64) -> u64 {
// TODO: Complete this function to return the factorial of `num`.
// Do not use:
// - early returns (using the `return` keyword explicitly)

View file

@ -47,6 +47,23 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
.sum()
}
// Equivalent to `count_collection_iterator`+`count_iterator`, iterating as if
// the collection was a single container instead of a container of containers
// (and more accurately, a single iterator instead of an iterator of iterators).
fn count_collection_iterator_flat(
collection: &[HashMap<String, Progress>],
value: Progress,
) -> usize {
// `collection` is a slice of hash maps.
// collection = [{ "variables1": Complete, "from_str": None, … },
// { "variables2": Complete, … }, … ]
collection
.iter()
.flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`)
.filter(|val| **val == value)
.count()
}
fn main() {
// You can optionally experiment here.
}
@ -121,18 +138,30 @@ mod tests {
count_collection_iterator(&collection, Progress::Complete),
6,
);
assert_eq!(
count_collection_iterator_flat(&collection, Progress::Complete),
6,
);
}
#[test]
fn count_collection_some() {
let collection = get_vec_map();
assert_eq!(count_collection_iterator(&collection, Progress::Some), 1);
assert_eq!(
count_collection_iterator_flat(&collection, Progress::Some),
1
);
}
#[test]
fn count_collection_none() {
let collection = get_vec_map();
assert_eq!(count_collection_iterator(&collection, Progress::None), 4);
assert_eq!(
count_collection_iterator_flat(&collection, Progress::None),
4
);
}
#[test]
@ -145,6 +174,10 @@ mod tests {
count_collection_for(&collection, progress_state),
count_collection_iterator(&collection, progress_state),
);
assert_eq!(
count_collection_for(&collection, progress_state),
count_collection_iterator_flat(&collection, progress_state),
);
}
}
}

View file

@ -111,6 +111,7 @@ mod tests {
test: true,
strict_clippy: true,
hint: String::new(),
skip_check_unsolved: false,
},
ExerciseInfo {
name: String::from("2"),
@ -118,6 +119,7 @@ mod tests {
test: false,
strict_clippy: false,
hint: String::new(),
skip_check_unsolved: false,
},
];