Here is the way this data structure / algorithm should work (each line is 1 step):
1. []
2. [1]
3. [1, 2]
4. [1, 2, 3]
5. [[1, 2, 3], [4]]
6. [[1, 2, 3], [4, 5]]
7. [[1, 2, 3], [4, 5, 6]]
8. [[1, 2, 3], [4, 5, 6], [7]]
9. [[1, 2, 3], [4, 5, 6], [7, 8]]
10. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
11. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10]]]
12. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11]]]
13. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12]]]
14. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13]]]
15. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14]]]
16. [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15]]]...
- You'll notice that at each level, the numbers are all at the same level in the tree.
- And at every level each array can only have 3 items before things change.
- You'll notice on the transition from step 4 to 5, it has to nest the arrays one level further down.
- The transition from step 10 to 11 also nests again further.
- The pattern will continue to nest as each level gets 3 items.
- As seen in step 11, when you add the next item, it is added at the proper depth of the tree.
- All numbers (arbitrary "items" really) are at the same depth level in the tree.
The tricky part is, when you reach the "end" of a particular run, how do you traverse the arrays and insert the new arrays in the appropriate spots? What is the general algorithm to implement this concisely? Ideally not a functional algorithm but a regular procedural/imperative one. My attempt is here. Essentially this is pushing an item in a "tree array", keeping every item/object/number at the same depth level at the leaves of the tree.
I am struggling when it comes to how to traverse up and down the tree to add a new item when the nesting level changes.
Note: I used numbers to demonstrate the order they were added. But they shouldn't be used in the final algorithm, it should take generic objects.