aboutsummaryrefslogtreecommitdiff
path: root/2021-kotlin/src/Day14.kt
diff options
context:
space:
mode:
authortchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 12:01:44 +0200
committertchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 12:01:44 +0200
commit34c2414304d59e76d52b96efe6bebebb4e75f086 (patch)
tree2b78254a2a909521993caa459b24ab68fae43324 /2021-kotlin/src/Day14.kt
parent8742021f42d2c5417abad25bfdb6d7abbf6e759e (diff)
downloadgleam_aoc2020-34c2414304d59e76d52b96efe6bebebb4e75f086.tar.gz
gleam_aoc2020-34c2414304d59e76d52b96efe6bebebb4e75f086.zip
Move year 2021 into a subfolder
Diffstat (limited to '2021-kotlin/src/Day14.kt')
-rw-r--r--2021-kotlin/src/Day14.kt46
1 files changed, 46 insertions, 0 deletions
diff --git a/2021-kotlin/src/Day14.kt b/2021-kotlin/src/Day14.kt
new file mode 100644
index 0000000..920ea9e
--- /dev/null
+++ b/2021-kotlin/src/Day14.kt
@@ -0,0 +1,46 @@
+object Day14 {
+ private fun getPolymerLetterCounts(input: List<String>, iterations: Int): Long {
+ val template = input.first()
+ val rules = input.drop(2).associate {
+ val (pattern, replacement) = it.split(" -> ")
+ (pattern[0] to pattern[1]) to replacement.first()
+ }
+
+ var pairCounts = template
+ .zipWithNext()
+ .groupingBy { it }
+ .eachCount()
+ .mapValues { (_, v) -> v.toLong() }
+
+ repeat(iterations) {
+ val newCounts = mutableMapOf<Pair<Char, Char>, Long>()
+
+ pairCounts.forEach { (pair, count) ->
+ newCounts.merge(rules[pair]!! to pair.second, count, Long::plus)
+ newCounts.merge(pair.first to rules[pair]!!, count, Long::plus)
+ }
+
+ pairCounts = newCounts
+ }
+
+ val letterCounts = mutableMapOf<Char, Long>()
+ pairCounts.forEach { (pair, count) -> letterCounts.merge(pair.second, count, Long::plus) }
+ letterCounts.merge(template.first(), 1, Long::plus)
+
+ return letterCounts.values.let { it.maxOrNull()!! - it.minOrNull()!! }
+ }
+
+ fun part1(input: List<String>): Long = getPolymerLetterCounts(input, 10)
+
+ fun part2(input: List<String>): Long = getPolymerLetterCounts(input, 40)
+}
+
+fun main() {
+ val testInput = readInputAsLines("Day14_test")
+ check(Day14.part1(testInput) == 1588L)
+ check(Day14.part2(testInput) == 2188189693529L)
+
+ val input = readInputAsLines("Day14")
+ println(Day14.part1(input))
+ println(Day14.part2(input))
+}