Skip to content

Commit ce90f4b

Browse files
committed
2017 day 8
1 parent a78c7ab commit ce90f4b

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

crates/year2017/src/day08.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
use std::collections::HashMap;
2+
use utils::prelude::*;
3+
4+
/// Evaluating conditional add instructions.
5+
#[derive(Clone, Debug)]
6+
pub struct Day08 {
7+
part1: i32,
8+
part2: i32,
9+
}
10+
11+
impl Day08 {
12+
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
13+
let parsed = parser::take_while1(u8::is_ascii_lowercase)
14+
.with_suffix(" ")
15+
.then(
16+
parser::one_of((
17+
parser::i32().with_prefix("inc "),
18+
parser::i32().with_prefix("dec ").map(|x| -x),
19+
))
20+
.with_suffix(" if "),
21+
)
22+
.then(parser::take_while1(u8::is_ascii_lowercase).with_suffix(" "))
23+
.then(
24+
parser::one_of((
25+
"==".map(|_| i32::eq as fn(&i32, &i32) -> bool),
26+
"!=".map(|_| i32::ne as fn(&i32, &i32) -> bool),
27+
"<=".map(|_| i32::le as fn(&i32, &i32) -> bool),
28+
">=".map(|_| i32::ge as fn(&i32, &i32) -> bool),
29+
"<".map(|_| i32::lt as fn(&i32, &i32) -> bool),
30+
">".map(|_| i32::gt as fn(&i32, &i32) -> bool),
31+
))
32+
.with_suffix(" "),
33+
)
34+
.then(parser::i32())
35+
.parse_lines(input)?;
36+
37+
let mut registers = HashMap::new();
38+
let mut max = 0;
39+
for (reg, value, cond_reg, comparison, cond_value) in parsed {
40+
if comparison(registers.entry(cond_reg).or_insert(0), &cond_value) {
41+
let entry = registers.entry(reg).or_insert(0);
42+
*entry += value;
43+
max = max.max(*entry);
44+
}
45+
}
46+
47+
Ok(Self {
48+
part1: registers.into_values().max().unwrap_or(0),
49+
part2: max,
50+
})
51+
}
52+
53+
#[must_use]
54+
pub fn part1(&self) -> i32 {
55+
self.part1
56+
}
57+
58+
#[must_use]
59+
pub fn part2(&self) -> i32 {
60+
self.part2
61+
}
62+
}
63+
64+
examples!(Day08 -> (i32, i32) [
65+
{
66+
input: "b inc 5 if a > 1\n\
67+
a inc 1 if b < 5\n\
68+
c dec -10 if a >= 1\n\
69+
c inc -20 if c == 10",
70+
part1: 1,
71+
part2: 10
72+
},
73+
]);

crates/year2017/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ utils::year!(2017 => year2017, ${
99
5 => day05::Day05,
1010
6 => day06::Day06,
1111
7 => day07::Day07<'_>,
12+
8 => day08::Day08,
1213
});

0 commit comments

Comments
 (0)