summaryrefslogtreecommitdiffstats
path: root/src/day_5.rs
blob: 006a59a670cdb6f5fc365f31944b2225212e38a2 (plain)
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
use std::{
    fmt::Display,
    ops::{Deref, DerefMut},
    str::FromStr,
};

use anyhow::{Context, Result};

use crate::{Problem, Solution};

#[derive(Debug)]
struct Procedure(Vec<Step>);

impl Procedure {
    fn run(self, mut stacks: Stacks, in_order: bool) -> Result<Stacks> {
        for step in self.0 {
            let mut move_stack = Vec::new();
            for _ in 0..step.count {
                let cargo = stacks[step.from - 1]
                    .pop()
                    .ok_or_else(|| anyhow::anyhow!("ran out of cargo"))?;
                move_stack.push(cargo)
            }

            if in_order {
                move_stack.reverse()
            }

            stacks[step.to - 1].append(&mut move_stack);
        }
        Ok(stacks)
    }
}

impl FromStr for Procedure {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut procedure = Procedure(Vec::new());
        for (linenr, step) in s.lines().enumerate() {
            procedure.push(
                step.parse()
                    .context(format!("Error in procedure step {}: '{}'", linenr, step))?,
            )
        }
        Ok(procedure)
    }
}

impl Deref for Procedure {
    type Target = Vec<Step>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Procedure {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug)]
struct Step {
    count: usize,
    from: usize,
    to: usize,
}

impl FromStr for Step {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut items = s.split_whitespace();
        Ok(Self {
            count: items.next_chunk::<2>().unwrap().last().unwrap().parse()?,
            from: items.next_chunk::<2>().unwrap().last().unwrap().parse()?,
            to: items.next_chunk::<2>().unwrap().last().unwrap().parse()?,
        })
    }
}

#[derive(Debug)]
struct Stacks(Vec<Vec<char>>);

impl Stacks {
    fn top(mut self) -> String {
        self.iter_mut().fold(
            "".to_owned(),
            |mut acc: String, s: &mut std::vec::Vec<char>| {
                if let Some(c) = s.pop() {
                    acc.push(c)
                }
                acc
            },
        )
    }
}

impl Deref for Stacks {
    type Target = Vec<Vec<char>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Stacks {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl FromStr for Stacks {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut stacks = Self(Vec::new());
        for line in s.lines().rev().skip(1) {
            let mut chars = line.chars().skip(1).enumerate();
            loop {
                let (stack, cargo) = match chars.next() {
                    Some((_, '[' | ']' | ' ')) => continue,
                    Some((index, c)) => (index / 4, c),
                    None => break,
                };
                if stacks.len() < stack + 1 {
                    stacks.push(Vec::new())
                }
                stacks[stack].push(cargo)
            }
        }
        Ok(stacks)
    }
}

impl Display for Stacks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Some(max_len) = self.0.iter().map(|v| v.len()).max() else {
            return Ok(())
        };

        for i in (0..max_len).rev() {
            let mut cargos = Vec::new();
            for stack in &self.0 {
                let cargo = match stack.get(i) {
                    Some(c) => format!("[{}]", c),
                    None => "   ".to_owned(),
                };
                cargos.push(cargo);
            }
            writeln!(f, "{}", cargos.join(" "))?
        }
        Ok(())
    }
}

pub struct Day5;

impl Problem for Day5 {
    const DAY: u8 = 5;

    const INPUT: &'static str = include_str!("../input/day_5.txt");
}

impl Solution for Day5 {
    type Answer1 = String;

    type Answer2 = String;

    fn part_1(input: &str) -> Result<Self::Answer1, anyhow::Error> {
        let (stacks, procedure) = input.split_once("\n\n").unwrap();
        let stacks = Stacks::from_str(stacks)?;
        let procedure = Procedure::from_str(procedure)?;
        Ok(procedure.run(stacks, false)?.top())
    }

    fn part_2(input: &str) -> Result<Self::Answer2, anyhow::Error> {
        let (stacks, procedure) = input.split_once("\n\n").unwrap();
        let stacks = Stacks::from_str(stacks)?;
        let procedure = Procedure::from_str(procedure)?;
        Ok(procedure.run(stacks, true)?.top())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_INPUT: &str = indoc::indoc! {r#"
                [D]
            [N] [C]
            [Z] [M] [P]
             1   2   3

            move 1 from 2 to 1
            move 3 from 1 to 3
            move 2 from 2 to 1
            move 1 from 1 to 2
        "#};

    #[test]
    fn test_part_1_example() -> Result<()> {
        Ok(assert_eq!("CMZ", Day5::part_1(TEST_INPUT)?))
    }

    #[test]
    fn test_part_2_example() -> Result<()> {
        Ok(assert_eq!("MCD", Day5::part_2(TEST_INPUT)?))
    }
}