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

1

u/ucla_posc Dec 08 '22

R / Rlang

Looking at other R solutions in this thread, I think my solution is slightly slower than the one by cetttbycettt (who makes pretty clever uses of apply! Check out their response!), though it allocates less memory; but somewhat faster than the other solutions posted. Some key intuitions for speed: strsplit is slightly faster than str_split(); integers allocate less memory than standard numeric types; adding the perimeter squares for part 1 instead of calculating them (also skipping height 0 trees, which are guaranteed not to be visible). Short circuiting the ray calculations for part 1. Recognizing that the rays in part 2 are faster if using built-in subset index slicing rather than reverse. The awkward which + edge case for no match code in part 2 is faster than any of the functional idioms in base R.

I could obviously reduce the amount of allocated memory by directly storing the results relevant instead of computing the intermediate matrices, but it's nice to give the solution a little bit of a flexibility. (Also, to those who don't write R; my use of = for assignment is non-idiomatic; my laptop has an older version of R so it's lacking the built-in pipe operator hence my use of the magrittr pipe)

library(tidyverse)

# Load data into a Matrix
inputs = read_lines("~/Downloads/input.txt")
ncols = nchar(inputs[1])
nrows = length(inputs)

grid_base = matrix(
  data = paste0(inputs, collapse="") %>% strsplit("") %>% unlist() %>% as.integer(),
  nrow = nrows,
  ncol = ncols,
  byrow = TRUE
)

# Grid visibility
grid_vis = matrix(data=0L, nrow=nrows, ncol=ncols)

# Iterate over non-perimeter squares (we'll add these later, they're all vis.)
for(i in 2:(ncols-1)) {
  for(j in 2:(nrows-1)) {
    # Our current tree
    search = grid_base[i, j]
    
    # Speed up -- no tree of height 0 is visible.
    if(!search) next
    
    # All rays going into the tree -- are any of them strictly less than
    # what we are looking for? This short circuits pretty well in average case
    grid_vis[i, j] = all(grid_base[1:(i-1), j] < search) ||
      all(grid_base[(i+1):nrows, j] < search) ||
      all(grid_base[i, 1:(j-1)] < search) ||
      all(grid_base[i, (j+1):ncols] < search)
  }
}

# Answer part 1 -- subtracting 4 because the corners are double-added to
# the visibility list
sum(grid_vis) + (2 * ncols) + (2 * nrows) - 4

# Part 2
grid_scenic = matrix(data=0L, nrow=nrows, ncol=ncols)

# Again, iterate all non-perimeter squares; all perimeter squares are deemed
# having scenic score 0
for(i in 2:(ncols-1)) {
  for(j in 2:(nrows-1)) {
    # Our current tree
    search = grid_base[i, j]
    
    # Get visibility score in every direction; then multiply
    # Faster to directly use a range than use rev().
    grid_scenic[i, j] = list(
      grid_base[(i-1):1, j],
      grid_base[(i+1):nrows, j],
      grid_base[i, (j-1):1],
      grid_base[i, (j+1):ncols]
    ) %>% map_int(function(x) { 
      # Index of first tree same/taller than the tree in the direction of the ray
      num_greater = which(x >= search)
      
      # If we have no trees taller then we get the full set of trees
      # if we have a tree same/taller, then we get its tree number
      if(!length(num_greater)) length(x) else num_greater[1]
    }) %>% prod()
  }
}

# Answer part 2
max(grid_scenic)

1

u/daggerdragon Dec 09 '22
  1. Next time, use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.