DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 319fd4590a6791f141f9c3700c302cf0db11f28b aoc2024/src/day3/part2.rs -rw-r--r-- 1.9 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::{
    fs::File,
    io::{BufReader, Read},
    path::Path,
};

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

#[derive(Debug)]
enum Instruction {
    Do,
    Dont,
    Mul { left: i32, right: i32 },
}

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

fn parse_do(input: &str) -> IResult<&str, Instruction> {
    let (rem, _) = tag("do()")(input)?;
    Ok((rem, Instruction::Do))
}

fn parse_dont(input: &str) -> IResult<&str, Instruction> {
    let (rem, _) = tag("don't()")(input)?;
    Ok((rem, Instruction::Dont))
}

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

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

fn parse(input: &str) -> IResult<&str, Instruction> {
    let (rem, ins) = alt((parse_do, parse_dont, parse_mul))(input)?;

    Ok((rem, ins))
}

pub(super) fn part_two(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;
    let mut mul_enabled = true;
    loop {
        if buf.len() < 5 {
            break;
        }

        let (rem, ins) = match parse(&buf) {
            Ok((rem, ins)) => (rem, ins),
            Err(_) => {
                buf.replace_range(0..1, "");
                continue;
            }
        };

        buf = rem.into();

        match ins {
            Instruction::Do => mul_enabled = true,
            Instruction::Dont => mul_enabled = false,
            Instruction::Mul { left, right } => {
                if mul_enabled {
                    answer += left * right
                }
            }
        }
    }

    Ok(answer)
}