Day1 faster

This commit is contained in:
Adam Millerchip 2023-12-01 23:52:27 +09:00
parent ad1826489e
commit 27babd9ed7

View file

@ -2,37 +2,37 @@ defmodule Day1 do
def part1(input) do def part1(input) do
input input
|> Enum.map(fn line -> |> Enum.map(fn line ->
numbers = String.replace(line, ~r/[^1-9]/, "") numbers = filter_digits(line)
String.to_integer(String.first(numbers) <> String.last(numbers)) String.to_integer(String.first(numbers) <> String.last(numbers))
end) end)
|> Enum.sum() |> Enum.sum()
end end
def filter_digits(<<>>), do: <<>>
def filter_digits(<<x, rest::binary>>) when x in ?1..?9, do: <<x>> <> filter_digits(rest)
def filter_digits(<<_, rest::binary>>), do: filter_digits(rest)
def part2(input) do def part2(input) do
input input
|> Enum.map(fn line -> |> Enum.map(fn line ->
numbers = numbers = filter_digits2(line)
line
|> string_to_digits()
|> String.replace(~r/[^1-9]/, "")
String.to_integer(String.first(numbers) <> String.last(numbers)) String.to_integer(String.first(numbers) <> String.last(numbers))
end) end)
|> Enum.sum() |> Enum.sum()
end end
def string_to_digits(line) do def filter_digits2(<<>>), do: <<>>
line def filter_digits2(<<x, rest::binary>>) when x in ?1..?9, do: <<x>> <> filter_digits2(rest)
|> String.replace("one", "o1e") def filter_digits2(<<"one", rest::binary>>), do: "1" <> filter_digits2("e" <> rest)
|> String.replace("two", "t2o") def filter_digits2(<<"two", rest::binary>>), do: "2" <> filter_digits2("o" <> rest)
|> String.replace("three", "t3e") def filter_digits2(<<"three", rest::binary>>), do: "3" <> filter_digits2("e" <> rest)
|> String.replace("four", "f4r") def filter_digits2(<<"four", rest::binary>>), do: "4" <> filter_digits2("r" <> rest)
|> String.replace("five", "f5e") def filter_digits2(<<"five", rest::binary>>), do: "5" <> filter_digits2("e" <> rest)
|> String.replace("six", "s6x") def filter_digits2(<<"six", rest::binary>>), do: "6" <> filter_digits2("x" <> rest)
|> String.replace("seven", "s7n") def filter_digits2(<<"seven", rest::binary>>), do: "7" <> filter_digits2("n" <> rest)
|> String.replace("eight", "e8t") def filter_digits2(<<"eight", rest::binary>>), do: "8" <> filter_digits2("t" <> rest)
|> String.replace("nine", "n9e") def filter_digits2(<<"nine", rest::binary>>), do: "9" <> filter_digits2("e" <> rest)
end def filter_digits2(<<_, rest::binary>>), do: filter_digits2(rest)
def input do def input do
with [input_filename] <- System.argv(), with [input_filename] <- System.argv(),