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())