aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/04/solver.ex
blob: 04787950775a481c60b4bc7527c2a77efca059a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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()