1. import scala.collection.mutable.{Map => MMap}
  2. import scala.collection.mutable.{Set => MSet}
  3. object Wrapper {
  4. // 0 1 2 3 4 5 6 7
  5. // 0 1 2 3 4 5 6 7
  6. // 0 1 2 3 4 5 6 7
  7. // 0 1 2 3 4 5 6 7
  8. val dy = Array( 0, 0, -1, -1, 1, 1)
  9. val dx = Array( 1, -1, 1, 0, 1, 0)
  10. // Took ages to realize that dx depends on the Y
  11. val dxx = Array( 1, -1, 0, -1, 0, -1)
  12. val mv = Array( "e", "w","ne","nw","se","sw")
  13. val lines = scala.io.Source.fromFile("input").getLines.toArray
  14. def part1(lines: Array[String]) = {
  15. val tiles = MMap[(Int, Int), Int]()
  16. lines.foreach { line =>
  17. var moves = line
  18. var x = 0
  19. var y = 0
  20. while(!moves.isEmpty){
  21. for(m <- 0 until 6){
  22. if(moves.startsWith(mv(m))){
  23. if(y%2 == 0)
  24. x += dx(m)
  25. else
  26. x += dxx(m)
  27. y += dy(m)
  28. moves = moves.substring(mv(m).length)
  29. }
  30. }
  31. }
  32. if(tiles.contains(x->y)){
  33. tiles(x->y) = 1 - tiles(x->y)
  34. } else {
  35. tiles(x->y) = 1
  36. }
  37. }
  38. println(tiles.values.sum)
  39. tiles
  40. }
  41. def neighbours(x: Int, y:Int) = {
  42. (0 until 6) map { m =>
  43. val xx = x + (if(y%2 == 0) dx(m) else dxx(m))
  44. val yy = y + dy(m)
  45. (xx, yy)
  46. }
  47. }
  48. def part2(tiles: MSet[(Int, Int)]){
  49. var cur = tiles.clone
  50. var next = MSet[(Int, Int)]()
  51. for(turn <- 1 to 100){
  52. val whites = MSet[(Int, Int)]()
  53. next = MSet[(Int, Int)]()
  54. cur.foreach { case (x, y) =>
  55. val nb = neighbours(x,y).toSet
  56. val blacks = nb.filter(cur)
  57. if(!(blacks.size == 0 || blacks.size > 2))
  58. next += x -> y
  59. whites ++= nb
  60. }
  61. whites --= cur
  62. whites.foreach { case (x, y) =>
  63. val nb = neighbours(x,y)
  64. val blacks = nb.filter(cur)
  65. if( blacks.size == 2)
  66. next += x -> y
  67. }
  68. cur = next.clone
  69. }
  70. println(cur.size)
  71. }
  72. def solve() = {
  73. val tiles = part1(lines).filter(_._2 == 1)
  74. val blacks = MSet[(Int, Int)]()
  75. blacks ++= tiles.keySet
  76. part2(blacks)
  77. }
  78. }
  79. Wrapper.solve()