Skip to content

Instantly share code, notes, and snippets.

@HerrBertling
Last active December 1, 2024 12:59
Show Gist options
  • Save HerrBertling/a8fc7bec3ef3c9a6b4b79745e04e13a2 to your computer and use it in GitHub Desktop.
Save HerrBertling/a8fc7bec3ef3c9a6b4b79745e04e13a2 to your computer and use it in GitHub Desktop.
Elixir LiveBook code for Advent of Code 2024, Day 1

AoC 2024 Day 1

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

Input

data = Kino.Input.textarea("Daily input")
input = Kino.Input.read(data)

{list1, list2} =
  input
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    line
    |> String.split()
    |> Enum.map(&String.to_integer/1)
    |> List.to_tuple()
  end)
  |> Enum.unzip()
  |> then(fn {list1, list2} ->
    {Enum.sort(list1), Enum.sort(list2)}
  end)

Part 1

Enum.zip_reduce(list1, list2, 0, fn a, b, acc ->
  acc + abs(a - b)
end)

Part 2

I asked ChatGPT if what I am doing is efficient and it was not. This is what it suggested to do instead. Makes sense to first count list 2 and then "just" Map.get() that count instead of re-counting every step along the way.

counts =
  Enum.reduce(list2, %{}, fn x, acc ->
    Map.update(acc, x, 1, &(&1 + 1))
  end)

result =
  Enum.reduce(list1, 0, fn number, acc ->
    # Get count from map (default to 0)
    appearance = Map.get(counts, number, 0)
    acc + number * appearance
  end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment