advent_of_code/year2018/
day17.rs

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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use crate::input::Input;
use std::cmp::{max, min};
#[cfg(feature = "debug-output")]
use std::env;

fn parse_point_interval(s: &str) -> Result<(u16, u16), String> {
    if s.contains("..") {
        let parts: Vec<&str> = s.split("..").collect();
        if parts.len() != 2 {
            return Err("Invalid input".to_string());
        }
        Ok((
            parts[0].parse::<u16>().map_err(|_| "Invalid input")?,
            parts[1].parse::<u16>().map_err(|_| "Invalid input")?,
        ))
    } else {
        let point = s.parse::<u16>().map_err(|_| "Invalid input")?;
        Ok((point, point))
    }
}

struct Grid {
    cells: Vec<u8>,
    width: usize,
    height: usize,
}

impl Grid {
    fn from(input_string: &str) -> Result<Self, String> {
        let mut points: Vec<(u16, u16)> = Vec::new();
        let mut x_range = (u16::MAX, u16::MIN);
        let mut y_range = (u16::MAX, u16::MIN);

        for line in input_string.lines() {
            let mut parts: Vec<&str> = line.split(", ").collect();
            if parts.len() != 2 || parts[0].len() < 3 || parts[1].len() < 3 {
                return Err("Invalid input".to_string());
            }
            parts.sort_unstable();
            let (x_start, x_end) = parse_point_interval(&parts[0][2..])?;
            let (y_start, y_end) = parse_point_interval(&parts[1][2..])?;

            x_range = (min(x_range.0, x_start), max(x_range.1, x_end));
            y_range = (min(y_range.0, y_start), max(y_range.1, y_end));

            for x in x_start..=x_end {
                for y in y_start..=y_end {
                    points.push((x, y));
                }
            }
        }

        // Water pouring down at sides:
        x_range = (x_range.0 - 1, x_range.1 + 1);

        // +1 since ranges are inclusive:
        let width = ((x_range.1 - x_range.0) + 1) as usize;
        let height = ((y_range.1 - y_range.0) + 1) as usize;

        let mut cells = vec![b'.'; width * height];
        for point in points {
            let x = point.0 - x_range.0;
            let y = point.1 - y_range.0;
            cells[y as usize * width + x as usize] = b'#';
        }

        let water_x = 500;
        if !(x_range.0..x_range.1).contains(&water_x) {
            return Err("Spring outside scanned area".into());
        }
        let water_x_relative = water_x - x_range.0;
        // Place water on top (may exist above as well coming from the spring, but ignore as that's
        // above the minimum y value).
        cells[water_x_relative as usize] = b'|';

        Ok(Self {
            cells,
            width,
            height,
        })
    }

    #[cfg(feature = "debug-output")]
    fn print(&self, name: &str) {
        if env::var("ADVENT_DEBUG").is_err() {
            return;
        }
        println!("### {}", name);
        for y in 0..self.height {
            println!(
                "{}",
                String::from_utf8(self.cells[y * self.width..(y + 1) * self.width].to_vec())
                    .unwrap_or_else(|_| "Invalid utf-8".to_string())
                    .replace('.', " ")
                    .replace('#', "█")
            );
        }
        println!();
    }

    fn at(&self, x: u16, y: u16) -> u8 {
        self.cells[y as usize * self.width + x as usize]
    }

    fn set_water_at(&mut self, x: u16, y: u16, solid: bool) {
        self.cells[y as usize * self.width + x as usize] = if solid { b'w' } else { b'|' };
    }

    fn dry_at(&mut self, x: u16, y: u16) {
        self.cells[y as usize * self.width + x as usize] = b'.';
    }

    fn wall_in_direction(&self, x_start: u16, y: u16, x_direction: i32) -> bool {
        let mut x = (i32::from(x_start) + x_direction) as u16;
        loop {
            let cell = self.at(x, y);
            if !(cell == b'.' || cell == b'w' || cell == b'|') {
                break;
            }
            let below = self.at(x, y + 1);
            if !(below == b'#' || below == b'w') {
                return false;
            }
            x = (i32::from(x) + x_direction) as u16;
        }
        self.at(x, y) == b'#'
    }

    fn fill_in_direction(&mut self, x_start: u16, y: u16, x_direction: i32, solid: bool) {
        let mut x = (i32::from(x_start) + x_direction) as u16;
        loop {
            let cell = self.at(x, y);
            if !(cell == b'.' || cell == b'w' || cell == b'|') {
                break;
            }
            self.set_water_at(x, y, solid);
            let below = self.at(x, y + 1);
            if !(below == b'#' || below == b'w') {
                return;
            }
            x = (i32::from(x) + x_direction) as u16;
        }
    }

    fn spread_water_at(&mut self, x: u16, y: u16) -> u16 {
        self.set_water_at(x, y, false);

        if (y as usize) < self.height - 1 {
            let below = self.at(x, y + 1);
            if below == b'#' || below == b'w' {
                let left_wall = self.wall_in_direction(x, y, -1);
                let right_wall = self.wall_in_direction(x, y, 1);
                let surrounded_by_walls = left_wall && right_wall;
                self.fill_in_direction(x, y, -1, surrounded_by_walls);
                self.fill_in_direction(x, y, 1, surrounded_by_walls);
                if surrounded_by_walls {
                    self.set_water_at(x, y, true);
                }
                if surrounded_by_walls && y > 0 {
                    return self.spread_water_at(x, y - 1);
                }
            }
        }
        y
    }

    fn pour_water(&mut self) {
        let mut line = 1;
        while line < self.height {
            let mut top_y = line;
            let mut to_fill = Vec::new();
            for x in 0..self.width {
                if self.at(x as u16, line as u16 - 1) == b'|'
                    && self.at(x as u16, line as u16) == b'.'
                {
                    to_fill.push(x);
                }
            }
            for x in to_fill {
                top_y = min(top_y, self.spread_water_at(x as u16, line as u16) as usize);
            }
            line = top_y + 1;
        }
    }

    fn holds_in_direction(&self, x_start: u16, y: u16, x_direction: i32) -> bool {
        let mut x = (i32::from(x_start) + x_direction) as u16;
        loop {
            let cell = self.at(x, y);
            let below = self.at(x, y + 1);
            if !(below == b'#' || below == b'w') {
                return false;
            }
            if cell == b'#' {
                return true;
            }
            x = (i32::from(x) + x_direction) as u16;
        }
    }

    fn dry_up(&mut self) {
        let mut line = self.height as u16;
        while line > 0 {
            line -= 1;
            for x in 0..self.width {
                if self.at(x as u16, line) == b'w' {
                    let below = if line == (self.height as u16 - 1) {
                        b'.'
                    } else {
                        self.at(x as u16, line + 1)
                    };

                    if !((below == b'#' || below == b'w')
                        && self.holds_in_direction(x as u16, line, -1)
                        && self.holds_in_direction(x as u16, line, 1))
                    {
                        self.dry_at(x as u16, line);
                    }
                }
            }
        }
    }

    fn count_water(&self) -> usize {
        self.cells
            .iter()
            .fold(0, |n, c| n + usize::from(*c == b'w' || *c == b'|'))
    }

    fn count_drained_water(&self) -> usize {
        self.cells
            .iter()
            .fold(0, |n, c| n + usize::from(*c == b'w'))
    }
}

pub fn solve(input: &Input) -> Result<usize, String> {
    let mut grid = Grid::from(input.text)?;
    #[cfg(feature = "debug-output")]
    grid.print("Initial");

    grid.pour_water();
    #[cfg(feature = "debug-output")]
    grid.print("After pouring");

    if input.is_part_one() {
        Ok(grid.count_water())
    } else {
        grid.dry_up();
        #[cfg(feature = "debug-output")]
        grid.print("After drying up");
        Ok(grid.count_drained_water())
    }
}

#[test]
fn tests() {
    use crate::input::{test_part_one, test_part_two};

    test_part_one!(
            "x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504"
        => 57
    );

    test_part_two!(
            "x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504"
        => 29
    );

    let input = include_str!("day17_input.txt");
    test_part_one!(input => 31949);
    test_part_two!(input => 26384);
}