import java.io.File import java.math.BigInteger import java.security.MessageDigest /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * 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())