[Question]
  [
In this challenge you will receive a list of non-negative integers. Each one represents a mushroom with a cap of that radius centered at that location. So a `0` means that it occupies no space at all, a `1` means that its cap only occupies space above it, a `2` means it occupies space above it and one unit to the left and right etc. More generally for size \$n\$ a total of \$2n-1\$ spaces are occupied, with the exception of 0 which occupies 0 spaces (i.e. there's no mushroom at all).
Mushroom caps can't occupy the same space as each other but mushrooms can have different heights to avoid collisions.
So for example here we have two mushrooms. They can't be in the same row since they would occupy the same space but if they are given different heights there is no issue:
```
          =-=-=
            |
  =-=-=-=-= |
      |     |
[ 0,0,3,0,0,2,0 ]
```
(Stems are drawn with `|` for clarity, but can't collide)
Your task is to take as input a list of mushrooms and output a list of heights, one for each input mushroom, such that there is no collisions between mushrooms and they occupy the fewest total rows.
For example here we have a worked case:
```
=-=-= =-=-=-=-=-=-= =
  |         |       |
  | =-=-=   |   =-=-=
  |   |     |     | |
  =-=-=     =-=-=-=-=
  | | |     |   | | |
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 2,0,1,0,0,2,0,0,1,2 ] -> Heights
```
(Stems are drawn with `|`, and extra spacer rows are added between layers for clarity)
For any input there are a wide variety of valid answers, you are allowed to output any 1 of them or all of them. You may also consistently use 1-indexed heights instead of 0-indexed heights if you wish.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal will be to minimize the size of your source code as measured in bytes.
## Selected examples
Here are some selected examples with possible solutions:
This one defeats a certain greedy algorithm:
```
  =-=-= =
    |   |
=-=-= =-=-=-=-=
  | |   | |
[ 2,2,0,1,3 ] <- Width
[ 0,1,0,1,0 ] -> Height
```
This one requires everything to be on its own row:
```
    =-=-=-=-=-=-=
          |
  =-=-=-=-=-=-=
        | |
    =-=-= |
      | | |
    = | | |
    | | | |
=-=-= | | |
  | | | | |
[ 2,1,2,4,4 ] <- Width
[ 0,1,2,3,4 ] -> Height
```
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ
```
A monadic Link that accepts a list of non-negative integers and yields a list of positive integers specifying the levels (i.e. 1-indexed heights).
**[Try it online!](https://tio.run/##AT8AwP9qZWxsef//4bik4oCZUl8iKyJKSuG5l0w74rGuIuG6jlHGkcmXxofGsuG5gMOe4bii////WzIsMiwwLDEsM10 "Jelly – Try It Online")**
### How?
Inefficient brute-force...
```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ - Link: cap sizes
Ḥ                       - double (the cap sizes)
 ’                      - decrement (these)
  R                     - range (those) - i.e. [[1..2*n-1] for each cap size, n]
    "                   - zip (those) and (cap sizes) applying:
   _                    -   subtraction - i.e. make these offsets like [...,-1,0,1,...]
       J                - range of length (cap sizes) -> [1..length(cap sizes)]
      "                 - zip (the offsets) with (the range) applying:
     +                  -   addition -> covered indices of each mushroom, "covers"
                   Ʋ    - last four links as a monad - f(covers):
        J               -   range of length -> same as [1..length(cap sizes)]
          L             -   length -> same as length(cap sizes)
         ṗ              -   (range) Cartesian power (length)
                              -> all lists of the same length as cap sizes
                                 using alphabet [1..length(cap sixes)] 
                  Ƈ     -   filter keep those (arrangements) for which:
                 ɗ      -     last three links as a dyad - f(arrangement, covers):
             "          -       zip with:
            Ɱ           -         map with:
           ;            -           concatenate -> coordinates
              Ẏ         -       tighten
                Ƒ       -       is invariant under?:
               Q        -         deduplicate
                     Þ  - sort by:
                    Ṁ   -   maximum value
                      Ḣ - head
```
[Answer]
# JavaScript (ES7), ~~146 131~~ 129 bytes
*Saved 15 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
Returns a single solution as a space-separated string.
```
f=(a,...B)=>(F=(x,b,o,w=a[x])=>1/w&&b.every((v,i,[...c])=>v&(c[i]|=m=4**w/2-1<<x>>w,m)||F(x+1,c,O=[o]+i+' ')))(0,B)?f(a,...B,0):O
```
[Try it online!](https://tio.run/##bY1BCsIwFET3nsJV/b/9pkntSkwFF249QMiixlYqakQlidC7xxRcyjAwzBuYS@val3kOj/fybk9djL2ElhhjO5QN7CUEOpIlL1sVdKpE6bPsyDrXPT8AjgZSaWwm5DIwatCjvMk6z31ZLcVmE5rG0w3HcQ@hEGToIJXVxVAs5gtEBE473Pa/S@K4PkRj7y977djVnqEHVdEknlQnr1IWGnH2Z8VJ0OovE4nWVCcWvw "JavaScript (Node.js) – Try It Online")
### How?
We generate one bitmask per mushroom cap and attempt to dispatch them among \$N\$ rows without any collision, trying all possible distributions. We start with \$N=0\$ (which is obviously unlikely to work) and increment \$N\$ until a solution is found.
The pattern for a mushroom cap of width \$w\$ and position \$x\$ is computed with:
$$\left\lceil\frac{4^w}{2}-1\right\rceil$$
which generates \$max(0,2w-1)\$ consecutive \$1\$'s.
The final bitmask is obtained by shifting this pattern by \$x\$ positions to the left and \$w\$ positions to the right.
[Answer]
# Python3, 248 bytes:
```
from itertools import*
E=enumerate
C=lambda x,c,I:[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]
f=lambda x:min([i for i in product(*[range(j+1)for j in x])if all(all(i[t]!=m for t in C(x,x[n],n))for n,m in E(i))],key=max)
```
[Try it online!](https://tio.run/##bY7PboMwDMbvPIV3S8BIBHqYqqaXqgeeAXHIIKzuSIKyVEqfnjXs32GTZR@@n/19Xu7h4mzzvPh1nbwzQEH74Nz8DmQW50OenaW2N6O9Cjo7yVmZl1FBxAHbfUcwOQ@ECsjCmUVOE6icMVWKgo6yLYdCgLIj0KHlzjMqVSEOsi2G8ks/tpz32fTjuzdk2bdvcl28G29DYHnnlX3V7FoInuA1wdhvifPMUlMX@idpttuQ8IlFjJ3t0fLtxqL5fJQeofim79KoyNfFkw1sYh1UWGGDadZYQc959stqTJXYbtuqUfyzUaHA5o8uHmSHu6SvHw)
Heights are 0-indexed.
A longer, no-import solution:
```
E=enumerate
def F(x):r={j:a for a,b in min(f(x),key=len).items()for j in b};return[r[i]*(a>0)for i,a in E(x)]
C=lambda x,c,I:{*[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]+[I]}
def f(x,c=0,d={0:[]}):
 if len(x)==c:yield d;return
 for i in d:
  if not C(x,x[c],c)&set(d[i]):yield from f(x,c+1,{**d,i:d[i]+[c]})
 yield from f(x,c+1,{**d,max(d)+1:[c]})
```
[Try it online!](https://tio.run/##dY/PisIwEIfvfYo5LUkzXRr1sGSNF1HoM5QeYpOycW0qsUKl9Nm7iQoL@4dADvN9M7@Z863/6Nzy7ezneSeNu7bGq94k2jSwJwMVXo5HoaDpPCg8gHXQWkeagPDT3OTJOPpqe9NeCI3OMRqH6d2b/upd6UtbpURt8ju0qCLeheYq2cqTag9awYA1FmJMSws/JNuASglRGWd2I4usZhyU02DXBe08sZlifC0LVmfP@qagtGJlUU33A8KWWMsctRxzUVYTFQmEmWHnMFzKWtysOWnQz22TR35M18GMqut62IYpQ1lXWNOXi@mJDjfRZ2vju/YRwziOaarRishZ8CeawH9WqwaiKePi7s1nb11P9qSEHHNcYvwXmENFafLNFhhfZKu7tUD@h5Ejx@WvOg9khatYn78A)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~115~~ ~~112~~ 102 bytes
```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι«≔⟦⟧ζＦη«≔§κ¹εＦΦＬε¬＆§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Ｌε⊞ει⊞ζκ»≔ζη»≔ＥηＬ⊟ιζＩ§η⌕ζ⌊ζ
```
[Try it online!](https://tio.run/##XVBBbsIwEDzDK3xcS64EKTdOtBQJqVQ5cLN8iMiWWDgO2A60qXh7uk5KQJVlK5OdndnZXZG5XZWZtl14r/cWpJRKMKkUvQWfjz8rx2CTHeEk2NqGpT7rHGGrS/Rwx0vcOSzRBswhrS7oYCaY5lywhG7/JxHswB8R1TlnP@PRzZosG7IcdZ5FV7rVFmFtc/yCg2BT0sBI63krbQLpvaPdhwKQih9VgBcdLtrjwuZDKwpm@M01rX0BDQVNTe0f1SdEkUbRG0NTzxadzdw3vJ3qzHiwvUrXVkY1wUrOVTdPJ/pPa5jrzsDYNqAmroXQddhD02/@Ov7DcZBiUEqrI8QM/a5Sp22A18yHwZioK025SWajrS7rEpqYmc/bVspExDOhM6P7TN9Tpdqns/kF "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟦⟦⟧⟦⟧⟧⟧η
```
Start with no mushrooms placed.
```
ＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι«
```
For each mushroom, calculate a bitmask corresponding to the space that it occupies. Edit: Saved 3 bytes by using my golf to @Arnauld's formula.
```
≔⟦⟧ζ
```
Start collecting placements that include this mushroom.
```
Ｆη«
```
Loop over the existing placements.
```
≔§κ¹ε
```
Get the bitmasks for the heights as this gets used a lot.
```
ＦΦＬε¬＆§ελι
```
Find whether this mushroom can be placed at any existing height.
```
⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧
```
Generate a placement for putting this mushroom at that height.
```
⊞§κ⁰Ｌε⊞ει⊞ζκ
```
Generate a placement for putting this mushroom at a new height.
```
»≔ζη
```
Save the new placements as the current placements.
```
≔ＥηＬ⊟ιζ
```
Get the heights of all of the placements.
```
Ｉ§η⌕ζ⌊ζ
```
Output one of the placements with minimal height.
Previous less inefficient 112-byte version:
```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι¿ι«≔⟦⟧ζＦη«≔§κ¹εＦΦＬε¬＆§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Ｌε⊞ει⊞ζκ»≔ζη»Ｆη⊞§κ⁰¦⁰≔ＥηＬ⊟ιζＩ§η⌕ζ⌊ζ
```
[Try it online!](https://tio.run/##bVHBbsIwDD3DV@ToSJkEHTdObAwJaUw9cItyqKihEWkKTQpbJ769c9q1oGmKEsXx83v2yy5Lyl2RmKZZOKcPFqSUSjCpFJ0Zn4/3Rclgk5zgLNja@qW@6BRhq3N0cI@XuCsxR@sxhbi4YgkzwTTngkW0u5dIsCN/jCjPOdN7Bpqz7/Go74CUa1IetdJZm@pzC7@2KX7CUbApUWGAdbiVNp5o39EefAZIyY/Cw4v2V@1wYdOhFAUzvBePK5dBTfPGpnKP7BOCSKPoDLNTzRZLm5Rf8HauEuPAdixtWR7YBMs5V20/LekfrqGvOwJD2RDVwR2KboMPdfcBtzEah6w34z/yCcF@i0K32SAXFycIg3aGxqW2Hl4T5wcCgq40mUNaG211XuVQB2P4vGmkjERYE1oz2s90nyrVPF3MDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Always places zero-width mushrooms at zero height instead of at all possible heights.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εD(Ÿ¦¨N+}[DN.Œ.Δε˜DÙQ}P}Zd#\}ε€ÅsIgÝ¨åN*}øO
```
Brute-force approach.
[Try it online](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPuzbaxU/v6CS9c1PObT09x@XwzMDagNqoFOWY2nNbHzWtOdxa7Jl@eO6hFYeX@mnVHt7h//9/tJEOCBoAoQkQGwPZhrEA) or [verify both test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/PbXXROLrj0LJDK/y0a6Nd/PSOTtI7N@Xc1tNzXA7PDKwNqI1KUY6pPbf1UdOaw63Fh9alH557aMXhpX5atYd3@P/X@R8dbaBjoGOsAyKNdAxidaKNdEAQxDcByxjpGMbGAgA).
**Explanation:**
Step 1: Change each value in the input to a list of indices it can reach:
```
ε            # Map over each value of the (implicit) input-list:
 D(          #  Create a negative copy
   Ÿ         #  Pop both, and push a list in the range [n,-n]
    ¦¨       #  Remove the first and last to make the range (n,-n)
             #  (or empty the list if n=0)
      N+     #  Add the current map-index as offset
}            # Close the map
```
[Try just this first step.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPu/b//2gjHRA0AEITIDYGsg1jAQ)
Step 2: Indefinitely loop up from \$N=0\$ and get all \$N\$-element combinations of the list of lists. Stop as soon as we've found a partition for which all inner indices are unique.
```
[            # Start an infinite loop:
 D           #  Duplicate the list we've created in step 1
  N          #  Push the loop-index `N`
   .Œ        #  Pop both, and get all N-sized partitions of the list
     .Δ      #  Find the first partition that's truthy for:
             #  (or -1 if none are truthy)
       ε     #   Map over each part:
        ˜    #    Flatten the list of lists of indices
         DÙQ #    Check whether all indices are unique:
         D   #     Duplicate it
          Ù  #     Uniquify this copy
           Q #     Check if both lists are still the same
       }P    #   After the map: check if all parts were truthy
      }Z     #  After the find_first: push the maximum (without popping)
             #  (which results in "-" for -1)
        d    #  If this is a non-negative integer (0 for "-", 1 otherwise)
         #   #   Stop the infinite loop, since we have a hit
         \   #  (else:) discard the -1 that's still on the stack
}            # Close the infinite loop
```
[Try just the first two steps.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPuzbaxU/v6CS9c1PObT09x@XwzMDagNqoFOWY2v//o410QNAACE2A2BjINowFAA)
Step 3: Convert this found result of parts of index-ranges to a list of heights to output:
```
ε            # Map over each part in this partition:
 €           #  Inner map over each inner index-range (-n,n):
  Ås         #   Pop and leave just the middle value
             #   (this is the offset we've added in step 1,
             #    or [] if the list was empty for n=0)
    IgÝ¨     #  Push a list in the range [0, input-length):
    I        #   Push the input-list
     g       #   Pop and push its length
      Ý      #   Pop and push a list in the range [0,length]
       ¨     #   Remove the last item to make the range [0,length)
        å    #  Check for each if it's in the earlier list
         N*  #  Multiply each by the 0-based map-index,
             #  which are the heights
}ø           # After the map: zip/transpose; swapping rows/columns
  O          # Sum each inner list (mapping each to its max, since each inner
             # list will only contain (at most) one non-0 height)
             # (after which this list of heights is output implicitly)
```
*Note: It outputs the first result it can find, so for the second example test case, it outputs this list of mushroom-heights:*
```
    =-=-=       =-=-=
      |           |
  =-=-=     =-=-=-=-=
    | |         | |
=-=-= =-=-=-=-=-=-= =
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 0,1,2,0,0,0,0,1,2,0 ] -> Heights
```
[Answer]
# [Python](https://www.python.org), ~~293~~ ~~264~~ ~~263~~ 262 bytes
*-1 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)*
```
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n)for a in h for b in h if not h[a]&h[b]),default=h,key=len)
def f(w):
    r=[0]*len(w);i=0
    for K in j({(i,):set(range(-x-~i,x+i))for i,x in enumerate(w)}):
        for k in K:r[k]=i
        i+=1
    return r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBLTsQwDIbFBml6iqwgpumoAyxQUU4wR6iqKmVSkj7cKqSiFY-LsJkN3AlOgzPVxIry5bf12_LXz7h4M-Dx-D35Onn4u7hsZKf66qCYyXqLnA5m0myfhnHhANuyfNHeet2XJVdxJXA7DiNX8L5CBQCDYw1HqOlVzCIzLGC1oq0ZDp6ZXBVXJq8KEAddq6nz0ohWL7LTCBFJrOavkEUbJ_O0uCGVvo9WptEmmO2DWcPfuBWQ0UDcKXzWPJmTTyvm2MKpO2Go0zj12imvyeIjeJ4s2pDaZy5vC2lJs7HcUTvtJ4fMrev4vZ6ZpElyditCpBT3dO-Id6yAaHQWPZ9hLT9v8R8)
Note: it's extremely inefficient.
A slightly more efficient (and longer) variant:
```
from itertools import*
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n) for a,b in combinations(h,2)if not h[a]&h[b]),default=h,key=len)
def f(w):
    r=[0]*len(w);i=0
    for K in j({(i,):set(range(-x+1+i,x+i))for i,x in enumerate(w) if x}):
        for k in K:r[k]=i
        i+=1
    return r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBBTsMwEBTH5hV7Am_jVm3hgIL8gj4hiiKndbDbeB25jkgFvIRLL_AneA0bKryyNDs7Ho_246s_JxvocvkcUrt4_LmZtzF4cMnEFEJ3Auf7ENM8O6hO-2avwRbekeBDhbLLXejPAnFZ1yeT-JWva6HzRtKyD73Q-HYFDSKGCAdBCC0DLRtwBLvgG0c6uUAnYeUGXQsUEthSV7e2bCqUe9PqoUvKyqM5q84QZkxBK16wyGZRlatqziy3T06tstnkvp28D-JVOIkF5xJR07MRizFf506OuUOcZAwnoaHBm6iTYQ_gAOP75PxndJzm2yKWx0o55lyu1vypSUMkiNeVfd-NoDhPCRs51Yrrge894zVUmPXRURIjXuX_m_4F)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~143~~ 142 bytes
```
f=(a,i=x=[])=>(g=y=>1/a[y.length]?x.some(i=>g(O=[...y,i])):!a.some((P,p)=>a.some((Q,q)=>y[p]==y[q]&p<q&P+Q>q-p+1&&P*Q)))([])?O:f(a,x.push(+i))
```
[Try it online!](https://tio.run/##bY3LDoIwEEX3/oUbMpVaqbIiDn6CsG66aJRHDdIiaujX4xjjjtxMMjdnJudm3ma8PKx/bnt3rea5RjDc4oRKM8yhwYC53BkVRFf1zbPVp0mM7l6BxbyBMyohROBWM5atzY9AwT39/lvJB2pBeY0Y1KAjfxyiIi7zYetjGUXFpmSMAflO56wm@yT8a2whtozNF9ePrqtE5xqoQe35NwklpTnQLsm8WrhKuOSHRSaJpjwlNn8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 28 bytes
```
d‹ɾ-:ż+:£₌żLÞẊ'¥¨£v"ÞfÞu;⁽G∵
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiZOKAucm+LTrFvCs6wqPigozFvEzDnuG6iifCpcKowqN2XCLDnmbDnnU74oG9R+KItSIsIiIsIlsyLDIsMCwxLDNdIl0=)
Port of Jelly. Outputs a list of 1-indexed heights.
[Answer]
## Clojure, ~~214~~ 227 bytes
```
(defn f([W](:H(nth(flatten(for[m(range)](f m 0 W[][1])))0)))([m i W H O](if-let[w(nth W i nil)](for[h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f m(inc i)W(conj H h)O)){:H H})))
```
[TIO](https://tio.run/##PY/BasQgEIbveYo5zrBZMN2eAqXX3DzmMHgIiVYXY0LWImXZZ08n3bYOA6Kf3/yOcbl@bnbfcbIugUPuDbYdpuzRxSFnm9AtG8@4DenDkkEHMyjo2XBjiEhJI88QoIcOtMHgztFmLodCzgKkEI9nIvFPiSD4BgUUNTATacaQ8gL6h5l@mROeoVBDhQzjSTQTeZln2uIl0rCu8QumcMshjfkd9DOYiEYI1OO4pKvE8aSJ7m0H3UNiVhWum4yKCVhofqmPUlKv0hfZy48q@F9/jKqb@mJI7vb9Gw).
Buggy code:
```
(defn f([W](:H(nth(flatten(f 0 W[][1]))0)))([i W H O](if-let[w(nth W i nil)](for[m(range)h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f(inc i)W(conj H h)O)){:H H})))
```
I thought I could move the `for[m(range)...` from the initial function call inside the recursion, but apparently it leads to a wrong output in come cases.
Less golfed:
```
(defn f
  ([widths] (first (flatten (for [max-height (range)] (f max-height 0 widths [] [])))))
  ([max-height ix widths heights occupied]
   (if (-> widths count (= ix))
     {:heights heights :occupied occupied}
     (for [w [(widths ix)]
           h (range (if (= w 0) 1 max-height))
           :let [new-occupied (for [dx (range (-> w - inc) w)] [(+ ix dx) h])
                 occupied (into occupied new-occupied)]
           :when (apply distinct? nil occupied)] ; Cannot call `distinct?` without any arguments, thus the `nil` is there.
       (f max-height (inc ix) widths
          (conj heights h)
          occupied)))))
```
]