Skip to content

Instantly share code, notes, and snippets.

@tfwright

tfwright/1.exs Secret

Last active December 19, 2022 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfwright/b44f3b5730bcd5c0aaf0d0f9e308a0f4 to your computer and use it in GitHub Desktop.
Save tfwright/b44f3b5730bcd5c0aaf0d0f9e308a0f4 to your computer and use it in GitHub Desktop.
AOC 2022 13
test_pair = fn
[nil, _], _ -> true
[_, nil], _ -> false
[left, right], _ when is_integer(left) and is_integer(right) ->
cond do
left == right -> nil
left < right -> true
right < left -> false
end
pair = [left, right], self when is_list(left) and is_list(right) ->
pair
|> Enum.map(fn list ->
missing = Enum.max([length(left), length(right)]) - length(list)
list ++ List.duplicate(nil, missing)
end)
|> List.zip()
|> Enum.reduce_while(nil, fn {left, right}, valid ->
case self.([left, right], self) do
nil -> {:cont, valid}
valid -> {:halt, valid}
end
end)
pair, self -> pair |> Enum.map(&List.wrap/1) |> self.(self)
end
System.argv()
|> List.first()
|> File.read!()
|> String.split("\n\n", trim: true)
|> Enum.with_index()
|> Enum.reduce(0, fn {pair, idx}, total ->
valid =
pair
|> String.split("\n", trim: true)
|> Enum.map(& &1 |> Code.eval_string() |> elem(0))
|> test_pair.(test_pair)
if valid, do: total + idx + 1, else: total
end)
|> IO.inspect
test_pair = fn
[nil, _], _ -> true
[_, nil], _ -> false
[left, right], _ when is_integer(left) and is_integer(right) ->
cond do
left == right -> nil
left < right -> true
right < left -> false
end
pair = [left, right], self when is_list(left) and is_list(right) ->
pair
|> Enum.map(fn list ->
missing = Enum.max([length(left), length(right)]) - length(list)
list ++ List.duplicate(nil, missing)
end)
|> List.zip()
|> Enum.reduce_while(nil, fn {left, right}, valid ->
case self.([left, right], self) do
nil -> {:cont, valid}
valid -> {:halt, valid}
end
end)
pair, self -> pair |> Enum.map(&List.wrap/1) |> self.(self)
end
System.argv()
|> List.first()
|> File.read!()
|> String.split("\n", trim: true)
|> Enum.map(& &1 |> Code.eval_string() |> elem(0))
|> Enum.concat([[[2]], [[6]]])
|> Enum.sort(fn a, b -> test_pair.([a, b], test_pair) == true end)
|> Enum.with_index()
|> Enum.flat_map(fn
{divider, idx} when divider in [[[2]], [[6]]] -> [idx + 1]
_ -> []
end)
|> Enum.product()
|> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment