Guest User

Untitled

a guest
Dec 24th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. private data class Pos(val x:Int, val y:Int)
  2.  
  3. fun main() {
  4. var input = getInputLines(2020, 24)
  5. val directions = listOf("e", "se", "sw", "w", "nw", "ne")
  6. fun parse(s:String): MutableList<String> {
  7. val out = mutableListOf<String>()
  8. var i = 0
  9. while(i<s.length) {
  10. val n = if (s[i] in listOf('e', 'w')) 1 else 2
  11. out.add(s.substring(i, i + n))
  12. i+=n
  13. }
  14. return out
  15. }
  16.  
  17. fun move(p:Pos, dir:String) =
  18. when(dir) {
  19. "e" -> { Pos(p.x + 1, p.y) }
  20. "w" -> { Pos(p.x - 1, p.y)}
  21. "se" -> { Pos(p.x + 1, p.y - 1) }
  22. "sw" -> { Pos(p.x, p.y - 1) }
  23. "ne" -> { Pos(p.x, p.y + 1) }
  24. "nw" -> { Pos(p.x - 1, p.y + 1) }
  25. else -> throw RuntimeException("Unknown direction $dir")
  26. }
  27.  
  28. var blacks = input.map { parse(it).fold(Pos(0, 0)) { p, d -> move(p, d)}}
  29. .groupBy { it }.map { it.key to it.value.size }
  30. .filterNot { it.second % 2 == 0 }.map { it.first }
  31. println(blacks.size)
  32. for(i in 1..100) {
  33. // number of black tiles around
  34. val ba = blacks.flatMap { b -> directions.map {move(b, it) } }
  35. .groupBy { it }.map { it.key to it.value.size }.toMap()
  36. // black tiles turning white
  37. val b2w = blacks.filter { ba[it] == null || ba[it]!!>2 }
  38. // white tiles turning black
  39. val w2b = ba.toList().filter { it.second == 2 }.map { it.first }.toSet().minus(blacks)
  40. // update black tiles
  41. blacks = blacks.minus(b2w).plus(w2b)
  42. }
  43. println(blacks.size)
  44. }
Advertisement
Add Comment
Please, Sign In to add comment