-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17.scala
84 lines (71 loc) · 2.69 KB
/
17.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import scala.sys.process._
def clear() = "clear".!
type Coord = (Int, Int)
sealed trait Square
case object Sand extends Square {
override def toString: String = "."
}
case object Clay extends Square {
override def toString: String = "#"
}
sealed trait Water extends Square
case object Settled extends Water {
override def toString: String = "~"
}
case object Flowing extends Water {
override def toString: String = "|"
}
case object Settling extends Water {
override def toString: String = "/"
}
sealed trait Direction
case object Down extends Direction
case object Left extends Direction
case object Right extends Direction
type Grid = Vector[Vector[Square]]
val pattern = "([xy])=(\\d+), ([xy])=(\\d+)..(\\d+)".r
val map = io.Source.stdin.getLines
.flatMap { case pattern(first, value, _, rangeStart, rangeEnd) =>
(rangeStart.toInt to rangeEnd.toInt).map(c => if (first == "x") (value.toInt, c) else (c, value.toInt))
}
.map(_ -> Clay)
.toMap
.withDefaultValue(Sand)
val minY = map.minBy(_._1._2)._1._2
val maxY = map.maxBy(_._1._2)._1._2
def settle(squares: Map[Coord, Square], current: Coord): Map[Coord, Square] = {
squares(current) match {
case Settling => settle(settle(squares + (current -> Settled), current.copy(_1 = current._1 - 1)), current.copy(_1 = current._1 + 1))
case _ => squares
}
}
def flood(squares: Map[Coord, Square], current: Coord, prev: Coord): Map[Coord, Square] = {
if (current._2 > maxY) {
squares
} else {
squares(current) match {
case Clay | _: Water => squares
case Sand =>
val below = current.copy(_2 = current._2 + 1)
val downStream = flood(squares + (current -> Flowing), below, current)
downStream(below) match {
case Flowing | Settling | Sand => downStream
case Clay | Settled =>
val left = current.copy(_1 = current._1 - 1)
val right = current.copy(_1 = current._1 + 1)
val leftStream = flood(downStream, left, current)
val rightStream = flood(leftStream, right, current)
(rightStream(left), rightStream(right)) match {
case (Clay | Settled | Settling, _) | (_, Clay | Settled | Settling) if prev == left || prev == right =>
rightStream + (current -> Settling)
case (Clay | Settled | Settling, Clay | Settled | Settling) =>
settle(settle(rightStream, left), right) + (current -> Settled)
case _ => rightStream
}
}
}
}
}
val flooded = flood(map, (500, 0), (500, -1))
println(flooded.count { case (c, square) => c._2 >= minY && square.isInstanceOf[Water] })
println(flooded.count { case (c, square) => c._2 >= minY && square == Settled })