-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay09.kt
59 lines (50 loc) · 1.52 KB
/
Day09.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* Copyright (c) 2018 by Todd Ginsberg
*/
/**
* Advent of Code 2018, Day 9 - Marble Mania
*
* Problem Description: http://adventofcode.com/2018/day/9
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day9/
*/
package com.ginsberg.advent2018
import java.util.ArrayDeque
import java.util.Deque
import kotlin.math.absoluteValue
class Day09(private val players: Int, private val highest: Int) {
fun solvePart1(): Long =
play(players, highest)
fun solvePart2(): Long =
play(players, highest * 100)
private fun play(numPlayers: Int, highest: Int): Long {
val scores = LongArray(numPlayers)
val marbles = ArrayDeque<Int>().also { it.add(0) }
(1..highest).forEach { marble ->
when {
marble % 23 == 0 -> {
scores[marble % numPlayers] += marble + with(marbles) {
shift(-7)
removeFirst().toLong()
}
marbles.shift(1)
}
else -> {
with(marbles) {
shift(1)
addFirst(marble)
}
}
}
}
return scores.max()!!
}
private fun <T> Deque<T>.shift(n: Int): Unit =
when {
n < 0 -> repeat(n.absoluteValue) {
addLast(removeFirst())
}
else -> repeat(n) {
addFirst(removeLast())
}
}
}