import java.io.File fun nextIndex(x: Int, y: Int, dir: Int) = listOf(1 + x to y, x to y-1, x-1 to y, x to y+1)[dir] fun canMove(x: Int, y: Int, dir: Int, path: List): Boolean { val (newX, newY) = nextIndex(x, y, dir) return (newY in 0 until path.size) && (newX in 0 until path[newY].size) && path[newY][newX] != ' ' } fun main(args: Array) { val file = File("../puzzle_19.txt") val path = file.readLines().toList().map { it.toCharArray() } var (indexX, indexY) = (163 to 0) var direction = 3 val letterStack = mutableListOf() var count = 1 while(true){ if(path[indexY][indexX] in ('A'..'Z')) letterStack.add(path[indexY][indexX]) if(!canMove(indexX, indexY, direction, path)) { direction = (direction + 1) % 4 } if(!canMove(indexX, indexY, direction, path)) { direction = (direction + 2) % 4 } if(!canMove(indexX, indexY, direction, path)) break count++ val moveBy = nextIndex(indexX, indexY, direction) indexX = moveBy.first indexY = moveBy.second } println(letterStack.joinToString("")) println(count) }