Skip to content

Instantly share code, notes, and snippets.

@seangeo
Last active May 29, 2024 13:37
Show Gist options
  • Save seangeo/7b1fba08ac66e81b590ff0db5bfe1087 to your computer and use it in GitHub Desktop.
Save seangeo/7b1fba08ac66e81b590ff0db5bfe1087 to your computer and use it in GitHub Desktop.
defmodule Day1P2 do
@number_words %{
"zero" => 0,
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"six" => 6,
"seven" => 7,
"eight" => 8,
"nine" => 9
}
# Replaces words representing numbers with the number itself
def numberify(line) do
String.replace(line, Map.keys(@number_words), fn word -> to_string(@number_words[word]) end)
end
def integers(codepoints) do
codepoints
|> Enum.flat_map(fn cp ->
case Integer.parse(cp) do
{i, _} -> [i]
:error -> []
end
end)
end
def pairs(integers) do
[List.first(integers), List.last(integers)]
end
end
{:ok, file} = File.open("data/day1p1.txt")
file
|> IO.stream(:line)
|> Stream.map(&String.trim(&1))
|> Stream.map(&Day1P2.numberify(&1))
|> Stream.map(&String.codepoints(&1))
|> Stream.map(&Day1P2.integers/1)
|> Stream.map(&Day1P2.pairs/1)
|> Stream.map(fn [a, b] -> a * 10 + b end)
|> Enum.sum()
|> IO.puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment