Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private data class Pos(val x:Int, val y:Int)
- fun main() {
- var input = getInputLines(2020, 24)
- val directions = listOf("e", "se", "sw", "w", "nw", "ne")
- fun parse(s:String): MutableList<String> {
- val out = mutableListOf<String>()
- var i = 0
- while(i<s.length) {
- val n = if (s[i] in listOf('e', 'w')) 1 else 2
- out.add(s.substring(i, i + n))
- i+=n
- }
- return out
- }
- fun move(p:Pos, dir:String) =
- when(dir) {
- "e" -> { Pos(p.x + 1, p.y) }
- "w" -> { Pos(p.x - 1, p.y)}
- "se" -> { Pos(p.x + 1, p.y - 1) }
- "sw" -> { Pos(p.x, p.y - 1) }
- "ne" -> { Pos(p.x, p.y + 1) }
- "nw" -> { Pos(p.x - 1, p.y + 1) }
- else -> throw RuntimeException("Unknown direction $dir")
- }
- var blacks = input.map { parse(it).fold(Pos(0, 0)) { p, d -> move(p, d)}}
- .groupBy { it }.map { it.key to it.value.size }
- .filterNot { it.second % 2 == 0 }.map { it.first }
- println(blacks.size)
- for(i in 1..100) {
- // number of black tiles around
- val ba = blacks.flatMap { b -> directions.map {move(b, it) } }
- .groupBy { it }.map { it.key to it.value.size }.toMap()
- // black tiles turning white
- val b2w = blacks.filter { ba[it] == null || ba[it]!!>2 }
- // white tiles turning black
- val w2b = ba.toList().filter { it.second == 2 }.map { it.first }.toSet().minus(blacks)
- // update black tiles
- blacks = blacks.minus(b2w).plus(w2b)
- }
- println(blacks.size)
- }
Advertisement
Add Comment
Please, Sign In to add comment