Skip to content

Commit 93201c9

Browse files
author
Kalle Wuoti
committed
Use regex to parse commands
1 parent 56112a2 commit 93201c9

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

day6/prog.scala

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,20 @@ def setBrightness(ls: Seq[collection.mutable.Seq[Int]], x1: Int, y1: Int, x2: In
1818
y <- y1 to y2
1919
} ls(x)(y) = if (cmd == toggleCmd) ls(x)(y) + 2 else if (cmd == turnOnCmd) ls(x)(y) + 1 else Math.max(0, ls(x)(y) - 1)
2020

21-
cmds.foreach {c =>
22-
val cmd = c.takeWhile(!_.isDigit).dropRight(1)
23-
val (x1, y1, x2, y2) = c.stripPrefix(cmd + " ").split(' ') match {
24-
case Array(coord1, _, coord2) => {
25-
val p = (s: String) => s.split(',') match { case Array(x, y) => (x.toInt, y.toInt) }
26-
val (x1, y1) = p(coord1)
27-
val (x2, y2) = p(coord2)
28-
(x1, y1, x2, y2)
29-
}
21+
val turnOnR = """turn on (\d+),(\d+) through (\d+),(\d+)""".r
22+
val turnOffR = """turn off (\d+),(\d+) through (\d+),(\d+)""".r
23+
val toggleR = """toggle (\d+),(\d+) through (\d+),(\d+)""".r
24+
25+
cmds.foreach { c =>
26+
val (cmd, x1, y1, x2, y2) = c match {
27+
case turnOnR(x1, y1, x2, y2) => (turnOnCmd, x1.toInt, y1.toInt, x2.toInt, y2.toInt)
28+
case turnOffR(x1, y1, x2, y2) => (turnOffCmd, x1.toInt, y1.toInt, x2.toInt, y2.toInt)
29+
case toggleR(x1, y1, x2, y2) => (toggleCmd, x1.toInt, y1.toInt, x2.toInt, y2.toInt)
3030
}
3131

3232
switchLights(lights, x1, y1, x2, y2, cmd)
3333
setBrightness(lights2, x1, y1, x2, y2, cmd)
3434
}
3535

36-
println(s"Number of lights turned on: ${lights.flatten.count(_ == true)}")
36+
println(s"Number of lights turned on: ${lights.flatten.count(b => b)}")
3737
println(s"Total brightness of all lights combined: ${lights2.flatten.sum}")

0 commit comments

Comments
 (0)