Powered by AppSignal & Oban Pro

Day8

advent_of_code/2022/day-08.livemd

Day8

Day 8: Treetop Tree House

Day 8: Treetop Tree House

Input

input = """
30373
25512
65332
33549
35390
"""
input_with_index =
  input
  |> String.split("\n", trim: true)
  |> Enum.map(&String.to_charlist/1)
row_size = Enum.count(input_with_index)
[head | _] = input_with_index
column_size = Enum.count(head)
map =
  for i <- 0..(row_size - 1), j <- 0..(column_size - 1), into: %{} do
    height = input_with_index |> Enum.at(i) |> Enum.at(j)
    {{i, j}, height}
  end
f_horizontal = fn row, start, ending, height ->
  start..ending
  |> Enum.map(fn index ->
    Map.get(map, {row, index}, 0)
  end)
  |> Enum.all?(&(height > &1))
end
f_vertical = fn column, start, ending, height ->
  start..ending
  |> Enum.map(fn index ->
    Map.get(map, {index, column}, 0)
  end)
  |> Enum.all?(&(height > &1))
end
for i <- 0..(row_size - 1),
    j <- 0..(column_size - 1),
    height = Map.fetch!(map, {i, j}),
    f_horizontal.(i, j + 1, column_size, height) or
      f_horizontal.(i, j - 1, -1, height) or
      f_vertical.(j, i - 1, -1, height) or
      f_vertical.(j, i + 1, row_size, height) do
  {i, j}
end
|> IO.inspect()
|> Enum.count()

Part 2

value = fn
  -1, _height, distance -> {:halt, distance}
  height, height, distance -> {:halt, distance + 1}
  other_height, height, distance when other_height > height -> {:halt, distance + 1}
  other_height, height, distance when other_height < height -> {:cont, distance + 1}
end
f_horizontal_distance = fn row, start, ending, height ->
  start..ending
  |> Enum.reduce_while(0, fn index, acc ->
    Map.get(map, {row, index}, -1)
    |> value.(height, acc)
  end)
end
f_vertical_distance = fn column, start, ending, height ->
  start..ending
  |> Enum.reduce_while(0, fn index, acc ->
    Map.get(map, {index, column}, -1)
    |> value.(height, acc)
  end)
end
for i <- 0..(row_size - 1),
    j <- 0..(column_size - 1),
    height = Map.fetch!(map, {i, j}),
    r = f_horizontal_distance.(i, j + 1, column_size, height),
    l = f_horizontal_distance.(i, j - 1, -1, height),
    t = f_vertical_distance.(j, i - 1, -1, height),
    d = f_vertical_distance.(j, i + 1, row_size, height) do
  r * l * t * d
end
|> IO.inspect()
|> Enum.max()