-
Notifications
You must be signed in to change notification settings - Fork 0
/
day08.rs
81 lines (68 loc) · 1.53 KB
/
day08.rs
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
use std::fs;
enum Op {
Nop(i32),
Acc(i32),
Jmp(i32),
}
enum Res {
Loop(i32),
Finished(i32),
}
fn parse_op(s: &str) -> Op {
let words: Vec<&str> = s.split(" ").collect();
let v = words[1].parse().unwrap();
match words[0] {
"acc" => Op::Acc(v),
"jmp" => Op::Jmp(v),
_ => Op::Nop(v),
}
}
fn check_loop(ops: &Vec<Op>) -> Res {
let mut pc: usize = 0;
let mut acc: i32 = 0;
let mut seen = vec![false; ops.len()];
while pc < ops.len() && !seen[pc] {
seen[pc] = true;
match ops[pc] {
Op::Nop(_) => pc += 1,
Op::Acc(v) => { pc += 1; acc += v },
Op::Jmp(v) => pc = ((pc as i32) + v) as usize,
}
}
if pc < ops.len() { Res::Loop(acc) }
else { Res::Finished(acc) }
}
fn part1(ops: &Vec<Op>) -> i32 {
match check_loop(ops) {
Res::Loop(acc) => acc,
Res::Finished(_) => -1,
}
}
fn part2(ops: &mut Vec<Op>) -> i32 {
for i in 0..ops.len() {
match ops[i] {
Op::Acc(_) => continue,
Op::Jmp(v) => {
ops[i] = Op::Nop(v);
if let Res::Finished(acc) = check_loop(ops) {
return acc
}
ops[i] = Op::Jmp(v)
},
Op::Nop(v) => {
ops[i] = Op::Jmp(v);
if let Res::Finished(acc) = check_loop(ops) {
return acc
}
ops[i] = Op::Nop(v)
}
}
}
-1
}
fn main() {
let input = fs::read_to_string("input/input08.txt").unwrap();
let mut ops: Vec<Op> = input.lines().map(parse_op).collect();
println!("Part 1: {}", part1(&ops));
println!("Part 2: {}", part2(&mut ops));
}