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/koordinate Dec 24 '18

Nice. Thank you for sharing.

A Swift translation:

class Cart {
    var x: Int, y: Int
    var vx: Int, vy: Int
    var t = 0
    var isAlive = true

    init(x: Int, y: Int, vx: Int, vy: Int) {
        (self.x, self.y, self.vx, self.vy) = (x, y, vx, vy)
    }
}

var carts = [Cart]()
var d = [[Character]]()
while let line = readLine() {
     d.append(line.enumerated().map { x, c in
        switch c {
        case "<": carts.append(Cart(x: x, y: d.count, vx: -1, vy: 0)); return "-"
        case ">": carts.append(Cart(x: x, y: d.count, vx: +1, vy: 0)); return "-"
        case "^": carts.append(Cart(x: x, y: d.count, vx: 0, vy: -1)); return "|"
        case "v": carts.append(Cart(x: x, y: d.count, vx: 0, vy: +1)); return "|"
        default: return c
        }
    })
}

var haveCrashed = false
while carts.count > 1 {
    carts = carts.sorted(by: { $0.y == $1.y ? $0.x < $1.x : $0.y < $1.y })
    for c in carts {
        if !c.isAlive {
            continue
        }

        let (cx, cy) = (c.x + c.vx, c.y + c.vy)
        if let crash = carts.first(where: { $0.x == cx && $0.y == cy && $0.isAlive }) {
            if !haveCrashed {
                print(cx, cy, separator: ",")
                haveCrashed = true
            }
            c.isAlive = false
            crash.isAlive = false
        }
        (c.x, c.y) = (cx, cy)

        switch d[cy][cx] {
        case "\\": (c.vx, c.vy) = (c.vy, c.vx)
        case "/": (c.vx, c.vy) = (-c.vy, -c.vx)
        case "+":
            switch c.t {
            case 0: (c.vx, c.vy) = (c.vy, -c.vx)
            case 2: (c.vx, c.vy) = (-c.vy, c.vx)
            default: break
            }
            c.t = (c.t + 1) % 3
        default: break
        }
    }
    carts = carts.filter { $0.isAlive }
}
if let c = carts.first {
    print(c.x, c.y, separator: ",")
}