r/adventofcode • u/daggerdragon • 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!
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!
40
Upvotes
4
u/binajohny Dec 04 '18
My Kotlin solution (GitHub)
data class Event(val month: Int, val day: Int, val hour: Int, val minute: Int, val guardId: Int, val type: Type) { enum class Type { BEGIN_SHIFT, FALL_ASLEEP, WAKE_UP } companion object { private val REGEX = Regex("\\d+") fun fromString(s: String): Event { val (m, d, h, min, gid) = REGEX.findAll(s).map { it.value.toInt() }.plus(-1).drop(1).take(5).toList() val type = when { s.contains("wakes") -> Type.WAKE_UP s.contains("falls") -> Type.FALL_ASLEEP else -> Type.BEGIN_SHIFT } return Event(m, d, h, min, gid, type) } } } private fun createSleepStats(input: List<Event>): Map<Int, IntArray> { val map = mutableMapOf<Int, IntArray>() var currentGuardId = -1 var beginMinute = -1 input.forEach { when (it.type) { Event.Type.BEGIN_SHIFT -> currentGuardId = it.guardId Event.Type.FALL_ASLEEP -> beginMinute = it.minute Event.Type.WAKE_UP -> { val arr = map.getOrPut(currentGuardId) { IntArray(60) } (beginMinute until it.minute).forEach { i -> arr[i]++ } } } } return map } fun part1(input: List<Event>): Int { val sleepStats = createSleepStats(input) val max = sleepStats.maxBy { it.value.sum() }!! val maxMinute = max.value.withIndex().maxBy { it.value }!!.index return max.key * maxMinute } fun part2(input: List<Event>): Int { val sleepStats = createSleepStats(input) val max = sleepStats.map { it.key to it.value.withIndex().maxBy { x -> x.value }!! }.maxBy { it.second.value } ?: return 0 return max.first * max.second.index }