Today, I’m pretty much playing Kerbal Space Program and planning some
orbital trajectories. As shown in the problem itself, a tree is the perfect
way to represent the orbits, so building one shouldn’t be too hard.
defp build_tree([], node), do: node
defp build_tree(list, p) do
connections = Enum.filter(list, &String.starts_with?(&1, p))
list = Enum.filter(list, fn x -> x not in connections end)
c =
connections
|> Enum.map(fn x -> x |> String.split(")") |> List.last() end)
|> Enum.map(fn x -> build_tree(list, x) end)
%{p: p, children: c}
end
list
here is the list of connections I’m given, in the form of AAA)BBB
, and
p
is the object that I am finding satellites of. First, I find all the
connections by filtering the list for lines that start with the payload, and
then for each child I build a tree with that child as the root. Once all the
lines are filtered out, the tree is complete.