Skip to content

Commit

Permalink
Day 15 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
benoitpas committed Dec 15, 2023
1 parent 8d1f780 commit 2827dc7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,4 @@ Part 2: By changing the order the rounded rocks to also do a one pass processing

Part 1: Suprisingly simple !

Part 2: The main difficulty is understanding the instructions.
Part 2: The main difficulty is understanding the instructions and then find out how to model the data.
29 changes: 24 additions & 5 deletions src/main/scala/day15.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,38 @@ import zio.Console._

object Day15 extends ZIOAppDefault {

def hashCmd(cmd:String) : Int =
cmd.foldLeft(0)( (a,c) => {
val na = (a + c)*17 % 256
na
def hashCmd(cmd: String): Int =
cmd.foldLeft(0)((a, c) => {
val na = (a + c) * 17 % 256
na
})

def part1(cmds: List[String]) =
def part1(cmds: List[String]) =
cmds.flatMap(_.split(',')).map(hashCmd).sum

def part2(cmds: List[String]) =
val m = cmds.flatMap(_.split(',')).foldLeft(Map[Int, List[(String, Int)]]()) { (m, cmd) =>
(m, cmd.split('=').toList, cmd.split('-').toList) match
case (m, label :: fl :: _, _) =>
m.updatedWith(hashCmd(label)) {
case Some(l) if l.exists(_._1 == label) => Some(l.map(p => if p._1 == label then (label, fl.toInt) else p))
case Some(l) => Some(l.appended((label, fl.toInt)))
case None => Some(List((label, fl.toInt)))
}
case (m, _, label :: _) =>
m.updatedWith(hashCmd(label)) {
case Some(l) => Some(l.filter(_._1 != label))
case l => l
}
}
m.toList.flatMap { case (boxIndex, l) =>
(l zip (1 to l.length)).map(e => ((boxIndex + 1) * e._2 * e._1._2))
}.sum

def run =
for {
v <- Day1.readFile("day15_input.txt")
_ <- printLine(s"part1=${part1(v)}")
_ <- printLine(s"part2=${part2(v)}")
} yield ()
}
4 changes: 4 additions & 0 deletions src/test/scala/day15_test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ class Day15Test {
def testPart1() =
assertEquals(1320, Day15.part1(cmds))

@Test
def testPart2() =
assertEquals(145, Day15.part2(cmds))

}

0 comments on commit 2827dc7

Please sign in to comment.