r/adventofcode • • Dec 08 '22

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

NEWS AND FYI

  • I discovered that I can make those tiny post/comment awards BIGGER on old.reddit! I hadn't even considered that! And when you hover over them, they get even bigger so you can actually see them in more detail! I've added the relevant CSS so now we no longer have awards for ants! Exclamation points!!!

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

  • PSA: I created a new example so it is a more relevant and unique archetype instead of recycling last year's hobbit >_>

--- Day 8: Treetop Tree House ---


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:10:12, megathread unlocked!

75 Upvotes

1.0k comments sorted by

View all comments

3

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

Had a go at a couple of solutions in Scala. First one I was determined not to use a multi-dimensional vector, but no idea why. Both work pretty similarly other than the way to determine neighbours...

V1 - (Single dimensional Vector) https://github.com/anatomic/advent-of-code/blob/main/src/main/scala/year2022/Day08.scala

V2 - (Multi-dimensional Vector) https://github.com/anatomic/advent-of-code/blob/main/src/main/scala/year2022/Day08_2.scala

I think I prefer this version:

import scala.io.Source

object Day08_2 {
  // Initially had some bizarre desire to not use a multi-dimensional grid.
  val grid =
    Source
      .fromResource("2022/day08.txt")
      .getLines()
      .map(_.map(_.asDigit).toVector)
      .toVector

  def main(args: Array[String]): Unit = {
    println(part1())
    println(part2())
  }

  def part1() =
    grid.zipWithIndex
      .map((r, y) =>
        r.zipWithIndex.count((tree, x) =>
          neighbours(x, y).exists(_.forall(_ < tree))
        )
      )
      .sum

  def part2() =
    grid.zipWithIndex
      .flatMap((r, y) =>
        r.zipWithIndex
          .map((tree, x) =>
            neighbours(x, y)
              .map(trees =>
                Math.min(trees.segmentLength(_ < tree) + 1, trees.size)
              )
              .product
          )
      )
      .max

  private def neighbours(x: Int, y: Int) =
    Vector(
      grid.take(y).map(_(x)).reverse,
      grid.drop(y + 1).map(_(x)),
      grid(y).take(x).reverse,
      grid(y).drop(x + 1)
    )
}

1

u/maneatingape Dec 08 '22

TIL: segmentLength. Nice approach!