Skip to content

Instantly share code, notes, and snippets.

@jstewart
Created December 3, 2022 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstewart/381ca470436065a42f96592b559de862 to your computer and use it in GitHub Desktop.
Save jstewart/381ca470436065a42f96592b559de862 to your computer and use it in GitHub Desktop.
defmodule AdventOfCode.Day05 do
@moduledoc """
Intuition:
Part 1: Split each line in half
convert each char of split line into set, find the intersection
calculate the priority of the intersection and sum
Part 2: Chunk input into groups of 3 lines
convert each char of each chunk into set, find the intersection
between both chunks as sets
calculate the priority of the intersection and sum
"""
def part1(args) do
args
|> Enum.map(fn {l1, l2} -> track_dupes(l1, l2) end)
|> Enum.map(&tally_priorities/1)
|> Enum.sum()
end
def part2(args) do
args
|> Enum.map(fn [l1, l2, l3] -> track_dupes(l1, l2, l3) end)
|> Enum.map(&tally_priorities/1)
|> Enum.sum()
end
defp track_dupes(list1, list2) do
MapSet.intersection(
MapSet.new(list1),
MapSet.new(list2)
)
end
defp track_dupes(list1, list2, list3) do
MapSet.intersection(
track_dupes(list1, list2),
MapSet.new(list3)
)
end
defp calculate_priority(item) do
charcode = String.to_charlist(item) |> hd
if charcode > 96 and charcode < 123, do: charcode - 96, else: charcode - 38
end
defp tally_priorities(set) do
set
|> Enum.map(&calculate_priority/1)
|> Enum.sum()
end
end
@jstewart
Copy link
Author

jstewart commented Dec 3, 2022

Input:

Part 1

    input =
      AdventOfCode.Input.get!(3)
      |> String.split("\n", trim: true)
      |> Enum.map(fn line -> String.split(line, "", trim: true) end)
      |> Enum.map(fn line ->
        n = length(line) / 2
        Enum.split(line, trunc(n))
      end)

Part 2

      AdventOfCode.Input.get!(3)
      |> String.split("\n", trim: true)
      |> Enum.map(fn line -> String.split(line, "", trim: true) end)
      |> Enum.chunk_every(3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment