[Question]
  [
You will be given as input a non-empty list of positive integers. For example:
```
[1,2,2,2,1]
```
You want to produce a ragged list as output which has this as its "depth map". This list should have the same elements in the same order but each element `n` should be at the depth equal to its value.
```
[1,[2,2,2],1]
```
This is a list where the `1`s are at the first level, the `2`s are nested in there, the threes would be nested in that etc.
There are multiple outputs that fit this description:
```
[1,[2],[2],[2],1]
[1,[],[2,[],2,2],1]
[1,[2,2,2],1,[[[]]]]
```
We want the simplest one, that is the one with the fewest lists total. So in this case
```
[1,[2,2,2],1]
```
only has 2 lists whereas all the other examples had more.
## Task
Take a depth map and produce the simplest ragged list that it could represent as outlined above.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as scored in bytes.
## Test cases
```
[1] -> [1]
[2] -> [[2]]
[3] -> [[[3]]]
[10] -> [[[[[[[[[[10]]]]]]]]]]
[1,2] -> [1,[2]]
[2,2] -> [[2,2]]
[2,1,2] -> [[2],1,[2]]
[1,2,3,2] -> [1,[2,[3],2]] 
[1,2,3,3,3,2,1] -> [1,[2,[3,3,3],2],1]
[1,2,1,2,1,3,3,1] -> [1,[2],1,[2],1,[[3,3]],1]
```
  
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 21 bytes
Input are comma-separated integers, output is in the same format as the test cases.
```
\d+
*[$&$&*]
+`],\[
,
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyZFm0srWkVNRU0rlks7IVYnJppL5/9/Qx0jMDTkMuQy4jLmMjTgAgpxGYExiAVSYAynQRCsWAcsC8QgEUMA "Retina ‚Äì Try It Online")
Wraps each number on its own, then repeatedly replaces `],[` with `,`.
[Answer]
# JavaScript (ES6), ~~¬†80 79¬†~~ 74 bytes
*Saved 5 bytes thanks to @tsh*
This builds a weird and dirty string internally but eventually returns a clean ragged list.
```
a=>eval('_='+[...a,'_'].map(g=v=>d^v?d++<v?"["+g(v):"],"+g(v,d-=2):v,d=0))
```
[Try it online!](https://tio.run/##bY@7boMwFIb3PIXFgi1OnEC2tCZTlg7t0BG5kcWtVARHEFnq01MfQyBFHMsX/d9/Lv5RRnVpW93u20ZneV@IXok4N6qm/kX4QcI5V@BffMmv6kZLYUScfZlTFgSv5uQlXlBSw46eBPeCbCsidrS32DPWvyQbQpJQAvkXux2KiKI1ZFUHD6vQygMO9ws@4DEsncK5YdHLDQGPXtEaduqIF/njnDBXsAY4PJseDQA/Yk1kduGyJdH75EIZnRBOBYeNJJTzxDCdmCRdgtzwQrdnlX5TRURMUt10us55rUv69vnxzrt7WzVlVfzSgipmo/8D "JavaScript (Node.js) ‚Äì Try It Online")
### How?
Starting with \$d=0\$, for each entry \$v\$ in the original array followed by an extra `"_"`:
* if the current depth \$d\$ is less than \$v\$: we append the string `"["` repeated \$v-d\$ times before \$v\$ and update \$d\$ to \$v\$
* if \$d\$ is greater than \$v\$: we append the string `"],"` repeated \$d-v\$ times before \$v\$ and update \$d\$ to \$v\$. (NB: The trailing `"_"` triggers this case and closes all pending brackets.)
* if \$d=v\$: we just leave \$v\$ unchanged
We then prepend `"_="`, which implicitly joins everything with commas, and we evaluate the resulting string.
For instance, `[1,2,3,3,3,2,1]` is turned into:
```
"_=[1,[2,[3,3,3,],2,],1,],_"
```
which is evaluated to:
```
[1,[2,[3,3,3],2],1]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
f=lambda x,l=0:x and"],"*(l-x[0])+"["*(x[0]-l)+"%s,"%x+f(x[1:],x[0])or"]"*l
```
[Try it online!](https://tio.run/##VU3NisMgEL77FCIUtJ2E2twC6YsED5YkrGBUVJb06bNOY3e7iM73O4Zn/vKu2/dlsHp9TJpuYIdrv1HtJqaAnblttvGqxIWNhSBsbCGnBOy0XZaiyF7BK@IjU@xsd7MGHzNNz0TI4iO11DhkbcqTcW2c9WSNmxMXPaEG/LDqwOdvbcG2KViTOWvuTAhCQzQucwNo8oUbIcCLfZSKNndaBhlvByyzkK6SApBKqK6Ew7/BbxyqIP8kBe9cEaH7LEPZiA369vCU8r8EipgCWVccF/WPYP0FX6wojP8A "Python 3 ‚Äì Try It Online")
Python's `%` formatter coming in clutch.
Output is a list in string format that can be evaluated by Python to the correct answer.
Simple recursive function that walks down the input list. `l` just stores the value of the last element.
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 71 bytes
```
lambda x,i=0:",".join((j-i)*"["+(i-(i:=j))*"],"+str(j)for j in x)+i*"]"
```
[Try it online!](https://tio.run/##VY3RboQgEEXf/QrC01BHU9eXxsT9EesDjZqOQSBANrtfb5nottsQmLn33Bn8I3072374sC/952709jVpcUfq3zuJsl4dWYC1IvUmB1kCVUBdv6osR5RlTAFWtbggVkFW3FVJGcidNu9CEvERi4KpYZpVHdNEtg6zngzZOYLqCkHo@k17mG/aoKmjN5RAVlepVCF8IJuAkCEsQEqhU/vQjKK6ilyK4XK0uWbRniI3LBs8aYMHv@BvHE@j@bNGfOayie3rMOaNPCGejE8e/pdgk1PYnCuOy/5L8PyFXx4ZOf4D "Python 3.8 (pre-release) ‚Äì Try It Online")
Using the walrus operator removes the need for recursion, and the trailing comma can be added by `str.join`. Suggested by @loopywalt.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 28 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{‚ü®0‚ü©:0;1+ùïä¬®{‚äê+`¬ª‚ä∏‚à®¬¨√óùï©}‚ä∏‚äîùï©-1}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KfqDDin6k6MDsxK/CdlYrCqHviipArYMK74oq44oiowqzDl/Cdlal94oq44oqU8J2VqS0xfQoKPuKLiOKfnEbCqCDin6gK4ouIMQrii4gyCuKLiDMK4ouIMTAKMeKAvzIKMuKAvzIKMuKAvzHigL8yCjHigL8y4oC/M+KAvzIKMeKAvzLigL8z4oC/M+KAvzPigL8y4oC/MQox4oC/MuKAvzHigL8y4oC/MeKAvzPigL8z4oC/MQrin6kK)
A single recursive function that builds the output as a nested list.
`‚ü®0‚ü©:0` Base case: If the argument is a list containing a single 0, return 0 as a scalar value.
`ùï©-1` Decrement each value.  
`{‚äê+`¬ª‚ä∏‚à®¬¨√óùï©}‚ä∏‚äî` Group adjacent positive integers, and put each 0 in its own group.  
`ùïä¬®` recursively call the function on each group.  
`1+` Add 1 to each number.
[Answer]
# [J](http://jsoftware.com/), 63 59 37 bytes
```
<:<@([:>:L:0$:^:(0<{.));.1~1,2~:/\=&1
```
[Try it online!](https://tio.run/##XY3BCsIwEETv@YpBpE2grklzW5NSFDwVD14VEaRFvPgBQn89pohNKMPCzgxv9xVWVA7wjBIVNDjOhnA4d8fg2LXywg13rNd8Y6ndh5TakRlNVY@8vfrCBCVOe8LgyTEQgUSou2xYtSR10ZPCAhT94/nGAIM6yuZ27qwQc/5f6lQmZC7zNcunq3ZpJ2XPzA@JMxUmfAE "J ‚Äì Try It Online")
-22 thanks to approach suggested by ovs! It's similar or the same as his BQN answer's.
## [J](http://jsoftware.com/), original approach 63 59 bytes
```
g=.((,$:/@,&.>/@]^:[~[:(1=*+.1<<.)/,&L.){.),}.@]
[:g/<^:]"+
```
[Try it online!](https://tio.run/##y/r/P91WT0NDR8VK30FHTc9O3yE2ziq6LtpKw9BWS1vP0MZGT1NfR81HT7NaT1OnVs8hlivNVi/aKl3fJs4qVkn7f2pyRr5CmoKhghEQGoMhiGXIxQWTgTGMYAxjLoQmuCQyE0ncEGwqGhdiiSGyIASDJAz/AwA "J ‚Äì Try It Online")
This is *ridiculous*. Someone please find a better approach that still uses boxes and let me know what it is...
The basic approach is:
* Individually wrap each element to its depth.
* Recursively meld together neighboring elements using a fold.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
‚âî‚Å∞Œ∑Ôº¶Ôº°¬´Ôº¶‚ÅªŒ∑Œπ]‚ÜíÔº¶‚ÅªŒπŒ∑[Ôº©Œπ‚âîŒπŒ∑¬ªÔº¶Œ∑]ÔºµÔº¢,
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEchQ9OaKy2/SEHDM6@gtERDU1OhmosTLOCbmVdarJGho5AJFAwoyswr0VCKVQIq5/TNL0vVsArKTM8oAXGRVGeCDISrjgarhnCcE4tLNIAmAQWglmdCLK@FWJ@BakdwaolTYnJ2elF@aV6KhpIOUOz//@hoQx0jHQg2BkLD2Nj/umU5AA "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
‚âî‚Å∞Œ∑
```
Start with a depth of 0.
```
Ôº¶Ôº°¬´
```
Loop through the depths.
```
Ôº¶‚ÅªŒ∑Œπ]
```
Add `]`s as necessary to reduce the depth to the current depth.
```
‚Üí
```
Leave a space between values.
```
Ôº¶‚ÅªŒπŒ∑[
```
Add `]`s as necessary to increase the depth to the current depth.
```
Ôº©Œπ
```
Output the current depth.
```
‚âîŒπŒ∑
```
Save the current depth as the previous depth.
```
¬ªÔº¶Œ∑]
```
Output the necessary closing `]`s at the end.
```
ÔºµÔº¢,
```
Replace all the interior spaces with commas. (The leading space simply gets skipped, since it wasn't actually printed.)
Actually creating the list in memory takes 44 bytes:
```
‚äûœÖ‚ü¶‚üßÔº¶Ôº°¬´Ôº∑‚ÄπÔº¨œÖŒπ¬´‚âî‚ü¶‚üßŒ∏‚äû¬ßœÖ¬±¬πŒ∏‚äûœÖŒ∏¬ª‚âî‚Ä¶œÖŒπœÖ‚äû¬ßœÖ¬±¬πŒπ¬ª‚≠Ü¬π¬ßœÖ‚Å∞
```
[Try it online!](https://tio.run/##fYw9C8IwEIbn9FdkvIMIVsdOpZOgUnAsHUqNSSCktUn8QPrbY2oVdJHj7jje555WNkPbNTqE0lsJntGqxiw5dQOFjem9A0T6SMhVKs0pbLm1cRjhIouMqjklubVKGKhqRs/xnZCXLXcbc@S3ybrnonEcUsQfwr@vMfkoinureSG7fspUpP2U/9OpCIxJOSjj4ODiErumh5TRL36JiFkIVZWyFZt7HSut67C46Cc "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
‚äûœÖ‚ü¶‚üß
```
Start with an empty list.
```
Ôº¶Ôº°¬´
```
Loop over the depths.
```
Ôº∑‚ÄπÔº¨œÖŒπ¬´
```
While the next depth is larger than the current depth, ...
```
‚âî‚ü¶‚üßŒ∏‚äû¬ßœÖ¬±¬πŒ∏‚äûœÖŒ∏
```
... nest a list.
```
¬ª‚âî‚Ä¶œÖŒπœÖ
```
Truncate the current depth to the next depth.
```
‚äû¬ßœÖ¬±¬πŒπ
```
Append the next depth value to its list.
```
¬ª‚≠Ü¬π¬ßœÖ‚Å∞
```
Pretty-print the final list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒµDG‚Ä¶[√ø]]',√Ω‚Ä¶[√ø]‚Ä¶],[',:
```
Input as list, output as string. It kinda feels like cheating, but I saw multiple other answers do the same.. And I guess we could technically add an eval.
[Try it online](https://tio.run/##yy9OTMpM/f//3FYX90cNy6IP74@NVdc5vBfKBlKxOtHqOlb//0cb6hjpQLAxEBrGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1td3B81LIs@vD@2tlZd5/BeKAdIxepEq@tY/df5Hx1tGKujEG0EIoxBhKEBmNQBixjBKCgfSOkYIzNBECgLE4BgkKBhbCwA).
A port of [*@xigoi*'s Jelly answer](https://codegolf.stackexchange.com/a/241653/52210) is 22 bytes as well:
```
0.√∏¬•√ù‚Ç¨{.¬±‚Ä¶,[]s√®JI.ŒπJ¬¶¬®
```
[Try it online](https://tio.run/##yy9OTMpM/f/fQO/wjkNLD8991LSmWu/QxkcNy3SiY4sPr/Dy1Du30@vQskMr/v@PNtQx0oFgYyA0jAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A73DOw4tPTz3UdOaar1DGx81LNOJji0@vMKrUu/cTq9Dyw6t@K/zPzraMFZHIdoIRBiDCEMDMKkDFjGCUVA@kNIxRmaCIFAWJgDBIEHD2FgA).
**Explanation:**
```
Œµ         # Map over each integer in the (implicit) input-list:
 D        #  Duplicate the integer
  G       #  Pop and loop the integer-1 amount of times:
   ‚Ä¶[√ø]   #   Wrap it in block-quotes as string
]         # Close both the inner loop and outer map
 ',√Ω     '# Join the strings with "," delimiter
    ‚Ä¶[√ø]  # Wrap the entire string into block-quotes as well
‚Ä¶],[',:  '# Replace all "],[" with ","
          # (after which the resulting string is output implicitly)
0.√∏       # Surround the (implicit) input-list with leading/trailing 0
   ¬•      # Get the deltas/forward-differences of this list
    √ù     # Transform each value to a list in the range [0,value]
     ‚Ç¨{   # Sort each inner list
       .¬± # Convert each to its sign (-1 if <0; 0 if 0; 1 if >0)
‚Ä¶,[]s√®    # Modular 0-based index each into ",[]"
      J   # Join each inner list of characters to a string
I.Œπ       # Interleave it with the input-list
   J      # Join it together again
    ¬¶¬®    # Remove the leading/trailing ","
          # (after which the resulting string is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
√ò0jIr0·π¢‚Ç¨·π†·ªã‚Äú[],‚Äù≈º‚Å∏F·∏ä·πñ
```
[Try it online!](https://tio.run/##y0rNyan8///wDIMszyKDhzsXPWpa83Dngoe7ux81zImO1XnUMPfonkeNO9we7uh6uHPa////ow11jHQg2BgIDXVMYgE "Jelly ‚Äì Try It Online")
A string-based approach.
## Explanation
```
√ò0jIr0·π¢‚Ç¨·π†·ªã‚Äú[],‚Äù≈º‚Å∏F·∏ä·πñ
√ò0j                  Surround with zeroes
   I                 Increments
    r0               Raplace each element x with the range x..0
      ·π¢‚Ç¨             Sort each range
        ·π†            Replace each number with its sign
         ·ªã‚Äú[],‚Äù      Perform the mapping: 1 -> "[", -1 -> "]", 0 -> ","
               ≈º‚Å∏    Zip with the original input
                 F   Flatten
                  ·∏ä·πñ Remove the leading and trailing commas
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~59~~ ~~41~~ 40 bytes
```
f@{a:0..}=a
f@l_:=f/@SplitBy[l-1,Sign]+1
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NoTrRykBPr9Y2kSvNISfeyjZN3yG4ICezxKkyOkfXUCc4Mz0vVtvwf0BRZl5JtLKuXZqDcqxaXXByYl5dNVe1Ya0OV7URiDAGEYYGYFIHLGIEo6B8IKVjjMwEQaAsTACCQYKGtVy1/wE "Wolfram Language (Mathematica) ‚Äì Try It Online")
[Answer]
# Python3, 112 bytes:
```
from itertools import*
f=lambda x,n=1:[j for a,b in groupby(x,key=lambda x:x==n)for j in(b if a else[f(b,n+1)])]
```
[Try it online!](https://tio.run/##VZHRboQgEEWf61dMfBHa6aasL40J/RFrGky1dYtAxDb69XYm4naLQZjLuTNhCOv86V35HKZt6yc/wjB30@y9jTCMwU/zfdZra8b23cCCTquqvkDvJzDYwuDgY/LfoV3Fgl/degWrRWsnGbsQJIjswUBnY1f3okX3oGQjm22vACbOWQSd53mtGnh8AVqy@rxvaaWgTAFtOFRPR5wGCddBx5jMCnf7Ga/ZMAnqT2rw4EjE8taMVJAdcJzxR@Z/BItMoUop9sn6DZiq8J8tDeN05Yy7NHAr4ykGO8yieHWFrLI77rCG0QRBDTpZfhhj37ofYxGGg@X0hZREx0gPB70wUut2@wU)
[Answer]
# [Perl 5](https://www.perl.org/) -p, 86 bytes
```
s/\d+,?|$/"]"x($d=$l-$&).","."["x-$d.($l=$&)/ge;s/(\[),|,(])|,(,)/$1$2$3/g;s/^.|..$//g
```
[Try it online!](https://tio.run/##TYlBCsIwEEX3HmMYJMFJxqS4kuJB0rhqCUKwpXXRRc9unNAuZHiP@f9Pw5xvpSzc9Rd6bMgQYVXYt5gNnrUFAgsBVoO9VZhb6TgN94VVFzRtpKIWkWZ06LHhJNPTbtYicyoluHgKXmgEd62iGv3hPYmp@fvqyXbkndq5@B2nz2t8L8VM@Qc "Perl 5 ‚Äì Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
f=->a,d=1{a.chunk{_1>d}.flat_map{_1 ? [f[_2,d+1]]:_2}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVDbasMwDKWv_gqRp7VTQpXCGIVmH-IZ4zU1DUuz0CWDUfIle-nD9lHt10zCTi8ytnSOzpFBP7_7_u37ePzrO58-n578Ki0clis6uGy97Zv3g6WiHDJfu87uXMsQXkB7bXMsH8mYpc2HIbjPk5n_2EMFVQOJJgNpAZyUzkPJmcEiAi4E0nzEMZi4BLcxmgmDPcfLNIwEXSmDo45JXNyakT8UB4w9OWy-UwgpKqQ4Ilzhb4TxF3nFYkSeZJ9tXXUPyWuTTDPZ1ObL1WAp8HpuBtWC15VRm6ZUKqxsXPw_)
-16 from AZTECCO.
[Answer]
# [R](https://www.r-project.org/), 84 bytes
Or **[R](https://www.r-project.org/)>=4.1, 77 bytes** by replacing the word `function` with a `\`.
```
f=function(v,s=1)"if"(all(v<s),v,{y[]=cumsum(c(T,y<-v==s)|y);Map(f,split(v,y),s+1)})
```
[Try it online!](https://tio.run/?fbclid=IwAR1LuUT8zKk_OaDLtmpg4YS-vE-DQlpYLwWbKDUBVzGBeBuScasDenpyqkI##jZBNCoMwEIX3PYW4ytARHF1qeoPuutMsRAgImkqjAWl7dptQKfhDdUJmk/e9eZPHOEoue1V21V0xg5oT@JX0WVHXzKQa0OBzyAQv@0b3DSvZDYc0MJxreA2QXIuWSdRtXXWWHgD1meANo7RKAkjKomO@F1y8jESugmXlKlc@nJw6mqmzSOzo47k@i8UeQeECmYpC8asdB5ynJNzPGeFyMzzA0IoSeGSa5TDeSIn2f9xc7wjujo2wZeLenBHSgSDf65i117SO685V/HUcPw "R ‚Äì Try It Online")
Outputs the actual list structure.
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal/releases/tag/v2.4.1) `D`, 20 bytes
```
ƒ†∆õh‚Äπ(w);S`‚ü©|‚ü®`\|√∏V·∏¢·π™
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%C4%A0%C6%9Bh%E2%80%B9%28w%29%3BS%60%E2%9F%A9%7C%E2%9F%A8%60%5C%7C%C3%B8V%E1%B8%A2%E1%B9%AA&inputs=%5B1%2C2%2C3%2C5%2C2%2C3%2C1%2C2%2C2%2C1%2C1%2C1%2C3%2C2%2C1%2C3%2C2%5D&header=&footer=)
A big mess. We're using v2.4.1 because v2.6+ prettyprint lists with spacing.
```
ƒ†                    # Group consecutive identical elements
 ∆õ     ;             # Map...
  h‚Äπ( )              # item-1 times...
     w               # wrap in a list
        S            # Stringify
         `‚ü©|‚ü®`\|√∏V   # Replace `‚ü©|‚ü®` with `|`
                  ·∏¢·π™ # Remove the first and last characters.
```
]