Created
December 20, 2021 21:42
-
-
Save bartoszm/f76854561b37210542bac87033c9e4a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package day20 | |
import java.nio.file.Files | |
import java.nio.file.Path | |
class Enhancer(val code: String) { | |
private fun getPixel(r: Int, c: Int, data: List<String>) = data.getOrNull(r)?.getOrNull(c) ?: defaultChar | |
private var defaultChar = '.' | |
fun enhance(input: List<String>): List<String> { | |
val rows = input.size | |
val cols = input[0].length | |
fun getValue(r: Int,c: Int): Char { | |
val pixels = (r-1..r+1).flatMap { rr -> (c-1..c+1).map { cc -> getPixel(rr,cc, input) } } | |
val idx = pixels | |
.map { p -> if(p == '#') 1 else 0 } | |
.fold(0){acc, next -> (acc shl 1) + next } | |
return code[idx] | |
} | |
val newData = (-1..rows).map { r -> | |
(-1..cols).map { c -> | |
getValue(r, c) | |
}.joinToString("") | |
} | |
defaultChar = if(defaultChar == '.') code[0] else code[code.lastIndex] | |
return newData | |
} | |
} | |
fun enhance(enhancer: Enhancer, data: List<String>, times: Int): List<String> { | |
var current = data | |
(1..times).forEach { | |
current = enhancer.enhance(current) | |
} | |
return current | |
} | |
fun main(args: Array<String>) { | |
val input = Files.readAllLines(Path.of(args[0])) | |
val data = input.drop(1).filter { it.isNotEmpty() } | |
val enhancer = Enhancer(input.first()!!) | |
val res = enhance(enhancer, data, 50) | |
println("${res.size} x ${res[0].length}") | |
println(res.sumOf { s -> s.count { it == '#' } }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment