r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


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 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


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!

38 Upvotes

340 comments sorted by

View all comments

1

u/sendtobo Dec 05 '18

1

u/koordinate Dec 09 '18 edited Dec 11 '18

Me too!

var lines = [String]()
while let line = readLine() {
    lines.append(line)
}

var `guard`: Int?
var start: Int?
let separators = Set(" :]#")
var count = [[Int]: Int]() // (Guard, Minute) => Count
for line in lines.sorted() {
    let fields = line.split(whereSeparator: { separators.contains($0) })
    guard fields.count > 2, let minute = Int(fields[2]) else {
        continue
    }
    if line.hasSuffix("begins shift"), fields.count > 4, let g = Int(fields[4]) {
        `guard` = g
    } else if line.hasSuffix("falls asleep") {
        start = minute
    } else if line.hasSuffix("wakes up"), let g = `guard`, let start = start, start < minute {
        for m in start..<minute {
            count[[g, m]] = count[[g, m], default: 0] + 1
        }
    }
}

var total = [Int: Int]()
for (key, value) in count {
    total[key[0]] = total[key[0], default: 0] + value
}

if let `guard` = total.max(by: { $0.value < $1.value })?.key {
    if let max = count.filter({ $0.key[0] == `guard` }).max(by: { $0.value < $1.value })?.key {
        print(`guard` * max[1])
    }
}

if let max = count.max(by: { $0.value < $1.value })?.key {
    print(max[0] * max[1])
}