Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 04

2022/elixir/day04.livemd

Day 04

Mix.install([
  {:kino, "~> 0.7.0"}
])

Puzzle Input

area = Kino.Input.textarea("Puzzle Input")
puzzle_input = Kino.Input.read(area)
example_input = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
"""

Common

pairs =
  puzzle_input
  |> String.split(["-", ",", "\n"], trim: true)
  |> Stream.map(fn str -> str |> Integer.parse() |> elem(0) end)
  |> Stream.chunk_every(2)
  |> Stream.map(&List.to_tuple/1)
  |> Stream.chunk_every(2)
  |> Stream.map(&List.to_tuple/1)
defmodule Logistics do
  def superset?({lhsStart, lhsEnd}, {rhsStart, rhsEnd}) do
    lhsStart <= rhsStart &amp;&amp; lhsEnd >= rhsEnd
  end

  def overlap?({lhsStart, lhsEnd}, {rhsStart, _}) do
    lhsStart <= rhsStart &amp;&amp; lhsEnd >= rhsStart
  end
end
ExUnit.start(autorun: false)

defmodule LogisticsTests do
  use ExUnit.Case, async: true

  test "superset" do
    assert Logistics.superset?({2, 8}, {3, 7})
    refute Logistics.superset?({2, 6}, {4, 8})
  end

  test "overlap" do
    assert Logistics.overlap?({5, 7}, {7, 9})
    refute Logistics.overlap?({2, 4}, {6, 8})
  end
end

ExUnit.run()

Part One

pairs
|> Stream.filter(fn {lhs, rhs} ->
  Logistics.superset?(lhs, rhs) || Logistics.superset?(rhs, lhs)
end)
|> Enum.count()

Part Two

pairs
|> Stream.filter(fn {lhs, rhs} ->
  Logistics.overlap?(lhs, rhs) || Logistics.overlap?(rhs, lhs)
end)
|> Enum.count()