|
| 1 | +defmodule Puzzle do |
| 2 | + def count_steps(data, mode \\ :default) do |
| 3 | + instructions = |
| 4 | + data |
| 5 | + |> String.split |
| 6 | + |> Enum.map(&String.to_integer/1) |
| 7 | + |
| 8 | + cache = build_cache(instructions) |
| 9 | + |
| 10 | + all_steps(cache, 0, 0, mode) |
| 11 | + end |
| 12 | + |
| 13 | + defp build_cache(instructions) do |
| 14 | + idxs = 0..(length(instructions) - 1) |
| 15 | + |
| 16 | + idxs |> Enum.zip(instructions) |> Map.new |
| 17 | + end |
| 18 | + |
| 19 | + defp all_steps(cache, position, steps, mode) do |
| 20 | + {move, updated_cache} = |
| 21 | + Map.get_and_update(cache, position, fn mv -> |
| 22 | + if mode == :weird && mv >= 3 do |
| 23 | + {mv, mv - 1} |
| 24 | + else |
| 25 | + {mv, mv + 1} |
| 26 | + end |
| 27 | + end) |
| 28 | + |
| 29 | + next_position = position + move |
| 30 | + |
| 31 | + if rem(steps, 100_000) == 0, do: IO.puts "Steps: #{steps}" |
| 32 | + |
| 33 | + if next_position < 0 || next_position >= map_size(cache) do |
| 34 | + steps + 1 |
| 35 | + else |
| 36 | + all_steps(updated_cache, next_position, steps + 1, mode) |
| 37 | + end |
| 38 | + end |
| 39 | +end |
| 40 | + |
| 41 | +mode = List.first(System.argv) |
| 42 | + |
| 43 | +if mode == "test" do |
| 44 | + ExUnit.start() |
| 45 | + |
| 46 | + defmodule PuzzleTest do |
| 47 | + use ExUnit.Case |
| 48 | + |
| 49 | + describe "count_steps(data, :default)" do |
| 50 | + setup [:with_default_mode] |
| 51 | + |
| 52 | + test "when data = [0 3 0 1 -3]", context do |
| 53 | + data = "0\n3\n0\n1\n-3" |
| 54 | + steps = Puzzle.count_steps(data, context[:mode]) |
| 55 | + assert steps == 5 |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + describe "count_steps(data, :weird)" do |
| 60 | + setup [:with_weird_mode] |
| 61 | + |
| 62 | + test "when data = [0 3 0 1 -3]", context do |
| 63 | + data = "0\n3\n0\n1\n-3" |
| 64 | + steps = Puzzle.count_steps(data, context[:mode]) |
| 65 | + assert steps == 10 |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + defp with_default_mode(_context) do |
| 70 | + [mode: :default] |
| 71 | + end |
| 72 | + |
| 73 | + defp with_weird_mode(_context) do |
| 74 | + [mode: :weird] |
| 75 | + end |
| 76 | + end |
| 77 | +else |
| 78 | + data = "05.txt" |> File.read! |> String.trim_trailing |
| 79 | + |
| 80 | + {time1, steps} = :timer.tc(fn -> Puzzle.count_steps(data) end) |
| 81 | + time1_seconds = time1 / 1_000_000 |
| 82 | + |
| 83 | + IO.puts "The number of steps: #{steps} (in #{time1_seconds}s)" |
| 84 | + |
| 85 | + {time2, steps_weird} = :timer.tc(fn -> Puzzle.count_steps(data, :weird) end) |
| 86 | + time2_seconds = time2 / 1_000_000 |
| 87 | + |
| 88 | + IO.puts "The number of steps (weird): #{steps_weird} (in #{time2_seconds}s)" |
| 89 | +end |
0 commit comments