operator fun Pair.plus(other: Pair) = this.first + other.first to this.second + other.second fun followPath(lines: List): String { var currentPos = lines[0].indexOf("|") to 0 var currentDir = 0 to 1 var steps = 0 val visitedLetters = mutableListOf() loop@ while (currentPos.first >= 0 && currentPos.second >= 0 && currentPos.second < lines.size && currentPos.first < lines[currentPos.second].length) { val c = lines[currentPos.second][currentPos.first] when { c == '+' -> currentDir = doTurn(lines, currentPos, currentDir) c.isLetter() -> visitedLetters.add(c) c in listOf('|', '-') -> { } else -> break@loop } currentPos += currentDir steps ++ } println(steps) return visitedLetters.joinToString("") } fun List.charAt(x:Int, y:Int) : Char { return try { this[y][x] } catch (e:StringIndexOutOfBoundsException) { return ' ' } } fun doTurn(lines: List, currentPos: Pair, currentDir: Pair): Pair { var nextDir: Pair? = null if (currentDir.first != 0) { if (currentPos.second > 0 && lines.charAt(currentPos.first, currentPos.second - 1) == '|') { nextDir = 0 to -1 } else if (currentPos.second < (lines.size - 1) && lines.charAt(currentPos.first, currentPos.second + 1) == '|') { nextDir = 0 to 1 } } else { if (currentPos.first > 0 && lines.charAt(currentPos.first - 1, currentPos.second) == '-') { nextDir = -1 to 0 } else if (lines.charAt(currentPos.first + 1, currentPos.second) == '-') { nextDir = 1 to 0 } } return if (nextDir != null) nextDir else throw IllegalArgumentException("Failed to turn at $currentPos : $currentDir") } fun main(args: Array) { val lines = input.split("\n") println(followPath(lines)) }