Day 5. Switched from Roc to Elixir. The compiler hasn\'t crashed once yet!
parent
5f3c8baba8
commit
315162e799
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,55 @@
|
||||
defmodule Day5 do
|
||||
def run do
|
||||
{rules, updates} = parseFile("data.txt")
|
||||
|
||||
{validUpdates, invalidUpdates} = Enum.split_with(updates, &updateValid?(&1, rules))
|
||||
|
||||
validMiddles = Enum.map(validUpdates, &middleDigit/1)
|
||||
IO.puts("Part 1: #{Enum.sum(validMiddles)}")
|
||||
|
||||
# sort the invalid ones with a custom sorter that looks for [a, b] in the rules list. if [a, b] exists, sort a before b
|
||||
invalidSorted =
|
||||
Enum.map(invalidUpdates, fn update ->
|
||||
Enum.sort(update, fn first, second ->
|
||||
Enum.member?(rules, [first, second])
|
||||
end)
|
||||
end)
|
||||
|
||||
invalidMiddles = Enum.map(invalidSorted, &middleDigit/1)
|
||||
IO.puts("Part 2: #{Enum.sum(invalidMiddles)}")
|
||||
end
|
||||
|
||||
defp parseFile(file) do
|
||||
[topSection, bottomSection] = File.read!(file) |> String.split("\n\n")
|
||||
|
||||
rules = String.split(topSection, "\n") |> Enum.map(fn l -> String.split(l, "|") end)
|
||||
|
||||
updates =
|
||||
String.split(bottomSection, "\n")
|
||||
|> Enum.drop(-1)
|
||||
|> Enum.map(fn l -> String.split(l, ",") end)
|
||||
|
||||
{rules, updates}
|
||||
end
|
||||
|
||||
defp updateValid?(update, rules) do
|
||||
Enum.reduce_while(rules, true, fn [left, right], acc ->
|
||||
# if it doesn't contain both, or it does and they're in the right order
|
||||
if !(Enum.member?(update, left) and Enum.member?(update, right)) or
|
||||
Enum.find_index(update, &(&1 == left)) < Enum.find_index(update, &(&1 == right)) do
|
||||
# continue and try the next one
|
||||
{:cont, acc}
|
||||
else
|
||||
# otherwise halt the reduction, this update is invalid
|
||||
{:halt, false}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp middleDigit(update) do
|
||||
middle = trunc(length(update) / 2)
|
||||
String.to_integer(Enum.at(update, middle))
|
||||
end
|
||||
end
|
||||
|
||||
Day5.run()
|
@ -0,0 +1,28 @@
|
||||
47|53
|
||||
97|13
|
||||
97|61
|
||||
97|47
|
||||
75|29
|
||||
61|13
|
||||
75|53
|
||||
29|13
|
||||
97|29
|
||||
53|29
|
||||
61|53
|
||||
97|53
|
||||
61|29
|
||||
47|13
|
||||
75|47
|
||||
97|75
|
||||
47|61
|
||||
75|61
|
||||
47|29
|
||||
75|13
|
||||
53|13
|
||||
|
||||
75,47,61,53,29
|
||||
97,61,53,29,13
|
||||
75,29,13
|
||||
75,97,47,61,53
|
||||
61,13,29
|
||||
97,13,75,29,47
|
Loading…
Reference in New Issue