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

Rock Paper Scissors

livebook/day02.livemd

Rock Paper Scissors

Mix.install([{:kino, "~> 0.7.0"}])

Input

input = Kino.Input.textarea("Input:")
input = Kino.Input.read(input)

Part 1

rounds =
  input
  |> String.trim()
  |> String.split("\n")
  |> Enum.map(
    &(String.split(&1, " ")
      |> Enum.map(fn
        "A" -> :rock
        "B" -> :paper
        "C" -> :scissors
        "X" -> :rock
        "Y" -> :paper
        "Z" -> :scissors
      end))
  )

score_for_shape = fn
  :rock -> 1
  :paper -> 2
  :scissors -> 3
end

who_won = fn
  :rock, :paper -> :me
  :paper, :rock -> :them
  :scissors, :paper -> :them
  :paper, :scissors -> :me
  :rock, :scissors -> :them
  :scissors, :rock -> :me
  _, _ -> :draw
end

score_for_result = fn
  :them -> 0
  :draw -> 3
  :me -> 6
end

scores =
  Enum.map(rounds, fn [them, me] ->
    result = who_won.(them, me)
    score_for_shape.(me) + score_for_result.(result)
  end)

Enum.sum(scores)

Part 2

rounds =
  input
  |> String.trim()
  |> String.split("\n")
  |> Enum.map(
    &(String.split(&1, " ")
      |> Enum.map(fn
        "A" -> :rock
        "B" -> :paper
        "C" -> :scissors
        "X" -> :lose
        "Y" -> :draw
        "Z" -> :win
      end))
  )

ensure_outcome = fn
  shape, :draw -> shape
  :rock, :lose -> :scissors
  :rock, :win -> :paper
  :paper, :lose -> :rock
  :paper, :win -> :scissors
  :scissors, :lose -> :paper
  :scissors, :win -> :rock
end

rounds =
  rounds
  |> Enum.map(fn
    [shape, desired_outcome] -> [shape, ensure_outcome.(shape, desired_outcome)]
  end)

scores =
  Enum.map(rounds, fn [them, me] ->
    result = who_won.(them, me)
    score_for_shape.(me) + score_for_result.(result)
  end)

Enum.sum(scores)