Skip to content

Instantly share code, notes, and snippets.

@mrdougwright
Created December 2, 2023 18:57
Show Gist options
  • Save mrdougwright/5d42c55508b2d417e6d3078231d1ffe5 to your computer and use it in GitHub Desktop.
Save mrdougwright/5d42c55508b2d417e6d3078231d1ffe5 to your computer and use it in GitHub Desktop.
AoC 2023 - Day 1
{input, _} = Code.eval_file(File.cwd!() <> "/data/day-01.exs")
defmodule Day1 do
@word_ints %{
"0" => "0",
"1" => "1",
"2" => "2",
"3" => "3",
"4" => "4",
"5" => "5",
"6" => "6",
"7" => "7",
"8" => "8",
"9" => "9",
"eight" => "8",
"five" => "5",
"four" => "4",
"nine" => "9",
"one" => "1",
"seven" => "7",
"six" => "6",
"three" => "3",
"two" => "2",
"zero" => "0"
}
def part1(calibration_values) do
Enum.reduce(calibration_values, 0, fn str, acc ->
int = get_int(str) <> get_int(String.reverse(str))
acc + String.to_integer(int)
end)
end
def part2(values) do
values =
Enum.map(values, fn str ->
get_int_value(str) <> get_int_value_reverse(str)
end)
part1(values)
end
def get_int_value_reverse(str) do
str
|> String.reverse()
|> String.split("")
|> Enum.reduce_while("", fn x, acc ->
case contains_num(acc) do
{:ok, num} -> {:halt, num}
:error -> {:cont, x <> acc}
end
end)
end
def get_int_value(str) do
str
|> String.split("")
|> Enum.reduce_while("", fn x, acc ->
case contains_num(acc) do
{:ok, num} -> {:halt, num}
:error -> {:cont, acc <> x}
end
end)
end
def contains_num(str) do
case Enum.find(@word_ints, fn {word, _int} -> String.contains?(str, word) end) do
nil -> :error
{_word, int} -> {:ok, int}
end
end
defp get_int(str) do
str
|> String.split("", trim: true)
|> Enum.filter(&("0" <= &1 and &1 <= "9"))
|> List.first()
end
end
# Doesn't work, too greedy and replaces first match on num, not
# necessarily first num
# Enum.reduce(@word_ints, str, fn {num, int}, acc ->
# Regex.replace(~r/#{num}/, acc, int)
# end)
# answer = Day1.part1(input)
# IO.inspect(answer)
answer = Day1.part2(input)
IO.inspect(answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment