DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 1: Report Repair

Collapse
ranquebenoit profile image
Benoit Ranque • Edited

Bit late to the party, here is my iterator focused solution in rust. input is a Vec, aka the parsed input data

    if let Some((a, b, c)) = input.iter().find_map(|a| {
        if let Some((b, c)) = input.iter().find_map(|b| {
            if let Some(c) = input.iter().find(|c| a + b + *c == 2020) {
                Some((b, c))
            } else {
                None
            }
        }) {
            Some((a, b, c))
        } else {
            None
        }
    }) {
        println!("A: {}, B: {}, C: {} result: {}", a, b, c, a * b * c);
    } else {
        println!("Could not find numbers fullfilling the requirement")
    }
Enter fullscreen mode Exit fullscreen mode

Edit: solution 2, same concept, but more concise

    match input.iter().find_map(|a| {
        input.iter().find_map(|b| {
            input.iter().find_map(|c| {
                if a + b + c == 2020 {
                    Some((a, b, c))
                } else {
                    None
                }
            })
        })
    }) {
        Some((a, b, c)) => println!("A: {}, B: {}, C: {} result: {}", a, b, c, a * b * c),
        None => println!("Could not find numbers fullfilling the requirement"),
    }
Enter fullscreen mode Exit fullscreen mode