Day 3: Foggy Forest

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • VegOwOtenks
    link
    fedilink
    arrow-up
    4
    ·
    1 day ago

    Futhark

    Very brute force, this is optimizable by checking in a triangle pattern rather than everywhere and aborting afterwards.

    def tabulate2d n m f = tabulate n (\ i -> tabulate m (\ j -> f i j))
    def sum2d xss = i64.sum (map i64.sum xss)
    def map2d f = map (map f)
    
    def findSquare [n][m] (trees: [n][m]bool) row col: i64
      = let maxSz = i64.min (n - row) (m - col)
        let isSquare sz = sz != 0 && trees[row][col] && trees[row+sz][col] && trees[row][col+sz] && trees[row+sz][col+sz]
        in tabulate maxSz isSquare |> map i64.bool |> i64.sum
    
    def findRotSquare [n][m] (trees: [n][m]bool) row col: i64
      = let maxSz = i64.min n m 
        let isTree i j = i >= 0 && j >= 0 && i < n && j < m && trees[i][j]
        let isRotSquare sz rot = true
              && sz != 0
              && sz > rot
              && isTree row col -- top-left
              && isTree (row+rot) (col-rot+sz) -- top-right
              && isTree (row+sz) (col-rot+sz-rot) -- bot-right
              && isTree (row+sz-rot) (col-rot)
        in tabulate2d maxSz maxSz isRotSquare |> map2d i64.bool |> sum2d
    
    def main [n][m] (trees: [n][m]bool): (i64, i64)
      = let part1 = tabulate2d n m (findSquare trees) |> sum2d
        let part2 = tabulate2d n m (findRotSquare trees) |> sum2d
        in (part1, part2)
    

    To run it, first format the input using sed:

    Sed Formatting
    1i[
    s/^/[/
    s/#/true, /g
    s/\./false, /g
    s/$/], /
    $a]