summaryrefslogtreecommitdiff
path: root/2022/src/bin/day_1.rs
blob: bc988b78d089549376dc041d47671685a786bad9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use nom::{
    character::complete::{line_ending, u32 as nom_u32},
    combinator::map,
    multi::separated_list1,
    sequence::pair,
    IResult,
};
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_1.txt")?;
    let elves = Elves::parser(&input).unwrap().1;
    dbg!(elves.max_calories_sum(1));
    dbg!(elves.max_calories_sum(3));
    Ok(())
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Elves {
    elves: Vec<Elf>,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Elf {
    calories: Vec<u32>,
}

impl Elves {
    fn parser(input: &str) -> IResult<&str, Elves> {
        map(
            separated_list1(pair(line_ending, line_ending), Elf::parser),
            Elves::new,
        )(input)
    }

    fn new(mut elves: Vec<Elf>) -> Elves {
        elves.sort_unstable_by_key(|elf| elf.total_calories());
        Elves { elves }
    }

    fn max_calories_sum(&self, count: usize) -> u32 {
        self.elves
            .iter()
            .rev()
            .take(count)
            .map(|elf| elf.total_calories())
            .sum()
    }
}

impl Elf {
    fn parser(input: &str) -> IResult<&str, Elf> {
        map(separated_list1(line_ending, nom_u32), |calories| Elf {
            calories,
        })(input)
    }

    fn total_calories(&self) -> u32 {
        self.calories.iter().sum()
    }
}