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

Day 2

02.livemd

Day 2

Preparation

Mix.install([:kino])

Part 1

commands = """
forward 5
down 5
forward 8
up 3
down 8
forward 2
"""

current_pos =
  commands
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    [direction, step] = String.split(line, " ")
    {direction, String.to_integer(step)}
  end)
  |> Enum.reduce({0, 0}, fn command, {horizontal_pos, depth} ->
    case command do
      {"forward", step} ->
        {horizontal_pos + step, depth}

      {"down", step} ->
        {horizontal_pos, depth + step}

      {"up", step} ->
        {horizontal_pos, depth - step}
    end
  end)

{horizontal_pos, depth} = current_pos

horizontal_pos * depth

Part 2

example_commands = """
forward 5
down 5
forward 8
up 3
down 8
forward 2
"""

commands = Kino.Input.textarea("Please input your file:", default: example_commands)
# horizontal_pos, depth, aim
start_pos = {0, 0, 0}

current_pos =
  commands
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    [direction, step] = String.split(line, " ")
    {direction, String.to_integer(step)}
  end)
  |> Enum.reduce(start_pos, fn command, {horizontal_pos, depth, aim} ->
    case command do
      {"forward", step} ->
        {horizontal_pos + step, depth + aim * step, aim}

      {"down", step} ->
        {horizontal_pos, depth, aim + step}

      {"up", step} ->
        {horizontal_pos, depth, aim - step}
    end
  end)

{horizontal_pos, depth, _aim} = current_pos

horizontal_pos * depth