DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 319fd4590a6791f141f9c3700c302cf0db11f28b aoc2024/src/day3/part1.rs -rw-r--r-- 1.1 KiB
319fd459Jonni Liljamo feat: day3 a month ago
                                                                                
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
use std::{
    fs::File,
    io::{BufReader, Read},
    path::Path,
};

use nom::{
    bytes::complete::tag,
    character::complete::i32,
    sequence::{delimited, separated_pair},
    IResult,
};

#[derive(Debug)]
struct Mul {
    left: i32,
    right: i32,
}

fn parse_int32_pair(input: &str) -> IResult<&str, (i32, i32)> {
    separated_pair(i32, tag(","), i32)(input)
}

fn parse_mul(input: &str) -> IResult<&str, Mul> {
    let (rem, (left, right)) = delimited(tag("mul("), parse_int32_pair, tag(")"))(input)?;

    Ok((rem, Mul { left, right }))
}

pub(super) fn part_one(input: &Path) -> anyhow::Result<i32> {
    let mut reader = BufReader::new(File::open(input)?);
    let mut buf = String::new();
    reader.read_to_string(&mut buf)?;

    let mut answer = 0;
    loop {
        if buf.len() < 5 {
            break;
        }
        let (rem, mul) = match parse_mul(&buf) {
            Ok((rem, mul)) => (rem, mul),
            Err(_) => {
                buf.replace_range(0..1, "");
                continue;
            }
        };
        buf = rem.into();
        answer += mul.left * mul.right;
    }

    Ok(answer)
}