day 2 part 2 done naively

This commit is contained in:
m5r 2024-12-04 00:16:54 +01:00
parent d6b6715e3d
commit e49e64ceef
Signed by: mokhtar
GPG Key ID: 1509B54946D08A95

View File

@ -1027,78 +1027,66 @@ defmodule AdventOfCode.Day02 do
end
defp is_ascending_order?(report) do
count_out_of_order_ascending(report) == 0
end
defp count_out_of_order_ascending(report) do
Enum.with_index(report)
|> Enum.map(fn {level, index} ->
is_last_level = index == length(report) - 1
case is_last_level do
true -> true
false -> level < Enum.at(report, index + 1)
|> Enum.reduce(true, fn {level, index}, acc ->
case index == length(report) - 1 do
true -> acc
false -> acc and level < Enum.at(report, index + 1)
end
end)
|> Enum.filter(fn item -> item == false end)
|> length()
end
defp is_descending_order?(report) do
count_out_of_order_descending(report) == 0
end
defp count_out_of_order_descending(report) do
Enum.with_index(report)
|> Enum.map(fn {level, index} ->
is_last_level = index == length(report) - 1
case is_last_level do
true -> true
false -> level > Enum.at(report, index + 1)
|> Enum.reduce(true, fn {level, index}, acc ->
case index == length(report) - 1 do
true -> acc
false -> acc and level > Enum.at(report, index + 1)
end
end)
|> IO.inspect()
|> Enum.filter(fn item -> item == false end)
|> length()
end
defp difference_is_within_limits?(report) do
count_outside_limits(report) == 0
end
defp count_outside_limits(report) do
Enum.with_index(report)
|> Enum.map(fn {level, index} ->
is_last_level = index == length(report) - 1
case is_last_level do
|> Enum.reduce(true, fn {level, index}, acc ->
case index == length(report) - 1 do
true ->
true
acc
false ->
difference = abs(level - Enum.at(report, index + 1))
difference >= 1 and difference <= 3
acc and difference >= 1 and difference <= 3
end
end)
|> Enum.filter(fn item -> item == false end)
|> length()
end
defp count_unsafe(report) do
outside_limits = count_outside_limits(report)
out_of_order_ascending = count_out_of_order_ascending(report)
out_of_order_descending = count_out_of_order_descending(report)
IO.inspect({outside_limits, out_of_order_ascending, out_of_order_descending})
outside_limits + out_of_order_ascending + out_of_order_descending
end
def part2() do
parse_reports(@input_test)
|> Enum.map(fn report -> count_unsafe(report) end)
|> Enum.filter(fn result -> result <= 1 end)
|> length()
reports = parse_reports(@input)
first_round = reports |> Enum.map(fn report -> is_safe?(report) end)
safe_results = Enum.filter(first_round, fn result -> result == true end) |> length()
potentially_safe_results =
Enum.map(reports, fn report ->
case is_safe?(report) do
true ->
nil
false ->
Enum.with_index(report)
|> Enum.reduce(false, fn {_level, index}, acc ->
case acc do
true ->
true
false ->
List.delete_at(report, index) |> is_safe?()
end
end)
end
end)
|> Enum.filter(fn result -> result == true end)
|> length()
safe_results + potentially_safe_results
end
end