Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 9

day9/index.livemd

Day 9

Setup

input =
  File.read!("aoc2021/day9/test_input.txt")
  |> String.split("\n", trim: true)
  |> Enum.map(&String.to_charlist/1)

grid =
  for {line, row} <- Enum.with_index(input),
      {val, col} <- Enum.with_index(line),
      into: %{} do
    {{row, col}, val - ?0}
  end
%{
  {4, 5} => 6,
  {1, 2} => 8,
  {0, 9} => 0,
  {3, 6} => 6,
  {2, 4} => 7,
  {4, 8} => 7,
  {0, 3} => 9,
  {1, 1} => 9,
  {4, 3} => 9,
  {3, 7} => 7,
  {0, 5} => 4,
  {0, 1} => 1,
  {4, 0} => 9,
  {3, 2} => 6,
  {0, 8} => 1,
  {3, 1} => 7,
  {2, 0} => 9,
  {2, 7} => 8,
  {4, 6} => 5,
  {0, 7} => 2,
  {0, 0} => 2,
  {2, 8} => 9,
  {1, 4} => 8,
  {0, 4} => 9,
  {1, 7} => 9,
  {4, 2} => 9,
  {2, 3} => 6,
  {1, 8} => 2,
  {3, 4} => 8,
  {2, 1} => 8,
  {4, 7} => 6,
  {3, 3} => 7,
  {3, 0} => 8,
  {4, 9} => 8,
  {1, 6} => 4,
  {4, 1} => 8,
  {1, 9} => 1,
  {3, 5} => 9,
  {1, 0} => 3,
  {2, 6} => 9,
  {1, 5} => 9,
  {2, 5} => 8,
  {2, 2} => 5,
  {0, 2} => 9,
  {4, 4} => 9,
  {0, 6} => 3,
  {3, 8} => 8,
  {1, 3} => 7,
  {3, ...} => 9,
  {...} => 2
}

Part 1

# Cheated from Jose Valim twitch feed. 
grid
|> Enum.filter(fn {{row, col}, value} ->
  up = grid[{row - 1, col}]
  down = grid[{row + 1, col}]
  left = grid[{row, col - 1}]
  right = grid[{row, col + 1}]
  value < up and value < down and value < left and value < right
end)
|> Enum.map(fn {_, value} -> value + 1 end)
|> Enum.sum()
[{{2, 2}, 5}, {{4, 6}, 5}, {{0, 1}, 1}, {{0, 9}, 0}]

Part 2

# Cheated from Jose Valim twitch feed.