From 47da5f850703a77c76a88c0c7a10418c06aaf251 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 1 Dec 2024 13:39:53 +0100 Subject: [PATCH] chore(lib): include helpers from last Kotlin run Signed-off-by: Matej Focko --- src/Utils.kt | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/Utils.kt b/src/Utils.kt index 7ff1419..b158c9f 100644 --- a/src/Utils.kt +++ b/src/Utils.kt @@ -1,12 +1,6 @@ +import java.io.File import java.math.BigInteger import java.security.MessageDigest -import kotlin.io.path.Path -import kotlin.io.path.readText - -/** - * Reads lines from the given input txt file. - */ -fun readInput(name: String) = Path("src/$name.txt").readText().trim().lines() /** * Converts string to md5 hash. @@ -19,3 +13,37 @@ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteA * The cleaner shorthand for printing output. */ fun Any?.println() = println(this) + +private fun openFile(day: Int, name: String) = File("inputs/day%02d".format(day), "$name.txt") + +/** + * Reads lines from the given input txt file. + */ +fun readInput(day: Int, name: String) = openFile(day, name).readText().trim().lines() + +fun readInputAsString(day: Int, name: String) = openFile(day, name).readText() +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() } + +fun readGraph(day: Int, name: String) = readInput(day, name).fold(mapOf>()) { currentGraph, edge -> + val (fromVertex, toVertex) = edge.split("-") + val fromNeighbours = currentGraph.getOrDefault(fromVertex, emptySet()) + toVertex + val toNeighbours = currentGraph.getOrDefault(toVertex, emptySet()) + fromVertex + + currentGraph + mapOf(fromVertex to fromNeighbours, toVertex to toNeighbours) +}.toMap() + +fun product(xs: Sequence, ys: Sequence): Sequence> = + xs.flatMap { x -> ys.map { y -> x to y } } + +fun product(xs: Sequence, ys: Sequence, zs: Sequence): Sequence> = + xs.flatMap { x -> ys.flatMap { y -> zs.map { z -> Triple(x, y, z) } } } + +fun product(xs: Iterable, ys: Iterable): Sequence> = + product(xs.asSequence(), ys.asSequence()) + +fun product(xs: Iterable, ys: Iterable, zs: Iterable): Sequence> = + product(xs.asSequence(), ys.asSequence(), zs.asSequence())