summaryrefslogtreecommitdiffstats
path: root/day14b/src/main.rs
blob: f1c384657c2a4e04555175f8dee3055fb399e56e (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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/// --- Part Two ---
///
/// You realize you misread the scan.  There isn't an endless void at the bottom of the scan -
/// there's floor, and you're standing on it!
///
/// You don't have time to scan the floor, so assume the floor is an infinite horizontal line with
/// a y coordinate equal to two plus the highest y coordinate of any point in your scan.
///
/// In the example above, the highest y coordinate of any point is 9, and so the floor is at y=11.
/// (This is as if your scan contained one extra rock path like -infinity,11 -> infinity,11.) With
/// the added floor, the example above now looks like this:
///
/// ```
///         ...........+........
///         ....................
///         ....................
///         ....................
///         .........#...##.....
///         .........#...#......
///         .......###...#......
///         .............#......
///         .............#......
///         .....#########......
///         ....................
/// <-- etc #################### etc -->
/// ```
///
/// To find somewhere safe to stand, you'll need to simulate falling sand until a unit of sand
/// comes to rest at 500,0, blocking the source entirely and stopping the flow of sand into the
/// cave.  In the example above, the situation finally looks like this after 93 units of sand come
/// to rest:
///
/// ```
/// ............o............
/// ...........ooo...........
/// ..........ooooo..........
/// .........ooooooo.........
/// ........oo#ooo##o........
/// .......ooo#ooo#ooo.......
/// ......oo###ooo#oooo......
/// .....oooo.oooo#ooooo.....
/// ....oooooooooo#oooooo....
/// ...ooo#########ooooooo...
/// ..ooooo.......ooooooooo..
/// #########################
/// ```
///
/// Using your scan, simulate the falling sand until the source of the sand becomes blocked.  How
/// many units of sand come to rest?
use clap::Parser;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::character::complete::i32;
use nom::combinator::{map, opt};
use nom::error::{ContextError, ErrorKind as NomErrorKind, ParseError};
use nom::multi::many1;
use nom::sequence::{terminated, tuple};
use nom::IResult;

use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::PathBuf;

const FILEPATH: &'static str = "examples/input.txt";
const SAND_SOURCE: Coords = Coords { x: 500, y: 0 };
const FLOOR_OFFSET: usize = 2;

pub type Input<'a> = &'a str;
pub type Result<'a, T> = IResult<Input<'a>, T, Error<Input<'a>>>;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    Nom(NomErrorKind),
    Context(&'static str),
    Custom(String),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Terrain {
    Air,
    Rock,
    Sand,
    SandSource,
}

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Cli {
    #[clap(short, long, default_value = FILEPATH)]
    file: PathBuf,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error<I> {
    pub errors: Vec<(I, ErrorKind)>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Coords {
    x: i32,
    y: i32,
}

impl Coords {
    fn path_between(&self, other: &Coords) -> Vec<Coords> {
        if self == other {
            panic!()
        }
        if self.x == other.x {
            let yrange = {
                if self.y > other.y {
                    other.y..=self.y
                } else if other.y > self.y {
                    self.y..=other.y
                } else {
                    panic!()
                }
            };
            yrange.map(|y| Coords { x: self.x, y }).collect_vec()
        } else {
            let xrange = {
                if self.x > other.x {
                    other.x..=self.x
                } else if other.x > self.x {
                    self.x..=other.x
                } else {
                    panic!()
                }
            };
            xrange.map(|x| Coords { x, y: self.y }).collect_vec()
        }
    }
}

#[derive(Clone, Debug)]
struct Grid {
    data: Vec<Vec<Terrain>>,
    bounds: GridBoundaries,
}

impl Grid {
    fn new(bounds: GridBoundaries) -> Self {
        let xlen = (bounds.maxx - bounds.minx) as usize + 1;
        let ylen = (bounds.maxy - bounds.miny) as usize + 1;
        let data = vec![vec![Terrain::Air; ylen]; xlen];
        Self { data, bounds }
    }

    fn get(&self, coord: &Coords) -> &Terrain {
        &self.data[(coord.x - self.bounds.minx) as usize][(coord.y - self.bounds.miny) as usize]
    }

    fn set(&mut self, coord: &Coords, terrain: Terrain) {
        self.data[(coord.x - self.bounds.minx) as usize][(coord.y - self.bounds.miny) as usize] =
            terrain;
    }

    fn populate(&mut self, geography: Vec<RockStructure>) {
        geography
            .into_iter()
            .map(|rstruct| {
                rstruct
                    .0
                    .as_slice()
                    .windows(2)
                    .map(|window| window[0].path_between(&window[1]))
                    .flatten()
                    .collect_vec()
            })
            .flatten()
            .scan(self, |state, coords| {
                state.data[(coords.x - state.bounds.minx) as usize]
                    [(coords.y - state.bounds.miny) as usize] = Terrain::Rock;
                Some(())
            })
            .last()
            .unwrap()
    }

    fn run(&mut self) -> usize {
        let mut count = 0;
        let mut pos = SAND_SOURCE;
        let mut history = vec![SAND_SOURCE];
        'block: loop {
            for (dx, dy) in [(0, 1), (-1, 1), (1, 1)] {
                let next_pos = Coords {
                    x: &pos.x + dx,
                    y: &pos.y + dy,
                };

                if (next_pos.x < self.bounds.minx)
                    || (next_pos.x > self.bounds.maxx)
                {
                    continue;
                }

                if self.get(&next_pos) == &Terrain::Air {
                    history.push(next_pos);
                    pos = next_pos;
                    continue 'block;
                }
            }

            count += 1;
            if pos == SAND_SOURCE {
                break 'block;
            }
            self.set(&pos, Terrain::Sand);
            pos = {
                loop {
                    let prev_pos = history[history.len() - 1];
                    match self.get(&prev_pos) {
                        Terrain::Air | Terrain::SandSource => break prev_pos,
                        _ => {
                            let _ = history.pop();
                            continue;
                        }
                    };
                }
            };
        }
        count
    }
}

#[derive(Clone, Debug)]
struct GridBoundaries {
    minx: i32,
    maxx: i32,
    miny: i32,
    maxy: i32,
}

impl GridBoundaries {
    fn new() -> Self {
        GridBoundaries {
            minx: i32::max_value(),
            maxx: i32::min_value(),
            miny: 0,
            maxy: i32::min_value(),
        }
    }

    fn combine(&mut self, other: &GridBoundaries) {
        self.minx = i32::min(self.minx, other.minx);
        self.maxx = i32::max(self.maxx, other.maxx);
        self.miny = i32::min(self.miny, other.miny);
        self.maxy = i32::max(self.maxy, other.maxy);
    }

    fn fold(&self, other: &Coords) -> Self {
        let mut res = GridBoundaries::new();
        res.minx = i32::min(self.minx, other.x);
        res.maxx = i32::max(self.maxx, other.x);
        res.miny = i32::min(self.miny, other.y);
        res.maxy = i32::max(self.maxy, other.y);
        res
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct RockStructure(Vec<Coords>);

impl<I> ParseError<I> for Error<I> {
    fn from_error_kind(input: I, kind: NomErrorKind) -> Self {
        let errors = vec![(input, ErrorKind::Nom(kind))];
        Self { errors }
    }

    fn append(input: I, kind: NomErrorKind, mut other: Self) -> Self {
        other.errors.push((input, ErrorKind::Nom(kind)));
        other
    }
}

impl<I> ContextError<I> for Error<I> {
    fn add_context(input: I, ctx: &'static str, mut other: Self) -> Self {
        other.errors.push((input, ErrorKind::Context(ctx)));
        other
    }
}

fn parse_coord(input: &str) -> Result<Coords> {
    map(tuple((terminated(i32, tag(",")), i32)), |(x, y)| Coords {
        x,
        y,
    })(input)
}

fn parse_line(input: &str) -> Result<RockStructure> {
    map(many1(terminated(parse_coord, opt(tag(" -> ")))), |v| {
        RockStructure(v)
    })(input)
}

fn main() {
    let args = Cli::parse();

    let file = File::open(&args.file).unwrap();
    let reader = BufReader::new(file);

    let mut bounds = GridBoundaries::new();
    let mut geography = reader
        .lines()
        .map(|l| parse_line(l.unwrap().as_str()).unwrap().1)
        .scan(&mut bounds, |state, rstruct| {
            state.combine(
                &rstruct
                    .0
                    .iter()
                    .fold(GridBoundaries::new(), |acc, x| acc.fold(x)),
            );
            Some(rstruct)
        })
        .collect_vec();

    bounds.maxy = bounds.maxy + FLOOR_OFFSET as i32;
    let max_x_len = 2 * bounds.maxy - 1;
    let minx = SAND_SOURCE.x - (max_x_len - 1) / 2;
    let maxx = SAND_SOURCE.x + (max_x_len - 1) / 2;
    assert!(minx < bounds.minx);
    assert!(maxx > bounds.maxx);
    bounds.minx = minx;
    bounds.maxx = maxx;

    geography.push(RockStructure(vec![
        Coords {
            x: minx,
            y: bounds.maxy,
        },
        Coords {
            x: maxx,
            y: bounds.maxy,
        },
    ]));

    let mut grid = Grid::new(bounds);
    grid.set(&SAND_SOURCE, Terrain::SandSource);
    grid.populate(geography);
    assert_eq!(grid.get(&SAND_SOURCE), &Terrain::SandSource);

    let res = grid.run();
    println!("{res:?}");
}