Skip to content

Instantly share code, notes, and snippets.

@jaeyson
Created October 7, 2022 07:39
Show Gist options
  • Save jaeyson/10055d9c7dd21e8e55793b4b99537088 to your computer and use it in GitHub Desktop.
Save jaeyson/10055d9c7dd21e8e55793b4b99537088 to your computer and use it in GitHub Desktop.
Submarine route command
data =
"""
forward 5
down 5
forward 8
up 3
down 8
forward 2
"""
instructions = String.split(data, ~r/[\n]+/, trim: true)
coordinates =
instructions
|> Enum.reduce(%{x: 0, y: 0}, fn cmd, acc ->
case cmd do
"forward " <> step ->
step = Integer.parse(step) |> elem(0)
%{acc | x: acc.x + step}
"down " <> step ->
step = Integer.parse(step) |> elem(0)
%{acc | y: acc.y + step}
"up " <> step ->
step = Integer.parse(step) |> elem(0)
%{acc | y: acc.y - step}
end
end)
%{x: x, y: y} = coordinates
IO.inspect(x * y, label: "total")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment