import java.io.File fun updateScanners(depths: MutableMap, scannerPos: MutableMap, scannerDirection: MutableMap){ depths.forEach { t, u -> val absent = !scannerPos.contains(t) val position = scannerPos.computeIfAbsent(t) { -1 } val direction = scannerDirection.computeIfAbsent(t) { 1 } val nextPosition = (position + direction) if(nextPosition == u - 1 || (nextPosition == 0 && !absent)) scannerDirection.put(t, -direction) scannerPos.put(t, nextPosition) } } fun main(args: Array) { // val sourceFile = File("../puzzle_13.txt") val sourceFile = File("test.txt") val allLines = sourceFile.readLines() val firstLine = allLines.first() val depthMap = mutableMapOf() allLines.forEach { depthMap.put(it.split(": ")[0].toInt(), it.split(": ")[1].toInt()) } val scannerPos = mutableMapOf() val scannerDir = mutableMapOf() var currentIndex = 0 var cost = 0 val goalIndex = depthMap.keys.sorted().last() while(currentIndex <= goalIndex) { updateScanners(depthMap, scannerPos, scannerDir) if(!depthMap.containsKey(currentIndex)) {} else if(scannerPos[currentIndex]!! == 0) cost += depthMap[currentIndex]!! * currentIndex currentIndex++ } println(cost) }