Skip to main content

aoc/year2018/
day13.rs

1//! # Mine Cart Madness
2//!
3//! Simulates the mine carts for both parts. When checking the grid we only care about `\`, `/`
4//! and `+` characters, all other characters can be ignored. Carts are sorted by `y` and then by
5//! `x` before each tick as the movement order is important to resolve collisions or near misses
6//! correctly.
7use crate::util::grid::*;
8use crate::util::point::*;
9
10pub struct Input {
11    grid: Grid<u8>,
12    carts: Vec<Cart>,
13}
14
15#[derive(Clone, Copy)]
16struct Cart {
17    position: Point,
18    direction: Point,
19    turns: u8,
20    active: bool,
21}
22
23impl Cart {
24    fn new(position: Point, direction: Point) -> Self {
25        Self { position, direction, turns: 0, active: true }
26    }
27
28    fn tick(&mut self, grid: &Grid<u8>) {
29        self.position += self.direction;
30
31        match grid[self.position] {
32            b'\\' => self.direction = Point::new(self.direction.y, self.direction.x),
33            b'/' => self.direction = Point::new(-self.direction.y, -self.direction.x),
34            b'+' => {
35                self.direction = match self.turns {
36                    0 => self.direction.counter_clockwise(),
37                    1 => self.direction,
38                    _ => self.direction.clockwise(), // 2 turns
39                };
40                self.turns = (self.turns + 1) % 3;
41            }
42            _ => (),
43        }
44    }
45}
46
47pub fn parse(input: &str) -> Input {
48    let grid = Grid::parse(input);
49    let mut carts = Vec::new();
50
51    for point in grid.points() {
52        let b = grid[point];
53        if matches!(b, b'^' | b'v' | b'<' | b'>') {
54            carts.push(Cart::new(point, Point::from(b)));
55        }
56    }
57
58    Input { grid, carts }
59}
60
61pub fn part1(input: &Input) -> String {
62    let mut carts = input.carts.clone();
63    let mut occupied = input.grid.same_size_with(false);
64
65    loop {
66        // Turn order is important.
67        carts.sort_unstable_by_key(|c| (c.position.y, c.position.x));
68
69        for cart in &mut carts {
70            // Follow tracks to next position.
71            occupied[cart.position] = false;
72            cart.tick(&input.grid);
73            let next = cart.position;
74
75            if occupied[next] {
76                return format!("{},{}", next.x, next.y);
77            }
78
79            occupied[next] = true;
80        }
81    }
82}
83
84pub fn part2(input: &Input) -> String {
85    let mut carts = input.carts.clone();
86    let mut occupied = input.grid.same_size_with(false);
87
88    while carts.len() > 1 {
89        // Turn order is important.
90        carts.sort_unstable_by_key(|c| (c.position.y, c.position.x));
91
92        for i in 0..carts.len() {
93            // Crashed carts may not have been removed yet.
94            if carts[i].active {
95                // Follow tracks to next position.
96                occupied[carts[i].position] = false;
97                carts[i].tick(&input.grid);
98                let next = carts[i].position;
99
100                if occupied[next] {
101                    // Mark both carts as crashed.
102                    carts.iter_mut().filter(|c| c.position == next).for_each(|c| c.active = false);
103                }
104
105                occupied[next].toggle();
106            }
107        }
108
109        // Remove crashed carts to speed up future ticks.
110        carts.retain(|c| c.active);
111    }
112
113    let last = carts[0].position;
114    format!("{},{}", last.x, last.y)
115}