list manipulation - How to invert MapIndexed on a ragged structure? How to construct a tree from rules?
I have an arbitrary ragged nested list-of-lists (a tree) like
A = {{a, b}, {c, d}, {{{e, f, g, h, i}, {j, k, l}}, m}, n};
Its structure is given by the rules
B = Flatten[MapIndexed[#2 -> #1 &, A, {-1}]]
{{1, 1} -> a, {1, 2} -> b, {2, 1} -> c, {2, 2} -> d, {3, 1, 1, 1} -> e, {3, 1, 1, 2} -> f, {3, 1, 1, 3} -> g, {3, 1, 1, 4} -> h, {3, 1, 1, 5} -> i, {3, 1, 2, 1} -> j, {3, 1, 2, 2} -> k, {3, 1, 2, 3} -> l, {3, 2} -> m, {4} -> n}
How can I invert this operation? How can I construct A
solely from the information given in B
?
Thanks to all for contributing so far!
For robustness and versatility it would be nice for a solution to accept incomplete input like B = {{2} -> 1}
and still generate {0,1}
, not just {1}
.
Also, there are some very deep trees to be constructed, like B = {ConstantArray[2, 100] -> 1}
. A certain parsimony is required to be able to construct such trees within reasonable time.
Answer
Here's an inefficient but reasonably simple way:
groupMe[rules_] :=
If[Head[rules[[1]]] === Rule,
Values@GroupBy[
rules,
(#[[1, 1]] &) ->
(If[Length[#[[1]]] === 1, #[[2]], #[[1, 2 ;;]] -> #[[2]]] &),
groupMe
],
rules[[1]]
]
groupMe[B]
{{a, b}, {c, d}, {{{e, f, g, h, i}, {j, k, l}}, m}, n}
Comments
Post a Comment