Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 12

day12.livemd

Day 12

Mix.install([
  {:kino, "~> 0.14.2"},
  {:json, "~> 1.4"}
])

IEx.Helpers.c("/Users/johnb/dev/2015adventOfCode/advent_of_code.ex")
alias AdventOfCode, as: AOC
alias Kino.Input

# Note: when making the next template, something like this works well:
#   `cat day04.livemd | sed 's/03/04/' > day04.livemd`
#

Installation and Data

input_p1example = Kino.Input.textarea("Example Data")
input_p1puzzleInput = Kino.Input.textarea("Puzzle Input")
input_source_select =
  Kino.Input.select("Source", [{:example, "example"}, {:puzzle_input, "puzzle input"}])
p1data = fn ->
  (Kino.Input.read(input_source_select) == :example &&
     Kino.Input.read(input_p1example)) ||
    Kino.Input.read(input_p1puzzleInput)
end

Part 1

defmodule Day12 do
  def solve1(text) do
    Regex.scan(~r/(\-?\d+)/m, text)
    |> Enum.map(fn [_, match] -> String.to_integer(match) end)
    |> Enum.sum()
  end

  def count_non_red(int) when is_integer(int), do: int
  def count_non_red(list) when is_list(list) do
    Enum.map(list, fn item -> count_non_red(item) end)
    |> Enum.sum()
  end
  def count_non_red(map) when is_map(map) do
    values = Map.values(map)
    if Enum.any?(values, fn value -> value == "red" end) do
      0
    else
      count_non_red(values)
    end
  end
  def count_non_red(_huh), do: 0

  def solve2(text) do
    {:ok, list} = JSON.decode(text)
    count_non_red(list)
  end
end

# Example data:
# [[1,2,3] ,
# [1,{"c":"red","b":2},3] ,
# {"d":"red","e":[1,2,3,4],"f":5} ,
# [1,"red",5]]

p1data.()
|> Day12.solve1()
|> IO.inspect(label: "\n*** Part 1 solution (example: 33)")
# 156366

p1data.()
|> Day12.solve2()
|> IO.inspect(label: "\n*** Part 2 solution (example: 16)")
# 96852