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

Day1

2024/elixir/day1.livemd

Day1

Mix.install([
  {:kino_aoc, git: "https://github.com/ljgago/kino_aoc"}
])

Setup

{:ok, data} = KinoAOC.download_puzzle("2024", "1", System.fetch_env!("LB_AOC_SECRET"))

Solve

defmodule Day1 do
  def parse(data) do
    data
    |> String.split("\n", trim: true)
    |> Enum.reduce({[],[]}, fn str, {l1, l2} ->
        [d1, d2] = str |> String.split() |> Enum.map(&String.to_integer/1)
        {[d1 | l1], [d2 | l2]}
    end)
  end

  def solve(data) do
    {l1, l2} = parse(data)
    task1(l1, l2)
    task2(l1, l2)
  end

  def task1(l1, l2) do
    l1s = Enum.sort(l1)
    l2s = Enum.sort(l2)
    length(l1) == length(l2) || IO.puts("Lists doesn't match!")

    Enum.zip(l1s, l2s)
    |> Enum.map(fn {d1, d2} -> abs(d1 - d2) end)
    |> Enum.sum()
    |> IO.inspect(label: "res1 >>>")
  end

  def task2(l1, l2) do
    l2f =  Enum.frequencies(l2)

    l1
    |> Enum.map(fn d1 -> d1 * Access.get(l2f, d1, 0) end)
    |> Enum.sum()
    |> IO.inspect(label: "res2 >>>")
  end
end

test_data =
"""
3   4
4   3
2   5
1   3
3   9
3   3
"""

Day1.solve(test_data)
Day1.solve(data)