r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

51 Upvotes

407 comments sorted by

View all comments

1

u/arathunku Dec 02 '18

Hello! My Elixir solution:

defmodule Advent.Day2 do
  def checksum(ids) do
    counts =
      ids
      |> Enum.map(fn id ->
        id
        |> String.split("", trim: true)
        |> Enum.group_by(& &1)
        |> Enum.map(fn {_, letters} -> Enum.count(letters) end)
        |> Enum.filter(&(&1 == 2 || &1 == 3))
        |> Enum.dedup()
      end)
      |> List.flatten()

    Enum.count(counts, &(&1 == 2)) * Enum.count(counts, &(&1 == 3))
  end

  def common_letters(ids) do
    ids = Enum.map(ids, &String.split(&1, "", trim: true))

    ids
    |> Enum.map(fn id_a ->
      ids
      |> Enum.find(&similar?(Enum.zip(id_a, &1)))
    end)
    |> Enum.filter(&(&1 != nil))
    |> prune_different_letter([])
    |> Enum.reverse()
    |> Enum.join("")
  end

  defp prune_different_letter([[], []], acc), do: acc
  defp prune_different_letter([[a | id_a], [b | id_b]], acc) do
    if a == b do
      prune_different_letter([id_a, id_b], [a | acc])
    else
      prune_different_letter([id_a, id_b], acc)
    end
  end

  defp similar?(letters), do: similar?(letters, 0)
  defp similar?([], 1), do: true
  defp similar?([], _), do: false
  defp similar?([{ x, y } | id], different_letters_count) do
    if x == y do
      similar?(id, different_letters_count)
    else
      similar?(id, 1 + different_letters_count)
    end
  end
end

Testing:

defmodule Advent.Day2Test do
  use ExUnit.Case
  require Logger
  alias Advent.Day2, as: Day

  test "checksum for example" do
    input = ~w(abcdef bababc abbcde abcccd aabcdd abcdee ababab)
    output = 12

    assert Day.checksum(input) == output
  end

  test "common letters between two boxes - example" do
    input = ~w(abcde fghij klmno pqrst fguij axcye wvxyz )
    output = "fgij"

    assert Day.common_letters(input) == output
  end

  test "checksum for input" do
    input = Path.join(__DIR__, "./input.raw") |> File.read!() |> String.split("\n", trim: true)

    Logger.info("Day2: #{Day.checksum(input)} #{Day.common_letters(input)}")
  end
end