DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 6d04837a924cc606e7970e02877834fc5b8d70ce aoc2024/src/day17/mod.rs -rw-r--r-- 6.7 KiB
6d04837aJonni Liljamo feat: day17 partly 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
    str::FromStr,
};

pub fn solve(input: &Path) -> anyhow::Result<()> {
    println!("part one: {}", part_one(input)?);
    println!("part two: {}", part_two(input)?);

    Ok(())
}

#[derive(Debug)]
enum ProgramPart {
    Instruction(Ins),
    LiteralOperand(usize),
}

#[derive(Debug)]
enum Ins {
    Adv,
    Bxl,
    Bst,
    Jnz,
    Bxc,
    Out,
    Bdv,
    Cdv,
}

impl FromStr for Ins {
    type Err = Box<dyn std::error::Error>;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "0" => Ok(Self::Adv),
            "1" => Ok(Self::Bxl),
            "2" => Ok(Self::Bst),
            "3" => Ok(Self::Jnz),
            "4" => Ok(Self::Bxc),
            "5" => Ok(Self::Out),
            "6" => Ok(Self::Bdv),
            "7" => Ok(Self::Cdv),
            _ => unreachable!(),
        }
    }
}

#[derive(Debug)]
enum Copr {
    Literal(usize),
    RA,
    RB,
    RC,
}

impl Copr {
    fn from_usize(n: usize) -> Self {
        match n {
            0 => Self::Literal(0),
            1 => Self::Literal(1),
            2 => Self::Literal(2),
            3 => Self::Literal(3),
            4 => Self::RA,
            5 => Self::RB,
            6 => Self::RC,
            _ => unreachable!(),
        }
    }

    fn real(&self, ra: i32, rb: i32, rc: i32) -> i32 {
        match self {
            Self::Literal(n) => *n as i32,
            Self::RA => ra,
            Self::RB => rb,
            Self::RC => rc,
        }
    }
}

fn part_one(input: &Path) -> anyhow::Result<String> {
    let reader = BufReader::new(File::open(input)?);

    let mut ra: i32 = 0;
    let mut rb: i32 = 0;
    let mut rc: i32 = 0;
    let mut program: Vec<ProgramPart> = vec![];
    for line in reader.lines() {
        let line = line?;
        if line.starts_with("Register A") {
            ra = line.split_whitespace().last().unwrap().parse()?;
        } else if line.starts_with("Register B") {
            rb = line.split_whitespace().last().unwrap().parse()?;
        } else if line.starts_with("Register C") {
            rc = line.split_whitespace().last().unwrap().parse()?;
        } else if line.starts_with("Program") {
            program.append(
                &mut line
                    .split_whitespace()
                    .last()
                    .unwrap()
                    .split(",")
                    .enumerate()
                    .filter_map(|(i, c)| {
                        if c == "," {
                            None
                        } else if i % 2 == 0 {
                            Some(ProgramPart::Instruction(c.parse().unwrap()))
                        } else {
                            Some(ProgramPart::LiteralOperand(c.parse().unwrap()))
                        }
                    })
                    .collect::<Vec<_>>(),
            );
        }
    }

    let mut out: Vec<i32> = vec![];
    let mut ptr = 0;
    while ptr < program.len() {
        let mut incr = true;

        if let ProgramPart::Instruction(ins) = &program[ptr] {
            if let ProgramPart::LiteralOperand(lit_opr) = &program[ptr + 1] {
                let combo_opr = Copr::from_usize(*lit_opr).real(ra, rb, rc);
                match &ins {
                    Ins::Adv => ra /= 2_i32.pow(combo_opr as u32),
                    Ins::Bxl => rb ^= *lit_opr as i32,
                    Ins::Bst => rb = combo_opr % 8,
                    Ins::Jnz => {
                        if ra != 0 {
                            ptr = *lit_opr;
                            incr = false;
                        }
                    }
                    Ins::Bxc => rb ^= rc,
                    Ins::Out => out.push(combo_opr % 8),
                    Ins::Bdv => rb = ra / 2_i32.pow(combo_opr as u32),
                    Ins::Cdv => rc = ra / 2_i32.pow(combo_opr as u32),
                }
            } else {
                unreachable!();
            }
        } else {
            unreachable!();
        }

        if incr {
            ptr += 2;
        }
    }

    Ok(out
        .iter()
        .map(|o| o.to_string())
        .collect::<Vec<_>>()
        .join(","))
}

fn part_two(input: &Path) -> anyhow::Result<i32> {
    let reader = BufReader::new(File::open(input)?);

    let mut original_program = String::new();
    let mut program: Vec<ProgramPart> = vec![];
    for line in reader.lines() {
        let line = line?;
        if line.starts_with("Program") {
            original_program = line.split_whitespace().last().unwrap().into();
            program = original_program
                .clone()
                .split(",")
                .enumerate()
                .filter_map(|(i, c)| {
                    if c == "," {
                        None
                    } else if i % 2 == 0 {
                        Some(ProgramPart::Instruction(c.parse().unwrap()))
                    } else {
                        Some(ProgramPart::LiteralOperand(c.parse().unwrap()))
                    }
                })
                .collect::<Vec<_>>();
        }
    }

    let mut ra_init = 8;
    let mut ra: i32;
    let mut rb: i32;
    let mut rc: i32;
    loop {
        ra_init += 1;
        ra = ra_init;
        rb = 0;
        rc = 0;

        println!("trying {}", ra_init);

        let mut out: Vec<i32> = vec![];
        let mut ptr = 0;
        while ptr < program.len() {
            let mut incr = true;

            if let ProgramPart::Instruction(ins) = &program[ptr] {
                if let ProgramPart::LiteralOperand(lit_opr) = &program[ptr + 1] {
                    let combo_opr = Copr::from_usize(*lit_opr).real(ra, rb, rc);
                    match &ins {
                        Ins::Adv => ra /= 2_i32.pow(combo_opr as u32),
                        Ins::Bxl => rb ^= *lit_opr as i32,
                        Ins::Bst => rb = combo_opr % 8,
                        Ins::Jnz => {
                            if ra != 0 {
                                ptr = *lit_opr;
                                incr = false;
                            }
                        }
                        Ins::Bxc => rb ^= rc,
                        Ins::Out => out.push(combo_opr % 8),
                        Ins::Bdv => rb = ra / 2_i32.pow(combo_opr as u32),
                        Ins::Cdv => rc = ra / 2_i32.pow(combo_opr as u32),
                    }
                } else {
                    unreachable!();
                }
            } else {
                unreachable!();
            }

            if incr {
                ptr += 2;
            }
        }

        let out_str = out
            .iter()
            .map(|o| o.to_string())
            .collect::<Vec<_>>()
            .join(",");

        if out_str == original_program {
            break;
        }
    }

    Ok(ra_init)
}