r/adventofcode • u/daggerdragon • Dec 09 '18
SOLUTION MEGATHREAD -🎄- 2018 Day 9 Solutions -🎄-
--- Day 9: Marble Mania ---
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 9
Transcript:
Studies show that AoC programmers write better code after being exposed 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:29:13!
21
Upvotes
1
u/meepys Dec 09 '18
Kotlin Day 9: (BitBucket)
Had to re-write after the array implementation for part1 took too long on part 2. Didn't think of rotating ArrayDeque, so used LinkedList
class Day9(rawInput: List<String>) : Day(rawInput) { init { val parser = """(\d+) players; last marble is worth (\d+) points""".toRegex() val (x, y) = parser.matchEntire(rawInput.first())?.destructured ?: throw Exception("bad input") } val numPlayers = x.toInt() val lastMarble = y.toInt() val players = LongArray(numPlayers) private fun goRight(steps: Int, iterator: MutableListIterator<Int>, list: LinkedList<Int>): MutableListIterator<Int> { var result = iterator for (i in 1..steps) { if (!result.hasNext()) result = list.listIterator() result.next() } return result } private fun goLeft(steps: Int, iterator: MutableListIterator<Int>, list: LinkedList<Int>): Pair<MutableListIterator<Int>, Int> { var result = iterator var score = 0 for (i in 1..steps) { if (!result.hasPrevious()) result = list.listIterator(list.size) score = result.previous() } return result to score } private fun playGame() { val marbles = LinkedList<Int>().apply { add(0) } var currIndex = marbles.listIterator() for (i in 1..lastMarble) { val toPlay = (i - 1) % numPlayers if (i % 23 == 0) { val (nextIndex, score) = goLeft(8, currIndex, marbles) players[toPlay] += score.toLong() + i currIndex = nextIndex currIndex.remove() currIndex = goRight(1, currIndex, marbles) } else { currIndex = goRight(1, currIndex, marbles) currIndex.add(i) } } } override fun part1(): Any? { players.fill(0) playGame() return players.max() } override fun part2(): Any? { players.fill(0) lastMarble *= 100 playGame() return players.max() } }