generated from Jadarma/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathY2023D15.kt
76 lines (61 loc) · 3.04 KB
/
Y2023D15.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D15 : Solution {
/**
* A lens boxing operation.
* @property label The label of the lens to apply the operation on.
* @property box The ID of the box the operation should be performed in.
*/
private sealed class Operation(val label: String) {
val box: Int = hash(label)
/** An operation that should remove a lens from a box. */
class Remove(label: String) : Operation(label)
/** An operation that should replace or add a lens to a box. */
class Add(label: String, val focalLength: Int) : Operation(label)
}
/** A lens with a [focalLength] and identified by a [label]. */
private data class Lens(val label: String, val focalLength: Int)
/** An array of 256 boxes with lenses. */
private class HashBox {
private val boxes: Map<Int, MutableList<Lens>> = (0..<256).associateWith { mutableListOf() }
/** Apply the [operation] on the boxes and update their state. */
fun apply(operation: Operation): HashBox = apply {
val box = boxes.getValue(operation.box)
when (operation) {
is Operation.Add -> {
val lens = Lens(operation.label, operation.focalLength)
val existingLens = box.indexOfFirst { it.label == operation.label }
if (existingLens == -1) box.add(lens)
else box[existingLens] = lens
}
is Operation.Remove -> box.removeIf { it.label == operation.label }
}
}
/** Returns the total focusing power of all the lenses in all the boxes. */
val focusingPower: Int
get() = boxes.entries
.flatMap { (box, lenses) -> lenses.mapIndexed { slot, lens -> Triple(box, slot, lens) } }
.sumOf { (box, slot, lens) -> box.inc() * slot.inc() * lens.focalLength }
}
/** Calculates the Holiday ASCII String Helper value for the [string]. */
private fun hash(string: String): Int = string.fold(0) { hash, c -> hash.plus(c.code).times(17).rem(256) }
/** Parses the [input] and returns the list of [Operation]s described in the manual. */
private fun parseInput(input: String): List<Operation> = parse {
val addRegex = Regex("""^([a-z]+)=(\d)$""")
val removeRegex = Regex("""^([a-z]+)-$""")
input
.split(',')
.map {
val add = addRegex.matchEntire(it)
val remove = removeRegex.matchEntire(it)
when {
add != null -> Operation.Add(add.groupValues[1], add.groupValues[2].toInt())
remove != null -> Operation.Remove(remove.groupValues[1])
else -> error("Input does not match regex.")
}
}
}
override fun partOne(input: String) = input.split(',').sumOf(::hash)
override fun partTwo(input: String) = parseInput(input).fold(HashBox(), HashBox::apply).focusingPower
}