diff --git a/2022/day09.livemd b/2022/day09.livemd index 6c5d8f9..9f02c35 100644 --- a/2022/day09.livemd +++ b/2022/day09.livemd @@ -34,20 +34,77 @@ Mix.install([ moves = puzzle_input |> String.split("\n", trim: true) - |> Enum.map(fn line -> + |> Enum.flat_map(fn line -> [dir, steps] = String.split(line) - {dir, String.to_integer(steps)} + deltas = + case dir do + "R" -> {-1, 0} + "L" -> {+1, 0} + "U" -> {0, +1} + "D" -> {0, -1} + end + + List.duplicate(deltas, String.to_integer(steps)) end) - |> Enum.flat_map(fn {dir, steps} -> List.duplicate(dir, steps) end) ``` ``` -["L", "R", "L", "U", "R", "R", "U", "D", "D", "R", "R", "U", "D", "D", "U", "U", "L", "L", "D", "U", - "D", "D", "L", "L", "D", "L", "L", "D", "D", "L", "U", "U", "R", "R", "L", "D", "D", "L", "L", "R", - "R", "D", "D", "L", "U", "R", "U", "L", "D", "R", ...] +[ + {1, 0}, + {-1, 0}, + {1, 0}, + {0, 1}, + {-1, 0}, + {-1, 0}, + {0, 1}, + {0, -1}, + {0, -1}, + {-1, 0}, + {-1, 0}, + {0, 1}, + {0, -1}, + {0, -1}, + {0, 1}, + {0, 1}, + {1, 0}, + {1, 0}, + {0, -1}, + {0, 1}, + {0, -1}, + {0, -1}, + {1, 0}, + {1, 0}, + {0, -1}, + {1, 0}, + {1, 0}, + {0, -1}, + {0, -1}, + {1, 0}, + {0, 1}, + {0, 1}, + {-1, 0}, + {-1, 0}, + {1, 0}, + {0, -1}, + {0, -1}, + {1, 0}, + {1, 0}, + {-1, 0}, + {-1, 0}, + {0, -1}, + {0, -1}, + {1, 0}, + {0, 1}, + {-1, 0}, + {0, 1}, + {1, 0}, + {0, ...}, + {...}, + ... +] ``` ```elixir @@ -62,7 +119,7 @@ defmodule Rope do def run(rope, moves) do {_rope, tail_positions} = - Enum.reduce(moves, {rope, MapSet.new([Rope.last(rope)])}, fn dir, {rope, acc} -> + Enum.reduce(moves, {rope, MapSet.new()}, fn dir, {rope, acc} -> new_rope = Rope.move(rope, dir) {new_rope, MapSet.put(acc, Rope.last(new_rope))} @@ -73,14 +130,8 @@ defmodule Rope do def last(%__MODULE__{segments: list}), do: List.last(list) - def move(%__MODULE__{segments: [%{x: x, y: y} | tails]}, dir) do - head = - case dir do - "L" -> %{x: x + 1, y: y} - "R" -> %{x: x - 1, y: y} - "U" -> %{x: x, y: y + 1} - "D" -> %{x: x, y: y - 1} - end + def move(%__MODULE__{segments: [%{x: x, y: y} | tails]}, {dx, dy}) do + head = %{x: x + dx, y: y + dy} %__MODULE__{segments: move_tails([head | tails])} end @@ -95,23 +146,22 @@ defmodule Rope do defp move_tails([head, tail | rest]) do {dx, dy} = step(head, tail) - [head | move_tails([%{x: head.x - dx, y: head.y - dy} | rest])] + [head | move_tails([%{x: tail.x + dx, y: tail.y + dy} | rest])] end def sgn(0), do: 0 def sgn(n) when n < 0, do: -1 def sgn(_), do: 1 - defp step(%{x: x1, y: y1}, %{x: x2, y: y2}) do - {sgn(div(x1 - x2, 2)), sgn(div(y1 - y2, 2))} - end + defp step(%{x: x1, y: y1}, %{x: x2, y: y2}), + do: {sgn(x1 - x2), sgn(y1 - y2)} end ``` ``` -{:module, Rope, <<70, 79, 82, 49, 0, 0, 23, ...>>, {:step, 2}} +{:module, Rope, <<70, 79, 82, 49, 0, 0, 22, ...>>, {:step, 2}} ``` ## Task 1