This commit is contained in:
Paul-Henri Froidmont 2022-12-07 08:10:02 +01:00
parent 53d5b39e80
commit 46b37c5bc1
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 1122 additions and 0 deletions

35
aoc/src/Day7.scala Normal file
View file

@ -0,0 +1,35 @@
import scala.io.Source
import scala.collection.mutable
object Day7 extends App:
val input = Source
.fromURL(getClass.getResource("day7Input.txt"))
.mkString
.split('\n')
.toList
.map(_.split(" "))
val sizes = input
.foldLeft((List.empty[String], Map.empty[List[String], Long])) {
case ((path, sizes), Array("$", "cd", "/")) => (List("/"), sizes.updated(List("/"), 0L))
case ((path, sizes), Array("$", "cd", "..")) => (path.dropRight(1), sizes)
case ((path, sizes), Array("$", "cd", cdArg)) =>
val fullPath = path.appended(cdArg)
(fullPath, sizes.updated(fullPath, 0L))
case ((path, sizes), Array(size, _)) if size.head.isDigit =>
val filteredSizes = sizes
.filter(key => path.startsWith(key._1))
.map((parentPath, totalSize) => (parentPath, totalSize + size.toLong))
(path, sizes.concat(filteredSizes))
case ((path, sizes), _) => (path, sizes)
}._2.values.toList.sorted
val part1 = sizes.filter(_ <= 100000).sum
println(s"Part 1: $part1")
val totalUsed = sizes.last
val part2 = sizes.find(totalUsed - _ <= 40000000).get
println(s"Part 2: $part2")
end Day7