1
1
Fork 0

Day 5 with two linked lists. Really fast.

I fully blame betseg for this, we had an hour of discussion whether you
could make this O(n). Turns out, you can.
This commit is contained in:
g 2018-12-05 21:58:53 +08:00
parent 61714a4c19
commit 72c4607879
No known key found for this signature in database
GPG key ID: 60F3D48C2F3C0415

53
day5_doublelinked.exs Normal file
View file

@ -0,0 +1,53 @@
defmodule DayFive do
def part_one(input) do
shortened = fully_react_new(input)
# IO.puts shortened
(String.length shortened) - 1
end
def fully_react(input) do
replacer = ~r/Aa|Bb|Cc|Dd|Ee|Ff|Gg|Hh|Ii|Jj|Kk|Ll|Mm|Nn|Oo|Pp|Qq|Rr|Ss|Tt|Uu|Ww|Vv|Xx|Yy|Zz|aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|wW|vV|xX|yY|zZ/
replace_forever(input, replacer, "")
end
def replace_forever(string, pattern, replacement) do
if Regex.match?(pattern, string) do
replace_forever(Regex.replace(pattern, string, replacement), pattern, replacement)
else
string
end
end
def react([<< char1 >> , << char2 >> | tail], rev) when char1 == char2 - 32 or char2 == char1 - 32, do: react(tail, rev)
def react([<< char1 >> | tail], [<< char2 >> | rev]) when char1 == char2 - 32 or char2 == char1 - 32, do: react(tail, rev)
def react([char | tail], rev), do: react(tail, [char | rev])
def react("", rev), do: rev
def react([], rev), do: rev
def fully_react_new(input) do
# IO.puts "mark"
String.reverse(Enum.join(react(String.codepoints(input), [])))
end
#def fully_react_new(input, acc) when input == acc, do: acc
#def fully_react_new(input, _acc) do
# IO.puts("#{length _acc} #{length input}")
# fully_react_new(react(input), input)
#end
def part_two(input) do
chars = Enum.map(?a..?z, &(<< &1 >>))
[{_char, poly} | _ ] = Enum.map(chars, fn char -> {char, String.replace(input, char, "")} end)
|> Enum.map(fn {char, poly} -> {char, String.replace(poly, String.upcase(char), "") } end)
|> Enum.map(fn {char, poly} -> {char, fully_react_new(poly)} end)
|> Enum.sort_by(fn {_char, poly} -> String.length(poly) end)
# IO.puts poly
String.length(poly) - 1
end
end
{:ok, content} = File.read "input5.txt"
IO.puts "Part 1: #{DayFive.part_one(content)}"
IO.puts "Part 2: #{DayFive.part_two(content)}"