You must write a program or function that sorts a nested list. Here are the rules for sorting a nested list:
Let's take this list as an example:
((5, 2), 2, 7, (2, 1, (3, 4)), 9)
Each element in this list has a "priority". An element counts as a number or a sublist. First, get the priority of each element at the same depth. If an element is just a number, its priority is the same as the number itself. If an element is a sublist, its priority is the sum of all the numbers in it, not including any sub-sublists.
So, the priorities of all the elements of depth 1 are:
( 7 ) 2 7 ( 3 ) 9
((5, 2), 2, 7, (2, 1, (3, 4)), 9)
Sort each element by priority. If there is a tie, you must keep the same order as the original list.
2 ( 3 ) ( 7 ) 7 9
(2, (2, 1, (3, 4)), (5, 2), 7, 9)
Repeat for every sublist. So on this sublist
(2, 1, (3, 4))
Our priorities look like:
2 1 ( 7 )
(2, 1, (3, 4))
So sorted, it looks like:
(1, 2, (3, 4))
(3, 4) is already sorted, so we're done. Repeat for (5, 2) which results in (2, 5) and we're done! Our final list is:
(2, (1, 2, (3, 4)), (2, 5), 7, 9)
Rules:
Highly doubtful, but just in case Mathematica has something for this, no nested list sorting builtins are allowed. Regular sorting functions are allowed.
I/O can be in any reasonable format.
Every sublist will contain at least one number or list. Also, sublists can be nested several levels deep. For example, in
(1, 2, (((3))))the(((3)))has a priority of 0, since it has only sublists in it.Invalid lists (unmatched parentheses, non-numbers, wrong bracket types, negative numbers, etc.) result in undefined behavior.
Test I/O:
(1, 2, 3) ---> (1, 2, 3)
(1, 2, 6, 3, 9, 8) ---> (1, 2, 3, 6, 8, 9)
(4, 3, (2), (1)) ---> ((1), (2), 3, 4)
(4, 3, (2), ((1))) ---> (((1)), (2), 3, 4)
(5, (1, 2, (9, 8))) ---> ((1, 2, (8, 9)), 5)
(3, (1, 2), (2, 1)) ---> (3, (1, 2), (1, 2))
(3, (1, 2, (99)), (2, 1, (34))) ---> (3, (1, 2, (99)), (1, 2, (34)))
(7, 2, (1, (9, 12)), (4, 3, 2, (1, 2))) ---> ((1, (9, 12)), 2, 7, (2, 3, (1, 2), 4))
Shortest answer in bytes wins.