Day 08
Mix.install([
{:kino, "~> 0.14.2"}
])
IEx.Helpers.c("/Users/johnb/dev/2015adventOfCode/advent_of_code.ex")
alias AdventOfCode, as: AOC
alias Kino.Input
require Integer
use Bitwise
# Note: when making the next template, something like this works well:
# `cat day01.livemd | sed 's/01/02/' > day02.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 Day08 do
def solve1(text) do
lines = AOC.as_single_lines(text)
lines
|> Enum.map(fn line ->
center = String.slice(line, 1..-2//1)
outer_quote_length = 2
inner_quotes_and_slashes = Regex.scan(~r/(\\"|\\\\)/, center)
escaped_chars = Regex.scan(~r/(\\x[0-9a-f][0-9a-f])/, center)
# Just count the extra chars needed
(outer_quote_length +
Enum.count(inner_quotes_and_slashes) +
Enum.count(escaped_chars) * 3)
end)
|> Enum.sum()
end
def solve2(text) do
lines = AOC.as_single_lines(text)
lines
|> Enum.map(fn line ->
center = String.slice(line, 1..-2//1)
outer_quote_length = 2
inner_quotes_and_slashes = Regex.scan(~r/("|\\)/, center)
# Just count the extra chars needed
(outer_quote_length * 2 +
Enum.count(inner_quotes_and_slashes)
)
end)
|> Enum.sum()
end
end
# Example data:
# ""
# "abc"
# "aaa\"aaa"
# "\x27"
p1data.()
|> Day08.solve1()
|> IO.inspect(label: "\n*** Part 1 solution (example: 12)")
# 1362 is too high
# 1350 is correct after ensuring hex chars
p1data.()
|> Day08.solve2()
|> IO.inspect(label: "\n*** Part 2 solution (example: 19)")
# 2085