add day 2 solutions

This commit is contained in:
Luna 2018-12-02 03:04:16 -03:00
parent b033d3eca7
commit bc3c9a0e46
2 changed files with 146 additions and 0 deletions

69
day2/day2_1.ex Normal file
View File

@ -0,0 +1,69 @@
input = IO.gets("input?")
|> String.trim
|> String.split(" ")
defmodule Solver do
# convert from bool to 1/0
def to_num(boolean) do
if boolean do
1
else
0
end
end
def process(input) do
ids_properties = Enum.map(input, fn box_id ->
# convert string to list
box_id_chars = box_id |> String.split("") |> Enum.filter(fn char ->
char != ""
end)
# get the letter repeats for each char in it
counts = Enum.map(box_id_chars, fn id_letter ->
count = Enum.count(box_id_chars, fn character ->
character == id_letter
end)
count
end)
IO.puts "counts: #{inspect counts}"
# check if it has letters repeated twice or three times
r = {
Enum.count(counts, fn count -> count == 2 end) > 1,
Enum.count(counts, fn count -> count == 3 end) > 1
}
IO.puts "result: #{inspect r}"
r
end)
# count all box ids that have twice/three-repeated
{total_twice, total_three} = Enum.reduce(ids_properties, {0, 0}, fn property, acc ->
{old_twice, old_three} = acc
{is_twice, is_three} = property
change_tw = to_num(is_twice)
change_th = to_num(is_three)
{
old_twice + change_tw,
old_three + change_th
}
end)
# Solution
total_twice * total_three
end
end
IO.puts "input: #{input}"
result = Solver.process(input)
IO.puts "ACTUAL RESULT: #{result}"

77
day2/day2_2.ex Normal file
View File

@ -0,0 +1,77 @@
input = IO.gets("input?")
|> String.trim
|> String.split(" ")
defmodule Solver do
def to_list(string) do
case string do
"" -> []
_ ->
string
|> String.split("")
|> Enum.filter(fn char ->
char != ""
end)
end
end
# get the common string between the box ids
def get_common(box_id, box_id_2) do
# convert to list
box_id_l = to_list(box_id)
box_id_2_l = to_list(box_id_2)
# zip them
list_chars = Enum.zip(box_id_l, box_id_2_l)
# if theyre equal, we add to the accumulator
common_str = Enum.reduce(list_chars, "", fn tup, acc ->
{c1, c2} = tup
if c1 == c2 do
acc <> c1
else
acc
end
end)
# for common_str to be valid it has to be
# L(common_str) = L(box_id) - 1
# since correct box ids have just *ONE*
# character difference between them
if String.length(common_str) == (String.length(box_id) - 1) do
{:ok, common_str}
else
:not_found
end
end
def solve(input) do
# find all the common strings
# and filter shit
commons = Enum.map(input, fn box_id ->
Enum.map(input, fn box_id_2 ->
common = get_common(box_id, box_id_2)
case common do
:not_found -> nil
{:ok, str} -> str
end
end)
|> Enum.filter(fn combo ->
combo != nil
end)
end)
|> Enum.filter(fn combo ->
combo != []
end)
end
end
res = Solver.solve(input)
IO.puts "result: #{inspect res}"