r/adventofcode • • Dec 13 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 13 Solutions -🎄-

--- Day 13: Mine Cart Madness ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 13

Transcript:

Elven chronomancy: for when you absolutely, positively have to ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 00:44:25!

24 Upvotes

148 comments sorted by

View all comments

Show parent comment

1

u/japanuspus Dec 14 '18

I decided to keep the position out of the Cart state, and this actually worked out nicely. Also, I ended up using raw numbers for the heading, since I found that the state transitions could be written in a closed algebraic form:

#[derive(Debug, Clone, Copy)]
pub struct Cart {
    heading: u8, //>v<^
    turn: u8, // left, straight, right  -- mod 3
}

impl Cart {
    pub fn nextpos(& self, ij: &(usize, usize)) -> (usize, usize) {
        match self.heading {
            0 => (ij.0, ij.1+1), //>
            1 => (ij.0+1, ij.1), //v
            2 => (ij.0, ij.1-1), //<
            3 => (ij.0-1, ij.1), //^
            _ => panic!()
        }
    }

    pub fn nextcart(&self, c: u8) -> Cart {
        match c {
            b'|' | b'-' => self.clone(),
            b'\\' => Cart {heading: ((-(self.heading as i8) + 1 + 4) % 4) as u8, turn: self.turn},
            b'/'  => Cart {heading: ((-(self.heading as i8) + 3 + 4) % 4) as u8, turn: self.turn},
            b'+'  => Cart {heading: (self.heading + self.turn + 3) % 4, turn: (self.turn + 1) % 3},  
            _ => panic!()
        }
    }
}

Parsing the input into this setup was super nice. The cart positions are stored in a BTreeMap to allow me to pull them out in the required order.

type Board = Vec<Vec<u8>>;
type Carts = BTreeMap<(usize, usize), Cart>;

pub fn parse_board(d: &str) -> (Board, Carts) {
    let mut carts: Carts = BTreeMap::new();
    let board: Board = d.lines().enumerate().map(|(i, r)| {
        r.as_bytes().iter().enumerate().map(|(j, c)| 
            match c {
                b'>' => {carts.insert((i, j), Cart {heading: 0,  turn: 0}); &b'-'},
                b'v' => {carts.insert((i, j), Cart {heading: 1,  turn: 0}); &b'|'},
                b'<' => {carts.insert((i, j), Cart {heading: 2,  turn: 0}); &b'-'},
                b'^' => {carts.insert((i, j), Cart {heading: 3,  turn: 0}); &b'|'},
                cc => cc,
            }
        ).cloned().collect()
    }).collect();
    (board, carts)
}

In each step of the simulation, I clone out the position of the carts in the order they need to be processed -- and then go from there:

pub fn part1_01(d: &str) -> (usize, usize) {
    let (board, mut carts) = parse_board(d);

    'outer: loop {
        let cart_positions: Vec<(usize, usize)> = carts.keys().cloned().collect();
        for pos in cart_positions {
            let cart = carts.remove(&pos).unwrap();
            let p2 = cart.nextpos(&pos);
            if carts.contains_key(&p2) {
                break 'outer p2;
            }
            carts.insert(p2, cart.nextcart(board[p2.0][p2.1]));
        }
    }
}

pub fn part2_01(d: &str) -> (usize, usize) {
    let (board, mut carts) = parse_board(d);

    'outer: loop {
        let cart_positions: Vec<(usize, usize)> = carts.keys().cloned().collect();
        for pos in cart_positions {
            if let Some(cart) = carts.remove(&pos) {
                let p2 = cart.nextpos(&pos);
                if carts.contains_key(&p2) {
                    carts.remove(&p2);
                } else {
                    carts.insert(p2, cart.nextcart(board[p2.0][p2.1]));
                }
            }
        }
        if carts.len()<2 {
            break 'outer carts.keys().next().unwrap().clone()
        }
    }
}

1

u/udoprog Dec 14 '18

Nicely done! I did a trade-off to be a bit more verbose to ease troubleshooting.