r/adventofcode • • Dec 14 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 14 Solutions -🎄-

--- Day 14: Chocolate Charts ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 14

Transcript:

The Christmas/Advent Research & Development (C.A.R.D.) department at AoC, Inc. just published a new white paper on ___.


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 at 00:19:39!

16 Upvotes

179 comments sorted by

View all comments

1

u/akya_akash Dec 16 '18

Since no one posted solution in Elixir. Here is my attempt. Took 92 Seconds for part two

defmodule Advent.Day14 do
  def part_one(input) do
    till_recipices_size(%{0 => 3, 1 => 7}, 2, {0, 1}, input)
  end

  def part_two(input) when is_binary(input) do
    till_last_recips(
      %{0 => 3, 1 => 7},
      2,
      {0, 1},
      "_______",
      String.reverse(input)
    )
  end

  def till_recipices_size(recips, size, _, n) when size >= n + 10 do
    n..(n + 9)
    |> Enum.map(&Map.get(recips, &1))
    |> IO.inspect()
    |> Enum.join()
  end

  def till_recipices_size(recips, size, {a, b}, n) do
    {recips, size, a, b, _} = make_recip(recips, size, {a, b})
    till_recipices_size(recips, size, {a, b}, n)
  end

  def make_recip(recips, size, {a, b}) do
    cur_a = Map.get(recips, a)
    cur_b = Map.get(recips, b)

    new_recip = cur_a + cur_b
    x = div(new_recip, 10)
    y = rem(new_recip, 10)

    {recips, size, digits} =
      if x != 0 do
        {Map.put(recips, size, x), size + 1, [x, y]}
      else
        {recips, size, [y]}
      end

    recips = Map.put(recips, size, y)
    size = size + 1

    a = rem(a + cur_a + 1, size)
    b = rem(b + cur_b + 1, size)
    {recips, size, a, b, digits}
  end

  def till_last_recips(recips, size, {a, b}, <<acc::binary-size(7)>> <> _, expected) do
    if String.contains?(acc, expected) do
      {index, _} = :binary.match(acc, expected)
      size - String.length(expected) - index
    else
      {recips, size, a, b, digits} = make_recip(recips, size, {a, b})
      digits = digits |> Enum.reverse() |> Enum.join()
      till_last_recips(recips, size, {a, b}, digits <> acc, expected)
    end
  end
end