rustlings icon indicating copy to clipboard operation
rustlings copied to clipboard

Please help to solve iterators5.rs

Open Leo777 opened this issue 3 years ago • 6 comments

Hi stuck on this exercises could someone please help to solve it

Leo777 avatar Aug 02 '21 22:08 Leo777

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.

quangvdao avatar Aug 04 '21 10:08 quangvdao

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()

LeoniePhiline avatar Aug 09 '21 01:08 LeoniePhiline

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".

kenden avatar Sep 17 '23 11:09 kenden

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 using fold.

benkeil avatar Nov 03 '23 22:11 benkeil

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))
}

zabor2432 avatar Nov 07 '23 12:11 zabor2432

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))
}

sotirr avatar Nov 09 '23 10:11 sotirr