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

2018 Day 03

livebooks/2018/03.livemd

2018 Day 03

Mix.install([
  {:req, "~> 0.4.5"},
  {:vega_lite, "~> 0.1.8"},
  {:kino_vega_lite, "~> 0.1.11"}
])

alias VegaLite, as: Vl

defmodule AOC do
  @aoc_session System.fetch_env!("LB_AOC_SESSION")

  def day(day, year) when day in 1..25 do
    headers = [cookie: "session=#{@aoc_session}"]
    req = Req.new(base_url: "https://adventofcode.com/#{year}/day/#{day}", headers: headers)
    input = Req.get!(req, url: "/input").body

    if input =~ "Please don't repeatedly request this endpoint before it unlocks",
      do: {:error, "Day #{day} hasn't been unlocked yet"},
      else: {:ok, %{req: req, input: input}}
  end

  def submit(answer, %{req: req}, part \\ :part_1) when part in [:part_1, :part_2] do
    part = if part == :part_2, do: 2, else: 1

    if !part_already_completed?(part, req) do
      body = Req.post!(req, url: "/answer", form: [level: part, answer: answer]).body

      cond do
        body =~ "That's the right answer" -> {:correct, answer}
        body =~ "your answer is too low" -> {:too_low, answer}
        body =~ "your answer is too high" -> {:too_high, answer}
        :else -> {:incorrect, answer}
      end
    else
      {:already_completed_part, answer}
    end
  end

  defp part_already_completed?(part, req) do
    body = Req.get!(req).body

    cond do
      body =~ "Both parts of this puzzle are complete!" -> true
      body =~ "The first half of this puzzle is complete!" -> part == 1
      :else -> false
    end
  end

  def nums(str) do
    Regex.scan(~r/\d+/, str) |> Enum.map(fn [x] -> String.to_integer(x) end)
  end
end

{:ok, day} = AOC.day(3, 2018)

Part 1

test_input = """
#1 @ 1,3: 4x4
#2 @ 3,1: 4x4
#3 @ 5,5: 2x2
"""
defmodule P1 do
  def solve(input) do
    patches =
      input
      |> String.split("\n", trim: true)
      |> Enum.map(fn str ->
        [_id, x, y, w, h] = AOC.nums(str)
        {x..(x + w - 1), y..(y + h - 1)}
      end)

    Enum.reduce(patches, %{}, fn {xs, ys}, grid ->
      for x <- xs, y <- ys, reduce: grid do
        grid -> Map.update(grid, {x, y}, 1, &amp;(&amp;1 + 1))
      end
    end)
    |> Enum.count(fn {_xy, fabric} -> fabric > 1 end)
  end
end

test_input |> P1.solve()
day.input |> P1.solve()

Part 2

defmodule P2 do
  def solve(input) do
    patches =
      input
      |> String.split("\n", trim: true)
      |> Enum.map(fn str ->
        [id, x, y, w, h] = AOC.nums(str)
        {id, x..(x + w - 1), y..(y + h - 1)}
      end)

    {id, _xs, _ys} =
      Enum.find(patches, fn {id, _, _} = patch ->
        patches
        |> List.delete_at(id - 1)
        |> Enum.all?(fn p -> !overlap?(p, patch) end)
      end)

    id
  end

  def overlap?({_id1, x1, y1}, {_id2, x2, y2}) do
    !Range.disjoint?(x1, x2) &amp;&amp; !Range.disjoint?(y1, y2)
  end
end

test_input |> P2.solve()
day.input |> P2.solve()