Skip to content

Commit

Permalink
Solve 2023 day 15 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 15, 2023
1 parent b85772d commit 8868afb
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day15.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,54 @@ object Day15 {

def sumStepHashes(steps: Seq[String]): Int = steps.map(hash).sum

case class HashMap(boxes: Vector[Vector[(String, Int)]]) {
def +(keyValue: (String, Int)): HashMap = {
val (key -> value) = keyValue
val boxI = hash(key)
val box = boxes(boxI)
val keyI = box.indexWhere(_._1 == key)
val newBox =
if (keyI < 0)
box :+ keyValue
else
box.updated(keyI, keyValue)
HashMap(boxes.updated(boxI, newBox))
}

def -(key: String): HashMap = {
val boxI = hash(key)
HashMap(boxes.updated(boxI, boxes(boxI).filterNot(_._1 == key)))
}

def focusingPower: Int = {
(for {
(box, boxI) <- boxes.zipWithIndex
((_, focalLength), slotI) <- box.zipWithIndex
} yield (boxI + 1) * (slotI + 1) * focalLength).sum
}
}

object HashMap {
def empty: HashMap = HashMap(Vector.fill(256)(Vector.empty))
}

def installLenses(steps: Seq[String]): HashMap = {
steps.foldLeft(HashMap.empty)({
case (acc, s"$key=$value") => acc + (key -> value.toInt)
case (acc, s"$key-") => acc - key
case (_, _) => ???
})
}

def focusingPower(steps: Seq[String]): Int = installLenses(steps).focusingPower


def parseSteps(input: String): Seq[String] = input.split(',').toSeq

lazy val input: String = scala.io.Source.fromInputStream(getClass.getResourceAsStream("day15.txt")).mkString.trim

def main(args: Array[String]): Unit = {
println(sumStepHashes(parseSteps(input)))
println(focusingPower(parseSteps(input)))
}
}
8 changes: 8 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day15Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,12 @@ class Day15Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(sumStepHashes(parseSteps(input)) == 507666)
}

test("Part 2 examples") {
assert(focusingPower(parseSteps(exampleInput)) == 145)
}

test("Part 2 input answer") {
assert(focusingPower(parseSteps(input)) == 233537)
}
}

0 comments on commit 8868afb

Please sign in to comment.