Powered by AppSignal & Oban Pro

Advent of Code - Day 4: Giant Squid

lib/advent_of_code/2021/day-04.livemd

Advent of Code - Day 4: Giant Squid

Mix.install([:kino])

Day 4: Giant Squid

Part One: Prompt

You're already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can't see any sunlight. What you can see, however, is a giant squid that has attached itself to the outside of your submarine.

Maybe it wants to play bingo?

Bingo is played on a set of boards each consisting of a 5x5 grid of numbers. Numbers are chosen at random, and the chosen number is marked on all boards on which it appears. (Numbers may not appear on all boards.) If all numbers in any row or any column of a board are marked, that board wins. (Diagonals don't count.)

The submarine has a bingo subsystem to help passengers (currently, you and the giant squid) pass the time. It automatically generates a random order in which to draw numbers and a random set of boards (your puzzle input). For example:

7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1

22 13 17 11  0
 8  2 23  4 24
21  9 14 16  7
 6 10  3 18  5
 1 12 20 15 19

 3 15  0  2 22
 9 18 13 17  5
19  8  7 25 23
20 11 10 24  4
14 21 16 12  6

14 21 17 24  4
10 16 15  9 19
18  8 23 26 20
22 11 13  6  5
 2  0 12  3  7

After the first five numbers are drawn (7, 4, 9, 5, and 11), there are no winners, but the boards are marked as follows (shown here adjacent to each other to save space):

22  13  17 *11*   0           3   15    0   2  22         14  21  17  24   *4*
 8   2  23  *4*  24          *9*  18   13  17  *5*        10  16  15  *9*  19
21  *9* 14  16   *7*         19    8   *7* 25  23         18   8  23  26   20
 6  10   3  18   *5*         20  *11*  10  24  *4*        22 *11* 13   6   *5*
 1  12  20  15   19          14   21   16  12   6          2   0  12   3   *7*

After the next six numbers are drawn (17, 23, 2, 0, 14, and 21), there are still no winners.

Finally, 24 is drawn. At this point, the third board wins because it has at least one complete row or column of marked numbers (in this case, the entire top row is marked: 14 21 17 24 4).

The score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512.

To guarantee victory against the giant squid, figure out which board will win first.

What will your final score be if you choose that board?

To begin, get your puzzle input.

Part One: Solution

input = Kino.Input.textarea("Please paste your input file:")
defmodule Bingo do
  def prepare_board(rows) do
    __MODULE__.Board.init(rows)
  end

  def normalize_draw_list(draw_list) when is_binary(draw_list) do
    draw_list
    |> String.split(",")
    |> Enum.map(&String.to_integer/1)
  end

  def normalize_draw_list(draw_list) when is_list(draw_list) do
    draw_list
  end

  def normalize_draw_list(_), do: :error

  def play_until_winner(boards, draw_list) do
    draw_list
    |> normalize_draw_list()
    |> Enum.reduce_while(boards, fn draw_number, acc ->
      boards = Bingo.play_number(acc, draw_number)
      winner = Enum.find(boards, & &1.winner)

      if winner, do: {:halt, {draw_number, winner}}, else: {:cont, boards}
    end)
  end

  def find_loser(boards, draw_list) do
    draw_list
    |> normalize_draw_list()
    |> Enum.reduce_while(boards, fn draw_number, acc ->
      boards = Bingo.play_number(acc, draw_number)

      case Enum.count(boards, &(!&1.winner)) do
        1 -> {:halt, Enum.find(boards, &(!&1.winner))}
        _ -> {:cont, boards}
      end
    end)
  end

  def play_number(boards, number) when is_list(boards) do
    boards
    |> Enum.map(fn board ->
      play_number(board, number)
    end)
  end

  def play_number(%__MODULE__.Board{} = board, number) do
    board
    |> __MODULE__.Board.play_number(number)
    |> __MODULE__.Board.check_winner()
  end

  defmodule Board do
    defstruct [:board, rows: [], columns: [], winner: false]

    def init(row_input) do
      rows = prepare_rows(row_input)

      %__MODULE__{
        board: row_input,
        rows: rows,
        columns: prepare_columns(rows)
      }
    end

    def score(%__MODULE__{rows: rows}) do
      rows
      |> List.flatten()
      |> Enum.filter(fn x -> x != :x end)
      |> Enum.sum()
    end

    def score({winning_number, %__MODULE__{} = board}) when is_integer(winning_number) do
      score(board) * winning_number
    end

    def play_number(%__MODULE__{} = board, number) do
      board
      |> Map.update!(:rows, &play_number(&1, number))
      |> Map.update!(:columns, &play_number(&1, number))
    end

    def play_number(rows_or_columns, number) when is_list(rows_or_columns) do
      rows_or_columns
      |> Enum.map(
        &Enum.map(&1, fn
          ^number -> :x
          x -> x
        end)
      )
    end

    def check_winner(%__MODULE__{} = board) do
      Map.put(board, :winner, do_check_winner(board))
    end

    defp do_check_winner(board) do
      ~w(rows columns)a
      |> Enum.any?(fn s ->
        board |> Map.get(s) |> winning_set?()
      end)
    end

    defp winning_set?(list) do
      Enum.any?(list, &all_negative?/1)
    end

    defp all_negative?(list), do: Enum.all?(list, &marked_cell?/1)

    defp marked_cell?(:x), do: true
    defp marked_cell?(_), do: false

    defp prepare_rows(rows) do
      rows
      |> Enum.reduce([], &prepare_row/2)
      |> Enum.reverse()
    end

    defp prepare_row(row, board) do
      [String.split(row) |> Enum.map(&String.to_integer/1) | board]
    end

    defp prepare_columns([row | _] = rows) do
      for x <- 0..(length(row) - 1), into: [] do
        Enum.map(rows, &Enum.at(&1, x))
      end
    end
  end
end
{:module, Bingo, <<70, 79, 82, 49, 0, 0, 18, ...>>,
 {:module, Bingo.Board, <<70, 79, 82, ...>>, {:prepare_columns, 1}}}
[draw_list | board_lines] =
  input
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
["0,56,39,4,52,7,73,57,65,13,3,72,69,96,18,9,49,83,24,31,12,64,29,21,80,71,66,95,2,62,68,46,11,33,74,88,17,15,5,6,98,30,51,78,76,75,28,53,87,48,20,22,55,86,82,90,47,19,25,1,27,60,94,38,97,58,70,10,43,40,89,26,34,32,23,45,50,91,61,44,35,85,63,16,99,92,8,36,81,84,79,37,93,67,59,54,41,77,42,14",
 "63  5 10 69 57", "64 88 27 40 76", "59 20 58 90  6", "74 32 72 16 26", "50 17  7 93 94",
 "92 77 33 44 14", "35 25 47 91  7", "99  6 56 82 10", "41 93 70  5 85", "81 97 58 96 29",
 "24 53  4  8 23", " 0 13 48 47 83", "55 56 72 50 52", "82 33 58 16 11", "91  7 89  9 81",
 "86 70 16  4 34", "49 69 37 78 11", "22 47 59 20 38", "33 82 60 63 56", "18 74 36  7 99",
 "64 45 72 86  7", "34 50 94  0 85", "15 69  2 26 32", "62 96 41 17 78", "63  5 99 79 47",
 "62 63 24 37 50", "89 80 40 41 13", "32 64 95 93 66", "45  3 23 78 48", "60 26 31 61 99",
 " 6 63 66 67 15", "33 43 62 95 89", "72 61 60  2 10", "29  7  9 50 18", "28 36  3 53 30",
 "91  4 57 74 66", "49 36 54  7 89", "33 65 59 14 92", "63 42  0 20 11", "64 32 96 18 58",
 "85 59 33 18 99", "90  4  1 51 35", " 2 57  9  5 78", "30 53 25 23 80", "74 76 20 19 21",
 " 5 42 50 72 90", "58 63 49 17 31", "39 76  8 19 41", " 9 59 61 23 54", ...]
board_list =
  board_lines
  |> Enum.chunk_every(5)
  |> Enum.map(&Bingo.prepare_board/1)
winner = Bingo.play_until_winner(board_list, draw_list)
Bingo.Board.score(winner)

Your puzzle answer was 45031.

The first half of this puzzle is complete! It provides one gold star: *

Part Two: Prompt

On the other hand, it might be wise to try a different strategy: let the giant squid win.

You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time counting its arms, the safe thing to do is to figure out which board will win last and choose that one. That way, no matter which boards it picks, it will win for sure.

In the above example, the second board is the last to win, which happens after 13 is eventually called and its middle column is completely marked. If you were to keep playing until this point, the second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 = 1924.

Figure out which board will win last.

Once it wins, what would its final score be?

loser = Bingo.find_loser(board_list, draw_list)
%Bingo.Board{
  board: ["67 51 43 89 94", " 4 96 50  9  8", "22 87 77 38 35", "39 37 17 59 32", " 5 25 26 83 81"],
  rows: [
    [67, :x, :x, :x, :x],
    [:x, :x, :x, :x, 8],
    [:x, :x, 77, :x, :x],
    [:x, 37, :x, 59, :x],
    [:x, :x, :x, :x, 81]
  ],
  columns: [
    [67, :x, :x, :x, :x],
    [:x, :x, :x, 37, :x],
    [:x, :x, 77, :x, :x],
    [:x, :x, :x, 59, :x],
    [:x, 8, :x, :x, 81]
  ],
  winner: false
}
winner = Bingo.play_until_winner([loser], draw_list)
{8,
 %Bingo.Board{
   board: ["67 51 43 89 94", " 4 96 50  9  8", "22 87 77 38 35", "39 37 17 59 32", " 5 25 26 83 81"],
   rows: [
     [67, :x, :x, :x, :x],
     [:x, :x, :x, :x, :x],
     [:x, :x, 77, :x, :x],
     [:x, 37, :x, 59, :x],
     [:x, :x, :x, :x, 81]
   ],
   columns: [
     [67, :x, :x, :x, :x],
     [:x, :x, :x, 37, :x],
     [:x, :x, 77, :x, :x],
     [:x, :x, :x, 59, :x],
     [:x, :x, :x, :x, 81]
   ],
   winner: true
 }}
Bingo.Board.score(winner)
2568

Your puzzle answer was 2568.

Both parts of this puzzle are complete! They provide two gold stars: **

At this point, you should return to your Advent calendar and try another puzzle.

If you still want to see it, you can get your puzzle input.