Skip to content

Instantly share code, notes, and snippets.

@borkdude
Created December 6, 2015 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borkdude/62094893df250225c9bc to your computer and use it in GitHub Desktop.
Save borkdude/62094893df250225c9bc to your computer and use it in GitHub Desktop.
Advent of Code Day 6 part 1 in Scala
import scala.io.Source
object App {
case class CommandLine(command: String,
leftTop: (Int, Int),
rightBottom: (Int, Int))
case object CommandLine {
def fromString(s: String): CommandLine = {
val preProcessed = s.replace("turn off", "turn-off")
.replace("turn on", "turn-on")
.split(' ')
val command = preProcessed(0)
val leftTopString = preProcessed(1)
val rightBottomString = preProcessed(3)
def parseCoordinates(s: String): (Int, Int) = {
val pairsString = s.split(',')
(pairsString(0).toInt, pairsString(1).toInt)
}
CommandLine(command, parseCoordinates(leftTopString), parseCoordinates(rightBottomString))
}
}
class Grid(grid: Array[Array[Int]]) {
def updateGrid(c: CommandLine): Unit = {
val (x1, y1) = c.leftTop
val (x2, y2) = c.rightBottom
for (x <- x1 to x2) {
val row = grid(x)
for (y <- y1 to y2) {
c.command match {
case "turn-off" => grid(x)(y) = -1
case "turn-on" => grid(x)(y) = 1
case "toggle" => grid(x)(y) = grid(x)(y) * -1
}
}
}
}
def countLights: Int = {
grid.flatten.count((e) => e == 1)
}
}
def main(args: Array[String]) = {
val lines = Source.fromFile("input.txt").getLines()
val grid = new Grid(Array.tabulate(1000, 1000)((x, y) => -1))
for (line <- lines) {
val command = CommandLine.fromString(line)
grid.updateGrid(command)
}
println(grid.countLights)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment