-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_08.ex
42 lines (35 loc) · 1.07 KB
/
day_08.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
defmodule AdventOfCode.Y2015.Day08 do
@moduledoc """
--- Day 8: Matchsticks ---
Problem Link: https://adventofcode.com/2015/day/8
Difficulty: m
Tags: string-encoding annoying
"""
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2015, 8)
def run(input \\ input()) do
input = Transformers.lines(input)
{run_1(input), run_2(input)}
end
defp run_1(input) do
Enum.reduce(input, 0, fn line, acc ->
acc + String.length(line) - actual_length(line)
end)
end
defp run_2(input) do
Enum.reduce(input, 0, fn line, acc ->
acc + expanded_length(line) - String.length(line)
end)
end
@esc_regex ~r/(\\\\|\\\"|\\x[\da-f]{2})/
@empty_regex ~r/\"/
def actual_length(line) do
line
|> unescape(@esc_regex, "*")
|> unescape(@empty_regex, "")
|> String.length()
end
@expansion_regex ~r/(\\|\")/
def expanded_length(line), do: 2 + String.length(unescape(line, @expansion_regex, "**"))
defp unescape(line, regex, replacement), do: Regex.replace(regex, line, replacement)
end