|
1 | | -use std::str::FromStr; |
2 | | - |
3 | | -use aoclp::anyhow::anyhow; |
4 | | -use aoclp::functional::ByRefPredHelper; |
| 1 | +use aoclp::forth::Forth; |
5 | 2 | use aoclp::solvers_impl::input::safe_get_input; |
6 | 3 | use itertools::Itertools; |
7 | 4 |
|
8 | 5 | 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() |
13 | 7 | } |
14 | 8 |
|
15 | 9 | 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() |
54 | 11 | } |
55 | 12 |
|
56 | 13 | #[derive(Debug)] |
57 | 14 | struct Problem { |
58 | 15 | operands: Vec<usize>, |
59 | | - operator: Operator, |
| 16 | + operator: String, |
60 | 17 | } |
61 | 18 |
|
62 | 19 | 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 |
67 | 29 | } |
68 | 30 | } |
69 | 31 |
|
@@ -136,13 +98,13 @@ fn cephaloproblems() -> Vec<Problem> { |
136 | 98 | .collect_vec() |
137 | 99 | } |
138 | 100 |
|
139 | | -fn parse_operators(input: &str) -> Vec<Operator> { |
| 101 | +fn parse_operators(input: &str) -> Vec<String> { |
140 | 102 | input |
141 | 103 | .lines() |
142 | 104 | .last() |
143 | 105 | .unwrap() |
144 | 106 | .split_ascii_whitespace() |
145 | | - .map(|op| op.parse::<Operator>().unwrap()) |
| 107 | + .map(<_>::to_string) |
146 | 108 | .collect_vec() |
147 | 109 | } |
148 | 110 |
|
|
0 commit comments