summaryrefslogtreecommitdiffstats
path: root/src/day_09.rs
blob: d73a93d4ecd482094f11a7bde1e6d54a622bbc29 (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
use std::{cmp::Ordering, collections::HashSet, fmt::Display, str::FromStr};

use crate::{Problem, Solution};

type Unit = isize;
type Position = (Unit, Unit);

enum Motion {
    Up(Unit),
    Down(Unit),
    Left(Unit),
    Right(Unit),
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once(' ') {
            Some(("U", n)) => Ok(Motion::Up(n.parse()?)),
            Some(("D", n)) => Ok(Motion::Down(n.parse()?)),
            Some(("L", n)) => Ok(Motion::Left(n.parse()?)),
            Some(("R", n)) => Ok(Motion::Right(n.parse()?)),
            _ => Err(anyhow::format_err!("Improper motion format: {}", s)),
        }
    }
}

impl Display for Motion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Motion::Up(n) => write!(f, "U {}", n),
            Motion::Down(n) => write!(f, "D {}", n),
            Motion::Left(n) => write!(f, "L {}", n),
            Motion::Right(n) => write!(f, "R {}", n),
        }
    }
}

#[derive(Clone)]
enum List {
    Cons(Position, Box<List>),
    None,
}

impl List {
    fn new() -> Self {
        Self::None
    }

    fn prepend(self) -> List {
        Self::Cons(Default::default(), Box::new(self))
    }

    fn update_from_motion(&mut self, motion: Motion) -> Vec<Position> {
        let Self::Cons(position, next) = self else {
            panic!("update_from_motion must be called on a head with at least one tail.");
        };

        let (dx, dy, count) = match motion {
            Motion::Up(n) => (0, 1, n),
            Motion::Down(n) => (0, -1, n),
            Motion::Left(n) => (-1, 0, n),
            Motion::Right(n) => (1, 0, n),
        };

        let mut visited = Vec::new();
        for _ in 0..count {
            position.0 += dx;
            position.1 += dy;
            visited.push(next.as_mut().update_from_position(position));
        }

        visited
    }

    fn update_from_position(&mut self, head: &Position) -> Position {
        let Self::Cons(position, next) = self else {
            return *head;
        };

        if position.0.abs_diff(head.0) > 1 || position.1.abs_diff(head.1) > 1 {
            match position.0.cmp(&head.0) {
                Ordering::Less => position.0 += 1,
                Ordering::Equal => {}
                Ordering::Greater => position.0 -= 1,
            }

            match position.1.cmp(&head.1) {
                Ordering::Less => position.1 += 1,
                Ordering::Equal => {}
                Ordering::Greater => position.1 -= 1,
            }
        }

        next.as_mut().update_from_position(position)
    }
}

pub struct Day09;

impl Problem for Day09 {
    const DAY: u8 = 9;

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

impl Solution for Day09 {
    type Answer1 = usize;

    type Answer2 = usize;

    fn part_1(input: &str) -> Result<Self::Answer1, anyhow::Error> {
        let mut head = List::new();
        head = head.prepend();
        head = head.prepend();

        input
            .lines()
            .flat_map(Motion::from_str)
            .flat_map(|motion| head.update_from_motion(motion))
            .try_fold(HashSet::new(), |mut set, pos| {
                set.insert(pos);
                Ok(set)
            })
            .map(|s| s.len())
    }

    fn part_2(input: &str) -> Result<Self::Answer2, anyhow::Error> {
        let mut head = List::new();
        for _ in 0..10 {
            head = head.prepend();
        }

        input
            .lines()
            .flat_map(Motion::from_str)
            .flat_map(|motion| head.update_from_motion(motion))
            .try_fold(HashSet::new(), |mut set, pos| {
                set.insert(pos);
                Ok(set)
            })
            .map(|s| s.len())
    }
}

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

    #[test]
    fn test_part_1_example() -> Result<(), anyhow::Error> {
        let test_input = indoc::indoc! {r#"
            R 4
            U 4
            L 3
            D 1
            R 4
            D 1
            L 5
            R 2
        "#};

        Ok(assert_eq!(13, Day09::part_1(test_input)?))
    }

    #[test]
    fn test_part_2_example() -> Result<(), anyhow::Error> {
        let test_input = indoc::indoc! {r#"
            R 5
            U 8
            L 8
            D 3
            R 17
            D 10
            L 25
            U 20
        "#};

        Ok(assert_eq!(36, Day09::part_2(test_input)?))
    }
}