r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

1

u/shapshankly Dec 07 '22 edited Dec 08 '22

Here's another effort in Scala - tricky one today!

package year2022

import scala.collection.mutable
import scala.io.Source
import scala.util.Using
import scala.util.matching.Regex

object Day07 {
  def main(args: Array[String]): Unit = {
    val dirs = parseInput("2022/day07.txt")    

    val part1 = dirs.values.filter(_ < 100000).sum
    println(part1)

    val part2 = dirs.values.toList.sorted
      .find(_ > 30000000 - (70000000 - dirs.values.max))
    part2.foreach(println)
  }

  val file: Regex = "(\\d+) (.+)".r

  private def parseInput(fileName: String) =
    Using(Source.fromResource(fileName)) { input =>
      input
        .getLines()
        .foldLeft(
          ("", mutable.Map[String, Long]())
        ) {
          case ((cwd, files), s"$$ cd $dir") => (nextPath(cwd, dir), files)
          case ((cwd, files), file(size, _)) =>
            cwd
              .split("/")
              .foldLeft(List("")) { (k, part) =>
                s"${k.head}/$part" :: k
              }
              .foreach(p => files(p) = size.toLong + files.getOrElse(p, 0L))
            (cwd, files)
          case (agg, _) => agg
        }
    }.get._2

  private def nextPath(cwd: String, p: String) = p match
    case ".." => cwd.split("/").init.mkString("/")
    case "/" => "/"
    case _ => cwd + "/" + p
}

1

u/daggerdragon Dec 08 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.