Powered by AppSignal & Oban Pro

Day 15 - Advent of Code 2015

lib/advent_of_code/2015/day-15.livemd

Day 15 - Advent of Code 2015

Mix.install([:kino, :benchee])
:ok

Links

Prompt

--- Day 15: Science for Hungry People ---

Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients.

Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon:

  • capacity (how well it helps the cookie absorb milk)
  • durability (how well it keeps the cookie intact when full of milk)
  • flavor (how tasty it makes the cookie)
  • texture (how it improves the feel of the cookie)
  • calories (how many calories it adds to the cookie)

You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories.

For instance, suppose you have these two ingredients:

Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3

Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties:

  • A capacity of 44*-1 + 56*2 = 68
  • A durability of 44*-2 + 56*3 = 80
  • A flavor of 44*6 + 56*-2 = 152
  • A texture of 44*3 + 56*-1 = 76

Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero.

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make?

To begin, get your puzzle input.

--- Part Two ---

Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100 teaspoons, same ingredients, same scoring system).

For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go down, though: only 57600000, the best you can do in such trying circumstances.

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500?

Although it hasn't changed, you can still get your puzzle input.

Input

input = Kino.Input.textarea("Please paste your input file:")
input = input |> Kino.Input.read()
"Sprinkles: capacity 2, durability 0, flavor -2, texture 0, calories 3\nButterscotch: capacity 0, durability 5, flavor -3, texture 0, calories 3\nChocolate: capacity 0, durability 0, flavor 5, texture -1, calories 8\nCandy: capacity 0, durability -1, flavor 0, texture 5, calories 8"

Solution

defmodule Day15 do
  defdelegate parse(input), to: __MODULE__.Input

  def part1(input) do
    %{name: input_by_name, prop: input_by_prop} = parse(input)

    input_by_name
    |> Enum.map(fn {k, v} -> {k, v[:max]} end)
    |> calc_max_score([], 0, input_by_prop, &calc_max_score_part1/3)
  end

  def part2(input) do
    %{name: input_by_name, prop: input_by_prop} = parse(input)

    input_by_name
    |> Enum.map(fn {k, v} -> {k, v[:max]} end)
    |> calc_max_score([], 0, input_by_prop, &calc_max_score_part2/3)
  end

  defp calc_max_score_part1(counts, 100, props) do
    count_map = Enum.into(counts, %{})
    cookie_score(props, count_map)
  end

  defp calc_max_score_part2(counts, 100, props) do
    count_map = Enum.into(counts, %{})

    case sum_prop(props.calories, count_map) do
      500 -> cookie_score(props, count_map)
      _ -> 0
    end
  end

  defp sum_prop(per_ingredient, ingredient_count_map) do
    per_ingredient
    |> Enum.map(fn {name, v} ->
      ingredient_count_map[name] * v
    end)
    |> Enum.sum()
  end

  defp cookie_score(props, ingredient_count_map) do
    props
    |> Map.delete(:calories)
    |> Enum.map(fn {_, map} ->
      Enum.max([0, sum_prop(map, ingredient_count_map)])
    end)
    |> Enum.product()
  end

  defp calc_max_score([{name, _} | []], counts, total, props, fun) do
    fun.([{name, 100 - total} | counts], 100, props)
  end

  defp calc_max_score([{name, max} | t], counts, total, props, fun) do
    0..Enum.min([max, 100 - total])
    |> Enum.map(fn x ->
      calc_max_score(t, [{name, x} | counts], total + x, props, fun)
    end)
    |> Enum.max()
  end

  defmodule Input do
    def parse(input) when is_binary(input) do
      input
      |> String.split("\n")
      |> parse()
    end

    def parse(input) when is_list(input) do
      by_name = Enum.map(input, &parse_line/1)
      by_prop = by_prop(by_name)

      by_name =
        by_name
        |> Enum.map(&add_max(&1, by_prop))
        |> Enum.into(%{})

      %{name: Enum.into(by_name, %{}), prop: by_prop}
    end

    defp by_prop([{_name, props} | _] = list) do
      for {k, _} <- props, into: %{} do
        {
          k,
          for({name, ip} <- list, into: %{}, do: {name, ip[k]})
        }
      end
    end

    defp add_max({k, ing_props}, prop_map) do
      max =
        ing_props
        |> Enum.map(fn
          {k, v} -> determine_max(v, prop_map[k])
        end)
        |> Enum.min()

      {k, Map.put(ing_props, :max, max)}
    end

    defp determine_max(negative_value, prop_map) do
      max_value = prop_map |> Map.values() |> Enum.max()

      100..0//-1
      |> Enum.find(fn x ->
        x * negative_value + (100 - x) * max_value > 0
      end)
    end

    def parse_line(line) do
      [name | props] = String.split(line, [": ", ", ", " "])

      {
        name,
        props
        |> Enum.chunk_every(2)
        |> Enum.map(fn
          [k, v] -> {String.to_atom(k), String.to_integer(v)}
        end)
        |> Enum.into(%{})
      }
    end
  end
end
{:module, Day15, <<70, 79, 82, 49, 0, 0, 19, ...>>,
 {:module, Day15.Input, <<70, 79, 82, ...>>, {:parse_line, 1}}}
Day15.parse(input)
%{
  name: %{
    "Butterscotch" => %{calories: 3, capacity: 0, durability: 5, flavor: -3, max: 62, texture: 0},
    "Candy" => %{calories: 8, capacity: 0, durability: -1, flavor: 0, max: 83, texture: 5},
    "Chocolate" => %{calories: 8, capacity: 0, durability: 0, flavor: 5, max: 83, texture: -1},
    "Sprinkles" => %{calories: 3, capacity: 2, durability: 0, flavor: -2, max: 71, texture: 0}
  },
  prop: %{
    calories: %{"Butterscotch" => 3, "Candy" => 8, "Chocolate" => 8, "Sprinkles" => 3},
    capacity: %{"Butterscotch" => 0, "Candy" => 0, "Chocolate" => 0, "Sprinkles" => 2},
    durability: %{"Butterscotch" => 5, "Candy" => -1, "Chocolate" => 0, "Sprinkles" => 0},
    flavor: %{"Butterscotch" => -3, "Candy" => 0, "Chocolate" => 5, "Sprinkles" => -2},
    texture: %{"Butterscotch" => 0, "Candy" => 5, "Chocolate" => -1, "Sprinkles" => 0}
  }
}

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make?

Your puzzle answer was 21367368.

Day15.part1(input)
21367368

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500?

Your puzzle answer was 1766400.

Day15.part2(input)
1766400

Both parts of this puzzle are complete! They provide two gold stars: **

At this point, you should return to your Advent calendar and try another puzzle.

If you still want to see it, you can get your puzzle input.

Tests

ExUnit.start(auto_run: false)

defmodule Day15Test do
  use ExUnit.Case, async: false

  setup_all do
    [
      input:
        "Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8\nCinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3"
    ]
  end

  describe "part1/1" do
    test "returns expected value", %{input: input} do
      assert Day15.part1(input) == 62_842_880
    end
  end

  describe "part2/1" do
    test "returns expected value", %{input: input} do
      assert Day15.part2(input) == 57_600_000
    end
  end
end

ExUnit.run()
..
Finished in 0.00 seconds (0.00s async, 0.00s sync)
2 tests, 0 failures

Randomized with seed 975531
%{excluded: 0, failures: 0, skipped: 0, total: 2}

Benchmarking

# https://github.com/bencheeorg/benchee

Benchee.run(
  %{
    "Part 1" => fn -> Day15.part1(input) end,
    "Part 2" => fn -> Day15.part2(input) end
  },
  memory_time: 2,
  reduction_time: 2
)

nil
Operating System: macOS
CPU Information: Apple M1 Pro
Number of Available Cores: 10
Available memory: 16 GB
Elixir 1.14.2
Erlang 25.1.2

Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 2 s
reduction time: 2 s
parallel: 1
inputs: none specified
Estimated total run time: 22 s

Benchmarking Part 1 ...
Benchmarking Part 2 ...

Name             ips        average  deviation         median         99th %
Part 2         18.47       54.15 ms     ±0.97%       54.04 ms       56.64 ms
Part 1          4.15      241.15 ms     ±0.98%      241.03 ms      250.08 ms

Comparison: 
Part 2         18.47
Part 1          4.15 - 4.45x slower +187.01 ms

Memory usage statistics:

Name           average  deviation         median         99th %
Part 2       120.98 MB     ±0.00%      120.98 MB      120.98 MB
Part 1       470.52 MB     ±0.00%      470.51 MB      470.55 MB

Comparison: 
Part 2       120.98 MB
Part 1       470.52 MB - 3.89x memory usage +349.55 MB

Reduction count statistics:

Name   Reduction count
Part 2         13.55 M
Part 1         55.92 M - 4.13x reduction count +42.37 M

**All measurements for reduction count were the same**
nil