Absolutely Rust newbie here! Please suggest me how to improve this simple program

Hello Rust community! this is my first workable Rust program. I googled way too many things and through trial and error reached this solution and it feels like I could've done this in simpler ways. Please tell me how can I improve this problem (Leetcode link)

Problem description

given a 2D vector [[1,2,3],[3,5,1]] I'd have to separately sum the vectors inside the 2D one and find out largest sum among them. I'm probably butchering the problem please pardon my English deficiency, have a look at Leetcode link.

My code snippet (via carbon.now.sh link)

I want to know what can be done to improve this (type of) programs. Thank you

You can use iterators and save an allocation:

fn main() {
    let v = vec![vec![1, 2, 3], vec![3, 5, 1]];
    let sum: i32 = v.iter().map(|list| list.iter().sum()).max().unwrap();
    println!("{}", sum);
}
1 Like

Thank you!
I'll look into map function/method. Is that enough to fully understand your improvements?

Here's the map documentation. The only minor change I would make to @chrefr's suggestion is using unwrap_or(0) instead of unwrap().

Incidentally, text is preferred over images in this forum, for ease of reading and copying (e.g. to the playground, like my second link above). You can read more about code formatting in this pinned post.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.