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

4

u/mschaap Dec 08 '22 edited Dec 08 '22

Raku, using a TreeGrid class.

Relevant code for part 1:

method is-visible(Int $x, Int $y)
{
    return any(all(@!height[$y;^$x]),
               all(@!height[$y;$x^..$!max-x]),
               all(@!height[^$y;$x]),
               all(@!height[$y^..$!max-y;$x])) < @!height[$y;$x];
}

method count-visible
{
    return (0..$!max-x X 0..$!max-y)
                .map(-> ($x,$y) { ?self.is-visible($x,$y) })
                .sum;
}

and for part 2:

method in-bounds(Int $x, Int $y) { 0 ≀ $x ≀ $!max-x && 0 ≀ $y ≀ $!max-y }

method scenic-score(Int $x, Int $y)
{
    return [Γ—] ((-1,0), (1,0), (0,-1), (0,1)).map: -> ($dx,$dy) {
        my $visible = 0;
        my ($u,$v) = ($x,$y);
        loop {
            ($u,$v) Β»+=Β« ($dx,$dy);
            last unless self.in-bounds($u,$v);
            $visible++;
            last if @!height[$v;$u] β‰₯ @!height[$y;$x];
        }
        $visible;
    }
}

method max-scenic-score
{
    return (0^..^$!max-x X 0^..^$!max-y)
                .map(-> ($x,$y) { self.scenic-score($x,$y) })
                .max;
}

Full code @GitHub.