From d7cde13a2e35fe4ac4c10e1b999d23d08f06d10a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 6 Dec 2021 10:35:12 +0100 Subject: [PATCH] day(06): add solution Signed-off-by: Matej Focko --- src/Utils.kt | 8 +++++++- src/day06/Day06.kt | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/day06/Day06.kt diff --git a/src/Utils.kt b/src/Utils.kt index 4b2bd58..879a2c7 100644 --- a/src/Utils.kt +++ b/src/Utils.kt @@ -2,12 +2,18 @@ import java.io.File import java.math.BigInteger import java.security.MessageDigest +private fun openFile(day: Int, name: String) = File("src/day%02d".format(day), "$name.txt") + /** * Reads lines from the given input txt file. */ -fun readInput(day: Int, name: String) = File("src/day%02d".format(day), "$name.txt").readLines() +fun readInput(day: Int, name: String) = openFile(day, name).readLines() fun readInputAsInts(day: Int, name: String) = readInput(day, name).map { it.toInt() } +fun readInputAsCommaSeparatedInts(day: Int, name: String) = openFile(day, name) + .readText() + .split(",") + .map { it.toInt() } /** * Converts string to md5 hash. diff --git a/src/day06/Day06.kt b/src/day06/Day06.kt new file mode 100644 index 0000000..8b56d4a --- /dev/null +++ b/src/day06/Day06.kt @@ -0,0 +1,29 @@ +package day06 + +import readInputAsCommaSeparatedInts + +fun howManyAfter(input: List, days: Int): Long { + var counts = List(9) { i -> input.count { it == i }.toLong() } + + for (day in 1..days) { + counts = List(9) { i -> + when (i) { + 6 -> counts[0] + counts[7] + else -> counts[(i + 1) % 9] + } + } + } + + return counts.sum() +} + +fun main() { + val testInput = readInputAsCommaSeparatedInts(6, "test_input") + val input = readInputAsCommaSeparatedInts(6, "input") + + check(howManyAfter(testInput, 80) == 5934.toLong()) + println(howManyAfter(input, 80)) + + check(howManyAfter(testInput, 256) == 26984457539) + println(howManyAfter(input, 256)) +}