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

Advent 2022 - Day 2

day2.livemd

Advent 2022 - Day 2

Mix.install([
  {:kino, github: "livebook-dev/kino"}
])
:ok

Setup

input = Kino.Input.textarea("Please paste your input file:")
input =
  input
  |> Kino.Input.read()
  |> String.trim()
  |> String.split("\n")
  |> Enum.map(&String.split(&1, " "))
[["A", "Y"], ["B", "X"], ["C", "Z"]]
defmodule RockPaperScissors do
  def score(them, you) do
    choice_score =
      case you do
        :rock -> 1
        :paper -> 2
        :scissors -> 3
      end

    game_score =
      case {you, them} do
        {you, you} -> 3
        {:rock, :paper} -> 0
        {:rock, :scissors} -> 6
        {:paper, :scissors} -> 0
        {:paper, :rock} -> 6
        {:scissors, :rock} -> 0
        {:scissors, :paper} -> 6
      end

    choice_score + game_score
  end

  def pick_then_score(them, wanted_result) do
    case {them, wanted_result} do
      {x, :draw} -> score(them, x)
      {:rock, :win} -> score(them, :paper)
      {:rock, :throw} -> score(them, :scissors)
      {:paper, :win} -> score(them, :scissors)
      {:paper, :throw} -> score(them, :rock)
      {:scissors, :win} -> score(them, :rock)
      {:scissors, :throw} -> score(them, :paper)
    end
  end
end
{:module, RockPaperScissors, <<70, 79, 82, 49, 0, 0, 9, ...>>, {:pick_then_score, 2}}

Part 1

assumed_guide = %{
  "A" => :rock,
  "B" => :paper,
  "C" => :scissors,
  "X" => :rock,
  "Y" => :paper,
  "Z" => :scissors
}
%{"A" => :rock, "B" => :paper, "C" => :scissors, "X" => :rock, "Y" => :paper, "Z" => :scissors}
input
|> Enum.map(fn [them, you] ->
  RockPaperScissors.score(assumed_guide[them], assumed_guide[you])
end)
|> Enum.sum()
15

Part 2

actual_guide = %{
  "A" => :rock,
  "B" => :paper,
  "C" => :scissors,
  "X" => :throw,
  "Y" => :draw,
  "Z" => :win
}
%{"A" => :rock, "B" => :paper, "C" => :scissors, "X" => :throw, "Y" => :draw, "Z" => :win}
input
|> Enum.map(fn [them, you] ->
  RockPaperScissors.pick_then_score(actual_guide[them], actual_guide[you])
end)
|> Enum.sum()
12