typealias Layout = List fun Layout.asString() = this.joinToString("/") fun Layout.count() = this.map { it.sumBy { if (it == '#') 1 else 0 } }.sum() fun Layout.flipHorizontal() = this.map { it.reversed() } fun Layout.rotateClockwise(): Layout { return (0 until size).map { x -> (0 until size).map { y -> this[y][x] }.joinToString("").reversed() } } fun Layout.transform(patterns: Map): Layout { return splitIntoBlocks() // Split Layout into 2x2 or 3x3 Blocks .map { it.map { l -> patterns.getValue(l.asString()) } } // Lookup appropriate Pattern for each Block .join() // Recombine the Patterns into a single, larger Layout } fun Layout.splitIntoBlocks(): List> { val width = if (this.size % 2 == 0) 2 else 3 return (0 until size step width).map { y -> (0 until size step width) .map { x -> (0 until width) .map { this[y + it].slice(x until x + width) } } } } /** * For a given layout generate all the possible rotations and reflections. */ fun Layout.permutations(): Set { return listOf(this, this.flipHorizontal()) .map { p -> (0..3).accumulate(p) { p, _ -> p.rotateClockwise() } } .flatten().map(Layout::asString) .toSet() } /** * Recombine the Blocks into a Layout */ fun List>.join() : Layout { val layoutSize = this[0][0].size return (0 until size).map { row -> (0 until layoutSize) .map { y -> (0 until size).map{ x-> this[row][x][y]} .joinToString("") } }.flatten() } fun String.extractPatterns(): List> { val (a, b) = this.split(" => ") val rows = a.split("/") val layout = b.split("/") return rows.permutations().map { it to layout } } fun runTransforms(patterns: Map, n:Int): Int { val finalLayout: Layout = (1..n).fold(START) { layout, _ -> layout.transform(patterns) } return finalLayout.count() } fun main(args: Array) { val patterns = input.split("\n").map { it.extractPatterns() }.flatten().toMap() println(runTransforms(patterns,5)) println(runTransforms(patterns,18)) } val START = listOf(".#.", "..#", "###")