rustlings
rustlings copied to clipboard
Please help to solve iterators5.rs
Hi stuck on this exercises could someone please help to solve it
For the function insidemap( |(k,v)| ... )
, you want a function that returns usize 1 if v == value
and 0 otherwise. Then sum it all up.
Alternatively, use filter()
:
map
.values()
.filter(|v| *v == &value)
.count()
Note that in count_collection_iterator()
you can call count_iterator()
instead of re-implementing the functionality. Something like:
collection
.iter()
.map(|map| count_iterator(map, value))
.sum()
The Rustlings' hint is to use fold()
. I would add why to the hint:
fold()
is a particularly good choice for operations that require reducing a collection to a single value... such as counting the number of elements in a collection.
So, count_collection_iterator()
could use fold()
to reduce the collection of hashmaps to a single count of how many times the value appears in the hashmaps.
But... thinking of using fold()
seems more difficult than thinking about using map()
.
And I would point to flatten()
and flat_map()
as part of the "advanced hint".
from the hint:
For a further challenge, consult the documentation for
Iterator
to find a different method that could make your code more compact than usingfold
.
For the fold approach you can think of something like that:
fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
collection.iter().fold(0, |acc, x| acc + count_iterator(x, value))
}
Both using fold:
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, ... }
map.iter().fold(0, |acc, cur| if cur.1 == &value { return acc + 1 } else { acc })
}
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, ... }, ... ]
collection.iter().fold(0, |acc, map| acc + count_iterator(map, value))
}