diff options
-rw-r--r-- | AoC2022/04/makefile | 1 | ||||
-rw-r--r-- | AoC2022/04/solver.ex | 36 |
2 files changed, 37 insertions, 0 deletions
diff --git a/AoC2022/04/makefile b/AoC2022/04/makefile index a7661bd..6516fa4 100644 --- a/AoC2022/04/makefile +++ b/AoC2022/04/makefile @@ -12,3 +12,4 @@ run: sbcl --load ~/.sbclrc --script solver.lisp emacs -batch -l ert -l solver.el -f ert-run-tests-batch-and-exit rustc solver.rs && ./solver + elixir solver.ex diff --git a/AoC2022/04/solver.ex b/AoC2022/04/solver.ex new file mode 100644 index 0000000..0478795 --- /dev/null +++ b/AoC2022/04/solver.ex @@ -0,0 +1,36 @@ +defmodule Solver do + def to_interval(range) do + [left, right] = String.split(range, "-") + {left, ""} = Integer.parse(left) + {right, ""} = Integer.parse(right) + {left, right} + end + + def contained({a0, a1}, {b0, b1}) do + (a0 - b0) * (a1 - b1) <= 0 + end + + def overlap({a0, a1}, {b0, b1}) do + a0 <= b1 && b0 <= a1 + end +end + +{:ok, input} = File.read("input") + +parsed = + input + |> String.split("\n", trim: true) + |> Enum.map(&String.split(&1, ",")) + |> Enum.map(fn [left, right] -> {Solver.to_interval(left), Solver.to_interval(right)} end) + +parsed +|> Enum.map(fn {left, right} -> Solver.contained(left, right) end) +|> Enum.filter(& &1) +|> length +|> IO.puts() + +parsed +|> Enum.map(fn {left, right} -> Solver.overlap(left, right) end) +|> Enum.filter(& &1) +|> length +|> IO.puts() |