Follow

I subscribe to a newsletter[1] that has a coding challenge every week.

I did this week's in , but I'm sure there are many ways to make it more compact/better....

play.rust-lang.org/?version=st

help welcome! How do I use map to sum over a Vector of structs?

(1) cassidoo.co/newsletter/

· · Web · 4 · 2 · 0

rust 

@schlink i'd have used that:

let slices_needed: usize = persons.iter().map(|p| p.slices_requested).sum();

with map to get the number we need, and sum to concisely sum them.
fold could work too but i find it more verbose and less elegant

rust 

@schlink

> I’m curious if there’s a more concise way to go from slices_needed to pizzas_needed

I think:

(slices_needed + slices_per_pizza - 1) / slices_per_pizza

would work.

rust 

@schlink

If you were doing it a lot, you could define div_upwards on integers like so:

play.rust-lang.org/?version=st

(I based the implementation on the definition of integer division from rusts core: doc.rust-lang.org/src/core/ops )

rust 

@schlink heeeeey, so you're back, learning things about Rust! Ping me anytime, and how's async going?

Sign in to participate in the conversation
Octodon

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!