Day 15
This commit is contained in:
parent
86c4da24ee
commit
c3ff1490a0
2 changed files with 47 additions and 0 deletions
1
input/day15
Normal file
1
input/day15
Normal file
File diff suppressed because one or more lines are too long
46
src/day15.scala
Normal file
46
src/day15.scala
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package aoc
|
||||
package day15
|
||||
|
||||
val dayNumber = "15"
|
||||
|
||||
@main def part1: Unit =
|
||||
println(part1(loadInput(dayNumber)))
|
||||
|
||||
@main def part2: Unit =
|
||||
println(part2(loadInput(dayNumber)))
|
||||
|
||||
def part1(input: String): String =
|
||||
input
|
||||
.split(',')
|
||||
.map(_.foldLeft(0)((acc, c) => ((acc + c) * 17) % 256))
|
||||
.sum
|
||||
.toString
|
||||
|
||||
def part2(input: String): String =
|
||||
val hash: String => Int = _.foldLeft(0)((acc, c) => ((acc + c) * 17) % 256)
|
||||
val steps = input
|
||||
.split(',')
|
||||
.map {
|
||||
case s"$label=$value" => (label, hash(label), Some(value.toInt))
|
||||
case s"$label-" => (label, hash(label), None)
|
||||
}
|
||||
val boxes = Map.empty[Int, List[(String, Int)]]
|
||||
steps
|
||||
.foldLeft(boxes) {
|
||||
case (boxes, (label, number, Some(value))) =>
|
||||
boxes.updatedWith(number) {
|
||||
case Some(lenses) =>
|
||||
val i = lenses.indexWhere(_._1 == label)
|
||||
if i >= 0 then Some(lenses.updated(i, (label, value)))
|
||||
else Some(lenses.appended((label, value)))
|
||||
case None => Some(List((label, value)))
|
||||
}
|
||||
case (boxes, (label, number, None)) =>
|
||||
boxes.updatedWith(number)(_.map(_.filterNot(_._1 == label)))
|
||||
|
||||
}
|
||||
.flatMap((boxNumber, lenses) =>
|
||||
lenses.zipWithIndex.map((s, i) => s._2 * (i + 1) * (boxNumber + 1))
|
||||
)
|
||||
.sum
|
||||
.toString
|
||||
Loading…
Add table
Add a link
Reference in a new issue