Skip to content

Commit 2f62a51

Browse files
committed
chore: appear smart because I have a Forth interpreter
1 parent e5412fd commit 2f62a51

File tree

1 file changed

+15
-53
lines changed

1 file changed

+15
-53
lines changed

aoclp_solutions/src/y2025/day_06.rs

Lines changed: 15 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,31 @@
1-
use std::str::FromStr;
2-
3-
use aoclp::anyhow::anyhow;
4-
use aoclp::functional::ByRefPredHelper;
1+
use aoclp::forth::Forth;
52
use aoclp::solvers_impl::input::safe_get_input;
63
use itertools::Itertools;
74

85
pub fn part_1() -> usize {
9-
problems()
10-
.into_iter()
11-
.map(Problem::answer.without_ref())
12-
.sum()
6+
problems().into_iter().map(Problem::answer).sum()
137
}
148

159
pub fn part_2() -> usize {
16-
cephaloproblems()
17-
.into_iter()
18-
.map(Problem::answer.without_ref())
19-
.sum()
20-
}
21-
22-
#[derive(Debug, Copy, Clone)]
23-
enum Operator {
24-
Plus,
25-
Times,
26-
}
27-
28-
impl Operator {
29-
fn initial(self) -> usize {
30-
match self {
31-
Operator::Plus => 0,
32-
Operator::Times => 1,
33-
}
34-
}
35-
36-
fn apply(self, a: usize, b: usize) -> usize {
37-
match self {
38-
Operator::Plus => a + b,
39-
Operator::Times => a * b,
40-
}
41-
}
42-
}
43-
44-
impl FromStr for Operator {
45-
type Err = aoclp::Error;
46-
47-
fn from_str(s: &str) -> Result<Self, Self::Err> {
48-
match s {
49-
"+" => Ok(Operator::Plus),
50-
"*" => Ok(Operator::Times),
51-
op => Err(anyhow!("Unknown operator: {op}")),
52-
}
53-
}
10+
cephaloproblems().into_iter().map(Problem::answer).sum()
5411
}
5512

5613
#[derive(Debug)]
5714
struct Problem {
5815
operands: Vec<usize>,
59-
operator: Operator,
16+
operator: String,
6017
}
6118

6219
impl Problem {
63-
fn answer(&self) -> usize {
64-
self.operands
65-
.iter()
66-
.fold(self.operator.initial(), |acc, i| self.operator.apply(acc, *i))
20+
fn answer(self) -> usize {
21+
let mut forth = Forth::new();
22+
for operand in self.operands {
23+
forth.eval(&operand.to_string()).unwrap();
24+
}
25+
while forth.stack().len() > 1 {
26+
forth.eval(&self.operator).unwrap();
27+
}
28+
forth.stack()[0] as usize
6729
}
6830
}
6931

@@ -136,13 +98,13 @@ fn cephaloproblems() -> Vec<Problem> {
13698
.collect_vec()
13799
}
138100

139-
fn parse_operators(input: &str) -> Vec<Operator> {
101+
fn parse_operators(input: &str) -> Vec<String> {
140102
input
141103
.lines()
142104
.last()
143105
.unwrap()
144106
.split_ascii_whitespace()
145-
.map(|op| op.parse::<Operator>().unwrap())
107+
.map(<_>::to_string)
146108
.collect_vec()
147109
}
148110

0 commit comments

Comments
 (0)