[Question]
      [
Given n, k, and p, find the probability that a weighted coin with probability p of heads will flip heads at least k times in a row in n flips, correct to 3 decimal digits after decimal point (changed from 8 because I don't know how to estimate the accuracy of double computation for this (was using arbitrary precision floating points before)).
Edits:
Examples:
```
n, k, p     -> Output
10, 3, 0.5  -> 0.5078125
100, 6, 0.6 -> 0.87262307
100, 9, 0.2 -> 0.00003779
```

[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ ~~39~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Brute-force approach:**
```
0Lα1Ý²ãʒγOà³@}èPO
```
Byte-count more than halved by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/249352/52210), which uses a similar approach as [@DominicVanEssen's top R answer](https://codegolf.stackexchange.com/a/249333/52210), so make sure to upvote them as well!
Inputs in the order \$p,n,k\$.
Very slow, so use small \$n\$ in order to run it on TIO.
[Try it online.](https://tio.run/##yy9OTMpM/f/fwOfcRsPDcw9tOrz41KRzm/0PLzi02aH28IoAf6CcnimXoQGXMQA)
**Original mathematical ~~40~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
÷L®s©>m²®¹*-D>®/$-*I+s®<cI®¹*m$-®<m)øPO
```
Inputs in the order \$k,n,p\$.
[Try it online.](https://tio.run/##yy9OTMpM/f//8HafQ@uKD620yz206dC6Qzu1dF3sDq3TV9HV8tQuPrTOJtkTLJqrogvk5Goe3hHg//@/GZehgQGXgZ4ZAA)
**General explanation of the larger original program:**
Even though the challenge description was just a single sentence, it lead me on a chase down the rabbit hole. After quite a long search, I came across this MathExchange answer: [Probability for the length of the longest run in *n* Bernoulli trials](https://math.stackexchange.com/questions/59738/probability-for-the-length-of-the-longest-run-in-n-bernoulli-trials), for which [the accepted answer](https://math.stackexchange.com/a/59749/368863) contains the generalized formula for this challenge, originally solved by *de Moivre* in 1738:
$$\mathbb{P}(\ell\_n \geq k)=\sum\_{j=1}^{\lfloor n/k\rfloor} (-1)^{j+1}\left(p+\left({n-jk+1\over j}\right)(1-p)\right){n-jk\choose j-1}p^{jk}(1-p)^{j-1}$$
Where \$\mathbb{P}(\ell\_n \geq k)\$ is the probability that a consecutive run of the same unfair coin result with a length \$\ell\_n\$ is at least \$k\$ flips. \$p\$, \$k\$, and \$n\$ are as given by the challenge description, with \$p\$ being a decimal probability (e.g. 0.70 for 70%), and \$k\$ and \$n\$ being integers.
**Code explanation:**
```
0L              # Push pair [1,0]
  α             # Get the absolute difference with the first (implicit) input p:
                #  [1-p,p]
   1Ý           # Push pair [0,1]
     ²ã         # Get the second input n'th cartesian product
                # (creating all n-sized lists with 0s/1s)
       ʒ        # Filter this list by:
        γ       #  Group the 0s/1s into consecutive adjacent items
         O      #  Sum each group
          à     #  Pop and push the maximum
           ³@   #  Check if this largest group of 1s is >= the third input k
       }è       # After the filter: (0-based) index each 0/1 into pair [1-p,p]
         P      # Take the product of each inner list
          O     # Take the sum of all values
                # (after which the result is output implicitly)
```
```
÷               # Integer divide the first two (implicit) inputs: n//k
 L              # Pop and push a list in the range [1,n//k] (its values are j)
  ®             # Push -1
   s            # Swap so the list is at the top
    ©           # Store it in variable `®` (without popping)
     >          # Increase each j in the list by 1
      m         # Pop both, and calculate -1**(j+1) for each
  ®             # Push the list `®` containing j again
   ¹*           # Multiply each j by the first input k
 ²   -          # Subtract each from the second input n
      D         # Duplicate this n-jk list, since we need it again later
       >        # Increase each by 1
        ®/      # Divide each by j
          $     # Push 1 and the third input p
           -    # Subtract: 1-p
            *   # Multiply this to each (n-jk+1)/j
             I+ # And add the third input p to each
 s              # Swap so the n-jk list is at the top again
  ®             # Push list `®` containing j again
   <            # Decrease each j by 1
    c           # Calculate the binomial coefficients of n-jk and j-1
 I              # Push the third input p again
  ®             # Push list `®` containing j again
   ¹*           # Multiply each j by the first input k again
     m          # Pop both, and calculate p**(jk)
 $              # Push 1 and the third input p again
  -             # Subtract again: 1-p
   ®            # Push list `®` containing j again
    <           # Decrease each j by 1 again
     m          # Calculate (1-p)**(j-1)
 )              # Wrap these five lists on the stack into a list of lists
  ø             # Zip/transpose; swapping rows/columns
   P            # Get the product of each inner list
O               # And finally sum everything together
                # (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 66 bytes (-1 @xnor)
```
f=lambda n,k,p:n>=k and(1-p*(n>k))*(1-f(n+~k,k,p))*p**k+f(n-1,k,p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BDoIwEEX3nKJh1ZZiQCNRElh4AC9giEGggRSmTS0LY_AibtjonbyNFWH35mcy78_zrW6mljCOr95wf_c58KTNu0uZI2CCqRjSRKAcShz6imJIBSHUMsfgPcRvw86KUuHZxA-nYL40cC07xHsojJTtFTWdktqgVvfnIi_qyrGmhfFRQkUwJw6X-m9GDaBTGLANC1bbjFkMWGQ5mnlveZ3FDlK6AYO5e7cNJn8cDe5cYnnrCw)
Adapted from my [answer to a similar challenge](https://codegolf.stackexchange.com/a/248518/107561). Note that I add memoization in the footer. This in theory doesn't change the result but it greatly accelerates the recursion.
### How?
Uses the recurrence
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$
(valid for *n*>*k*) which is obtained by accounting for words that have k consecutive heads somewhere in the first n-1 tosses, words that end in a tail followed by k heads and the overlap of these two groups.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S
```
A full program accepting `n`, `k`, and `p` that prints the result.
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//w5gu4bmX4bmjMVrhuavJl8aHX@KBtUFQ4oKsU////zEw/zP/MC42 "Jelly – Try It Online")** (`n=100` is too big for such an inefficient program.)
### How?
Creates all \$2^{n}\$ possible outcomes, filters them to those containing a run of at least \$k\$ heads and then sums the probability of each occurrence.
The probability of a given occurrence is the product of `p`'s and `(1-p)`s identified by heads and tails respectively. For example the chance of `[tails, tails, heads, heads, heads]` is the product of `[(1-p), (1-p), p, p, p]` i.e. \$p^3(1-p)^{2}\$.
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S - Main Link: integer n, integer k (p is accessed later)
Ø.              - [0,1]
  ṗ             - ([0,1]) Cartesian power (n)
                  -> all length-n tosses with 0 as heads and 1 as tails
        Ƈ       - filter keep those for which:
       ɗ        -   last three links as a dyad - f(Outcome, k):
   ṣ1           -     split at 1s -> runs of heads
     Z          -     transpose
      ṫ         -     tail from index k -> empty (falsey) if longest run < k
          ⁵     - third program argument, p
         _      - subtract -> valid outcomes with heads: -p; tails: 1-p
           A    - absolute values -> valid outcomes with heads: p; tails 1-p
            P€  - product of each -> valid outcome probabilities
              S - sum -> total probability of any valid outcome
```
---
If we could take the probability of tails (\$1-p\$) instead of heads (\$p\$) 14 byes taking `1-p`, `n`, `k`:
```
C©Ƭṗṣ®ZṫɗƇ⁵P€S
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//Q8KpxqzhuZfhuaPCrlrhuavJl8aH4oG1UOKCrFP///8uNP8xMP8z)
[Answer]
# [R](https://www.r-project.org/), ~~129~~ ~~122~~ 116 bytes
*Edit: -2 bytes thanks to pajonk (which led to -4 more...)*
```
function(n,k,p)sum(apply(which(array(T,rep(2,n)),T)-1,1,function(v,r=rle(v))prod(p*v+(1-p)*!v)*(max(r$l[!r$v])>=k)))
```
[Try it online!](https://tio.run/##lY9NboMwEIX3nGKiZjEDThQQpt3QU2RXtcgiIFsQ2xoSKKenQKWqaumimyfN3/ve8NQUulKXrjC2UAW7IZ/quy1vxlm0ohGeuvsVlfftiIM2pUbFrEY8C648JsISiTMdYhGLr7tecM5thT2RZ3dBH/YRxgdP4a6nEK/qHXnfvux437/Sc94Q0fQApVa2rMDVkMAaCYwFBXMkGMxNg7PtOI/q1vhu2VJQK8NQunkth9MxkcHPX@Z8iThKCoLv9nLTPvvbWb7JaNFsrU5p9vS4wcqE/M1K/89Ko0/iImsrTjZp6UKbPgA "R – Try It Online")
Exact solution: calculates the probability of every possible outcome of `n` coin flips, and sums those that contain at least `k` heads-in-a-row.
**How?**
```
function(n,k,p){
    a=expand.grid(rep(list(1:0),n)) # a is a matrix of all possible outcomes of n flips
                                    # with heads represented as 0, tails as 1
    pvals=apply(a,1,function(v)prod(p*v+(1-p)*!v))
                                    # pvals are the probabilities of each outcome
                                    # by multiplying the probability of each single flip
    itsarun=apply(a,1,function(v)max(rle(v)$l[!rle(v)$v])>=k)
                                    # itsarun is TRUE if the longest run of 0s in each row is >=k
                                    # (rle(v)$l = length of each run, rle(v)$v = value of each run)
    return(sum(pvals*itsarun))      # return the sum of all the pvals for successful outcomes
}
```
---
# [R](https://www.r-project.org/), 98 bytes
```
function(n,k,p){while((T=T+1)<1e19)F=F+(max((r=rle(sample(1:0,n,T,c(1-p,p))))$l[!r$v])>=k);F/1e19}
```
[Try it online with a low-accuracy version](https://tio.run/##dY5BDoIwEEX3nGKMLtpQEYhFo9YlJ2BnlDQVQgO0pKhojGfHwsoYncVMJvP/f2P6Mi0yfm5TqVKeGt2xPr8qcZFaIUVK0uBnV8gqQyhhiRvgXZBRHLPYRTW/I2SYsbeW140dwcYniiREoGDeWKetWXWYmNntiPesxNt4Yd2vfgqi4EpkoHMIYcSDVMDB4qGTlwK0qh72lFeyaQcVh5xLA0JbGQPfC6nz/TcKSUg8ih3nM57@jI/@J9MTdYcejZu/jNarH6yI0IHVvwE "R – Try It Online")
Brute-force approach: performs `1e19` series of `n` flips, and counts the number of times we get `k` heads-in-a-row. With this number of repetitions, the answer has a very high chance of being accurate to 8 decimal places, but there is a low-but-finite chance that this won't be the case...
We need to do them one-after-the-other in a `while` loop (rather than the more idiomatic vectorized [R](https://www.r-project.org/) approach of building a matrix and checking the rows) since the number of iterations needed to obtain 8 decimal places of accuracy is too big to be contained in an [R](https://www.r-project.org/) matrix.
The test link substitutes `1e5` in place of `1e19`, for a lower-accuracy output without timing-out. Feel free to run the high-accuracy version on your own computer if you have the time to wait.
---
# [R](https://www.r-project.org/), 83 bytes
```
function(n,k,p,m=cbind(rbind(1-p,diag(k)*p),!k:0))Reduce(`%*%`,rep(list(m),n))[k+1]
```
[Try it online!](https://tio.run/##lc7BToQwEAbgO08xZrNJu4wbaChuTHgJr0bZWoo0ZadNYbPx6RHwYhQPXv6k08n/TZxc3RnVDLWlWtXR36qpvZIerSdG6DDgpdJvlhoW18zvAzZWvTPHD4HjnXvMOH8yzVUbdt4f9meMJrDeDiO7cCTOn12av0w70J0ibcC3IGAVwRIomEW42bEDT/3H/NX2NgzLloJW2Qjaz2sVZEchk5@nMoECj5Inyfd6uVlf/t0sX2W6ZLm@sqI8PWxYJcrfVvF/q0i/xCXWUS42tWLRpk8 "R – Try It Online")
Port of [dancxviii's Markov method](https://codegolf.stackexchange.com/a/249365/95126) - upvote that one - but sadly still longer than [pajonk's R answer](https://codegolf.stackexchange.com/a/249376/95126)...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 23 bytes
```
2$ÞẊ'2€vLG›¹>;⁰⌐⁰"$İvΠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCIyJMOe4bqKJzLigqx2TEfigLrCuT474oGw4oyQ4oGwXCIkxLB2zqDiiJEiLCIiLCIxMFxuM1xuMC42Il0=)
Port of Jelly. Really slow.
Previous answer (much faster):
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 41 bytes
```
ḭɾ:£›u$e¹¥□h*-:›¥/⁰⌐*⁰+$¥‹ƈ?¥?*e⁰⌐¥‹eWƒ*∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLhuK3JvjrCo+KAunUkZcK5wqXilqFoKi064oC6wqUv4oGw4oyQKuKBsCskwqXigLnGiD/CpT8qZeKBsOKMkMKl4oC5ZVfGkiriiJEiLCIiLCI2XG4xMDBcbjAuNiJd)
Port of 05AB1E.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 53 bytes
```
k->p->g(n)=if(n>=k,p^k*(1-p*(n>k))*(1-g(n---k))+g(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN02zde0KdO3SNfI0bTPTNPLsbLN1CuKytTQMdQu0gNxsTU0QGyivq6sL5GiDVGpCNG8pKMrMK9FI0zDW1DDQM9XUMDSASS1YAKEB)
A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/9288). Takes input in the the form `(k)(p)(n)`
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 56 bytes
```
f(n,k,p)=Pol((1-y=p*x)/(t=1-x)/(t/y^k+x-y)+O(x^n*x))\x^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3SNPJ0snUKNG0D8nM0NAx1K20LtCo09TVKbA11wbR-ZVy2doVupaa2v0ZFXB5QUjMGSEP1hyQWFORUaiQq6NopFBRl5pUAmUogjpJCcmJOjkaajkKipqaOQnS0oYGOgrGOgoGeaSyQa2gA5JqBuGZwriWIaxQbqwkxG-ZGAA)
The generation function of the sequence (for given \$p, k\$) is \$\frac{p^k\ x^k\ (1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
---
This generation function can be derived from loopy walt's recurrence formula:
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$.
This recurrence formula is valid when \$n>k\$. In addition,
when \$n=k\$, we have \$f(n,k,p)=p^k\$ when \$n=k\$, and \$f(n,k,p)=0\$ when \$n<k\$.
Let \$F(k,p)\$ be the generation function (for given \$p, k\$), we have
\$\begin{align}
F(k,p) &= \sum\_{n=0}^{\infty}f(n,k,p)\ x^n \\
 &= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n,k,p)\ x^n \\
 &= p^k\ x^k+\sum\_{n=k+1}^{\infty}(f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p)))\ x^n \\
 &= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n-1,k,p)\ x^n+p^k(1-p)\sum\_{n=k+1}^{\infty}(x^n-f(n-k-1,k,p)x^n) \\
 &= p^k\ x^k+x\sum\_{n=0}^{\infty}f(n,k,p)\ x^n+p^k(1-p)\sum\_{n=0}^{\infty}(x^{n+k+1}-f(n,k,p)x^{n+k+1}) \\
 &= p^k\ x^k+x\ F(k,p)+p^k(1-p)(\frac{x^{k+1}}{1-x}-x^{k+1}F(k,p))
\end{align}\$.
Solving this equation, we have \$F(k,p)=\frac{p^k\ x^k(1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
[Answer]
# JavaScript (ES7), 106 bytes
Quickly computes the probability, using the formula [found by Kevin Cruijssen](https://codegolf.stackexchange.com/a/249334/58563).
```
(n,k,p,q=1-p)=>(g=s=>(x=n-(y=j*k))<0?0:s*(p-~x/j*q)*(h=k=>--k?h(k)*(x-k+1)/k:p**y*q**~-j++)(j)+g(-s))(j=1)
```
[Try it online!](https://tio.run/##bcnLDoIwEIXhvU/BcmbagVYjicTBZzFe0JZAscbAxlevdWni5uQ/@dzxdYynxz08eRjPl3SVBIP2OuhJLAeUFjqJeWcZGBZx5BH35mCaSBD4PVeOJiS4iZeW2R9u4POd2SuLlW8C0UIT0ZudUggOVQccMZdYTKdxiGN/KfuxgysU1uhiowtTbhFXv2ZNtvpr9X/bfW2NmD4 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES12), 58 bytes
Using [loopy walt's recursive formula](https://codegolf.stackexchange.com/a/249360/58563) is much shorter and much slower. This version uses a cache to speed it up (-7 bytes without the cache).
Expects `(k)(p)(n)`.
```
k=>p=>g=n=>g[n]||=n>=k&&p**k*(1-p*(n>k))*(1-g(--n-k))+g(n)
//         \_____/
//          cache
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3rbJt7Qps7dJt84BEdF5sTY1tnp1ttppagZZWtpaGoW6BlkaeXbamJoidrqGrm6cL5Gina-RpQk0ISs7PK87PSdXLyU_XSNMw1tQw0DPV1DA00NTkQpUyA0mZgaQw5SxBckZQOYjJCxZAaAA)
[Answer]
# PARI-GP, 75 bytes
[Port of below solution](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN73TNPJ0snUKNG01chNLijIrNLK1tYECiTpJOhqJuoa2tkmaWgXaGok2RppaGkk22UDSULdAEyiinWRrm62drakZl6cZna1jGAsxcl9BUWZeiUaahqEBDOgYmhroGOhZmJtqakIUwewHAA) (can run n ~ 1000000000, k ~ 150)
```
f(n,k,p)=(matrix(k++,k,a,b,(a-1==b)*p+(a<2)*(b<k)*(1-p)+(a+b==k+k))^n)[k,1]
```
# Python (Numpy), 104 bytes
Noone has the markov method yet:
The states are the number of consecutive heads starting at state 0, with the final state as state k. State i (i < k) goes to state i+1 with probability p and state 0 with probability 1-p. State k always goes to state k. The matrix is:
\$
\begin{bmatrix}
1 - p & 1 - p & 1 - p & \dots & 1 - p & 0 \\
p & 0 & 0 & \dots & 0 & 0 \\
0 & p & 0 & \dots & 0 & 0 \\
\dots & \dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & p & 1 \\
\end{bmatrix}
\$
Taking this matrix to the nth power and multiplying it by the vector \$\left[1, 0, 0, \dots, 0 \right]^T \$ gives the answer.
This [solution](https://ato.pxeger.com/run?1=RY1NCsIwEIXX5hRZJvaHBARFyN47lCBd9Ce0kwwxRetV3HSjd-ptTLXQ4Q3fvPcW8_rgGFpnp_lSewfUDoAjNYDOB7onW5b3xpZ9s1XEUkWliEO6eB0EwQiRH99DqLPT3IJ6Vt7dGOsSmcblnNTOU0ONpb60TcU6fiY7KIQujFYyw8WYRP4sEig6HaUkQW9sYFAGbx5XdPfKM0gtX3qh-f_ftGLlFw) is not an clean mathematical sum but it is much more computationally efficient then the sum.
```
m=zeros((k+1,k+1))
for i in range(k):
    m[0][i]=1-p
    m[i+1][i]=p
m[k][k]=1
print(matrix_power(m,n)[k][0])
```
[Answer]
# Desmos, 80 bytes
```
P(p,k,n)=∑_{j=1}^{n/k}-(-1)^j(p+(n-jk+1)(1-p)/j)nCr(n-jk,j-1)p^{jk}(1-p)^{j-1}
```
[Try it on Desmos](https://www.desmos.com/calculator/on5h94g72s) or [prettified](https://www.desmos.com/calculator/pgfnarlcg3).
Thanks to Kevin Cruijssen for finding this formula.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 133 bytes
```
[| n k p | n k /i [1,b] [| j | -1 j 1 + ^ n j k * - :> z z 1 + j
/ 1 p - * p + z j 1 - nCk p j k * ^ * 1 p - j 1 - ^ * * * ] map Σ ]
```
[Try it online!](https://tio.run/##PY/BTsMwDIbvfYr/vNGuZWISQ@LCAXHhgjhVnZSFdKTtnJCkBxh7Gt6HVypOMyErdv7vty25FTIYN72@PD0/btErR2rAYKQYPI4ivM@paEeSQRtKrJDmuNckeFDLC3KCDuryH0lL86bg1ceoSDK2ToXwaZ2mgLssO@GEqsQaZXGD8yxKbFht/tUtq2tW56n@BqGHRaorjbq62jdg3jHLKy4Vltix3XHDAjm29/jiiLjLVlwtwwXnJdPYnoMe4s40sOOXepIXdYyG77H4/UEz1Wi182HNjI@xxqvZ80HIvpj@AA "Factor – Try It Online")
Translation of the formula given in Kevin Cruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/249334/97916).
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
`[`=function(k,n,p)`if`(n<k,0,(1-p*(n>k))*(1-k[n-k-1,p])*p^k+k[n-1,p])
```
[Try it online!](https://tio.run/##lY/BisIwEIbvfYqBvSTtVNqSRA/WFxFtQ9fQEJmEqohPX5suC6Ldw16G@ecf/m9mGF3Tn/T3pbHU6Gbw93ps921tbtRdrSfmkDDw1pqW0dZhgazMQ8po5zhPp97tKXd5ieHA03B0WdSzGr@g6zV1J/AGKpghYAk0TBC422sPns6PyTJnGy5xS4PRdoDOT2s1FKtKJu/XsQorXEmeJK/xcjFe/Z0sjzKLVc2qEGqzXmBJVJ8s8X@WyH6Iscyjcukz8Uv7cBSK6IxP "R – Try It Online")
Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/55372).
For different approaches in [R](https://www.r-project.org/) see [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/249333/55372).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
ＮθＮηＮζＩΣＥΦＥＸ²θ⍘ι²№ι×1η×ＸζΣιＸ⁻¹ζ⁻θΣι
```
[Try it online!](https://tio.run/##XYzLCsIwEEX3@YrQ1QRGaSuuurNQcFEp1B@IpdhA01cShf58nBAQcVZzztw73SC3bpaj99dpcfbm9KPfYBUF@@Xhj3fiZlOThVIaC63TUMsFKjVauoa1md@05chXgfwiTd9ayj9BIc8FqXJ21Ca6K90bSLIE@SDCJYrY35GH3yr4aGo1OQMZ8p1UhPUbilN4n6XsxNLj2R9e4wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute force approach.
```
ＮθＮηＮζ
```
Input `n`, `k` and `p`.
```
ＥＸ²θ⍘ι²
```
Get all of the binary numbers up to `2ⁿ`.
```
Φ...№ι×1η
```
Keep only those with `k` consecutive heads, I mean `1`s.
```
Ｅ...×ＸζΣιＸ⁻¹ζ⁻θΣι
```
Compute their probabilities, which is `pⁱ(1-p)ⁿ⁻ⁱ`, where `i` is the number of `1`s in each relevant row.
```
ＩΣ...
```
Output the grand total.
A 40-byte port of @dancxviii's approach is much more efficient:
```
Ｎθ≔Ｅ⊕Ｎ¬ιηＦＮ«≔⊟ηζ≔⁺⟦×Ση⁻¹θ⟧×ηθη⊞η⁺ζ⊟η»Ｉ⊟η
```
[Try it online!](https://tio.run/##XY09D4IwEIZn@is6XhM0sLA4GScGCIluxqFitU1ogX44YPzttRRDjNPdPe/HtZzqtqed96UanK2dvDINI9mhvTHioaCiA5Sq1UwyZdkNfm2EpLjuLYh54SFz7zX@c@AXSr5VTT8AD84pOFfWOQPnk5DMwNHJqFdCBZineCTkkuJF5PFc3iSNM3wmMT2FGZtJkN6o0UJZOFBjYcXeZ9sCFSjPMr95dh8 "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `p`, `k`, `n`. Expects `k>1` (+1 byte to support `k=1`). Explanation:
```
Ｎθ
```
Input `p`.
```
≔Ｅ⊕Ｎ¬ιη
```
Create an array of `1` `1` and `k` `0`s.
```
ＦＮ«
```
Repeat `n` times.
```
≔⊟ηζ
```
Remove the last entry of the array.
```
≔⁺⟦×Ση⁻¹θ⟧×ηθη
```
Multiply the array by `p`, then prefix the sum of the array multiplied by `1-p`.
```
⊞η⁺ζ⊟η
```
Add the previous last entry to the current last entry.
```
»Ｉ⊟η
```
Output the last entry in the array.
I had been planning on working out how to solve the problem using dynamic programming but I'm pretty sure it would have resulted in the same algorithm.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~30~~ ~~19~~ 17 bytes
```
ṁoΠm≠²fö≥⁰▲mΣgπḋ2
```
[Try it online!](https://tio.run/##ATIAzf9odXNr///huYFvzqBt4omgwrJmw7biiaXigbDilrJtzqNnz4DhuIsy////MS8y/zX/Ng "Husk – Try It Online")
Port of [my R answer](https://codegolf.stackexchange.com/a/249333/95126).
Input is arg1=p, arg2=k, arg3=n.
```
                πḋ2     # cartesian arg-3-th power of binary digits of 2
                        # so: all possible combinations of n heads/tails;
        fö              # now consider only those with runs: filter by
            ▲           # the maximum of
             mΣg        # the sums of each group of identical elements
          ≥⁰            # is greater than or equal to arg-2;
                        # now convert the 1s & 0s to probabilities:
   mo -²                # subtract the probability of heads from each
     a                  # and get the absolute values
                        # so 1s become (1-p) and 0s become p;
ṁo                      # finally map across each group & sum the result
  Π                     # product of the probabilities
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
kpIf[#>=k,(1-Boole[#>k]p)(1-#0[#-k-1])p^k+#0[#-1],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/v9pIUFQOyZFq1sZ5uto2Go65Sfn5MK5GXHFmgCucoG0cq62bqGsZoFcdnaYJ5hrI5BrNr/gKLMvBIFB4W0aOPYaAM909hoQ4PY/wA "Wolfram Language (Mathematica) – Try It Online")
Port of Python. Takes `f(k)(p)(n)`.
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
1 :'0{_1{[:+/ .*^:(u-1)~(1,~]#0:),.~(*=@i.),~1-['
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1A2q4w2ro6209RX0tOKsNEp1DTXrNAx16mKVDaw0dfTqNLRsHTL1NHXqDHWj1f9rcqUmZ@QrGOiZKmgYGiikaSoYw0TMQCJgITOYkBFcyPI/AA "J – Try It Online")
Almost identical to dancxviii's Markov chain approach.
]


[Question]
      [
[Related](https://codegolf.stackexchange.com/questions/246025/average-ignorant-sets-of-integers).
Given a list of 3 or more positive integers, remove every number X for which there is another number Y in the list and the average of X and Y is also in the list. In other words, if X, Y, and the average of X and Y are all in the input, neither X nor Y should appear in the output.
Note: Pairs of numbers are not successively removed from the list, rather all at once. This avoids ambiguity. A pair of numbers whose average is in the list will be removed even if one or both of the numbers are already part of another such pair.
The average of two numbers is their sum divided by two.
Examples:
```
input => output
explanation
[1, 2, 3] => [2]
1 and 3 are removed because their average (2) is in the list.
[1, 2, 3, 4] => []
1 and 3 are removed because their average (2) is in the list,
2 and 4 are removed because their average (3) is in the list.
[1, 3, 4, 5] => [4]
1 and 5 are removed because their average (3) is in the list,
3 and 5 are removed because their average (4) is in the list.
[1, 5, 10, 20, 40] => [1, 5, 10, 20, 40]
No numbers are removed; No pair of numbers also has their average in the list.
[1, 5, 6, 10] => [1, 5, 6, 10]
[1, 2, 3, 4, 10, 52, 100, 200] => [10, 52, 200]
[1, 2, 3, 5, 8, 13, 21, 34] => []
```
You may assume numbers are given in ascending order with no duplicates.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") Shortest code wins.

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
+HfḊʋÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8/1/bI@3hjq5T3YcnPNwx///hdm/NyP//ow11FIx0FIxjdRRgTB0FEygPxNRRMIXyTHUUDA2ASoDYxAAhZgYSRtUOUWhqBKLBOlDlgZosgFJAlhHIEpNYAA "Jelly – Try It Online")
```
     Ðḟ    Remove elements for which
+          that element plus each element of the list
 H         halved
   Ḋ       has more than one element
  f ʋ      after being filtered to only elements of the original list.
```
[Answer]
# [J](http://jsoftware.com/), 27 22 15 14 bytes
```
-.&,~:/~*+:-/]
```
[Try it online!](https://tio.run/##XY5BCsIwFET3PcWg0FqbpEmaiKQUioIrceG@K2kRNx5AyNXrb9IKdfFJ8v7MZF7jRmQDGocMDBKOhguc79fLyEXKvCv9vnC87MY8uZ0ELT9t7et261PW9cIHAXdtUfqkfzzfGKBQwcAm8a3RBKZRRZBl4G5BMBHuFINlUJJB0xiZz6I/vFIfps1KGEjUKAmrySV/e81QUUaMs3o6Q@5sMHPRWH5ddTHTF0fy0U0Tq8z4BQ "J – Try It Online")
Consider `1 3 4 5`.
* `+:-/]` We note that if `c = (a + b)/2`, then `2c - a = b`. So we can double the input,
and create a subtraction table between that doubled input and the original input:
```
1 _1 _2 _3
5  3  2  1
7  5  4  3
9  7  6  5
```
Now any element in that table not on the diagonal is the `a` or `b` giving rise to
a `c` in the original list, and thus invalid.
* `~:/~*` So zero out the diagonal:
```
0 _1 _2 _3
5  0  2  1
7  5  0  3
9  7  6  0
```
* `-.&,` Flatten, and then remove all the table elements from the original list:
```
4
```
[Answer]
# [R](https://www.r-project.org), ~~48~~ 46 bytes
```
\(v)v[!v%in%combn(v,2)[,combn(v,2,mean)%in%v]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY39WI0yjTLohXLVDPzVJPzc5PyNMp0jDSjdeBsndzUxDxNkHRZbCxU15c0jWQNQx0FIx0FY01NZQVbO4Voo1guJFEdBROYBFwcJKijYAoTN4FLmOooGBoA9QGxiQFMGl0cWbUZSAJVIVgI3QkQ_aZGIBpsEEITVBwohKYJaJYFUD2QZQRyM8IbEL8vWAChAQ)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes
```
{x^/x+(x-\:x)^'0}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1kd1uwyAMhe95CkeREsiPDDSZJrZMfY+mVLnJM3jK0mevoWnSrJuEMJzPHIwZ3UQeqZRU946Uz/UsxOim6Qdx6NDZYnDMvpXXM7oTnS80R24+08EPPnDGOyal6WpMc98baQvVU61ylf5mZW/Taod2pFbRcmF0zExXIuZD17v8fim6lb2aRpQl+GoaogvnMkr+OcdVFl8en2tcnsa9ktcuJVXUoQBbbPJD4B5uogzC0tlVpZKVE33QObZ7/PMLwICFwyNCE1ccoY2rFowGq6HRy/aNhS070NbyHJI2vYV3MAew7NQ8JbPlsTICRWVFokXViN0Fq/3dNBgmYdwA8bGKRg==)
Dang, [Jonah's solution](https://codegolf.stackexchange.com/a/248996/78410) translates very well to K.
```
{x^/x+(x-\:x)^'0}
      (x-\:x)      self difference table
             ^'0   remove zeros from each row
    x+             add i-th item of x to i-th row of matrix above
 x^/               seeded reduce: remove all numbers that appear
                   in the matrix from x
```
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{((*>^/^\+\2#,x-)')_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1kF0OwiAMgN85RZclG8wtBRzGEGe8h4jhZWfATO8uxZ85jQmhpV/7NWG0E+fN3qN3K6fLNnaiFud4Y2y003RFDANa3QTLY3cRXt7QHuOJGoirXRl88MQTXjDO1dBhWXunuG6Ey+Lym807X2hBOpGVTxYPlRpWiHUYnK0fS9G+2a80o6rAXylFS3NVLP7M/f0XUKBh/YrQ5yxFMDkzoCRoCb18PjepMHcTNTrd1DTXDWxBrUEnU//RbBiyVrNCsrZnC/fb/PCRq6BzB9ykakw=)
I think this idea is not touched well yet (or at least not explained well in other answers).
The idea here is: given an element E of list X, E is to be removed from the result if:
* there exists two other elements E2 and E3 of X such that E2 = (E + E3)/2
* ⇔ E, E2, E3 forms an arithmetic progression
* ⇔ E2 = E + k, E3 = E + 2k for some nonzero k
* ⇔ X-E (elementwise) contains k and 2k for some nonzero k
```
{((*>^/^\+\2#,x-)')_x}
{((             )')_x}  apply to each element E and keep those that gives 0
              x-    L = X-E
         +\2#,      (L, 2L)
     ^/^\           set intersection of L and 2L
   *>      first of grade down (index of max)
           all k's (including zero) are found in increasing order;
           index of max is nonzero iff there exist some nonzero k's
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ʒ+;Ãg
```
Byte-count halved thanks to *@Steffan* by porting [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/249019/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//1CRt68PN6f//RxvqKBjpKBjrKJjoKBga6CiYGoFoIMPIwCAWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZX/T006tM6lSNv6cHP6/1qd/9HRhjpGOsaxOhBaxwTMAtI6pmCWqY6hgY6RgY6JAZRrBhRAqAbJmhoCSZAihLipjoWOobGOEdAkk9hYAA).
**Explanation:**
```
ʒ      # Filter the (implicit) input-list by:
 +     #  Add the current value to each in the (implicit) input-list
  ;    #  Halve each
   Ã   #  Only keep those values from the (implicit) input-list
    g  #  Pop and push the length to get the amount of remaining values
       #  (only 1 is truthy in 05AB1E)
       # (after which the filtered result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org), 39 bytes
```
f a=[x|x<-a,[1]==[1|z<-a,elem(2*z-x)a]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XTFBJtoytqKmx0E3WiDWNtbaMNa6pAnNSc1FwNI60q3QrNxNhYqPLO3MTMPAVbhZR8LgWFgqLMvBIFFYU0hWhDHWMdEx3TWHRRUx0zHUMDDGEFIx0FYx0FEx0FQwMdBVMjEA1kGBngVGqqo2ABVAVkGQHFjE2gDoL5AwA)
ovs and Wheat Wizard each saved a byte. Thanks!
[Answer]
# JavaScript (ES6), 50 bytes
```
a=>a.filter(x=>!a.some(y=>x-y&&a.includes(y*2-x)))
```
[Try it online!](https://tio.run/##fY5BDsIgEEX3ngI3DRhKWizGDVzEuJi01NQgmFINnB5Bt7WLyUzyXv78O7zB9/P0XGrrBp1GmUAqYONkFj3jINUemHcPjaNUoY5VBWyyvXkN2uN44HUghKTeWe@MZsbd8IgvLUWcouOVkN06oahbh4VQJNahoKhtckCervmrnIq1@foXI3jZ37xNPUees5kvXgqW4ukD "JavaScript (Node.js) – Try It Online")
### Commented
```
a =>            // a[] = input
a.filter(x =>   // for each value x in a[]:
  !a.some(y =>  //   test whether there is a value y in a[]:
    x - y &&    //     which is not equal to x
    a.includes( //     and is the average of x and
      y * 2 - x //     another value 2y - x that exists in a[]
    )           //
  )             //   end of some()
)               // end of filter()
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 20 bytes
```
{x^/a*~=#a:-x-\:2*x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6quiNNP1KqzVU600q3QjbEy0qqo5eJKUzBUMFIwhtEKJmAWkFYwBbNMFQwNFIwMFEwMoFwzoABCNUjW1AhIghQhxE0VLBQMjRWMgCaZAABf3xgV)
Switched to @Jonah's approach.
-1 byte thanks to @ovs!
## Explanation
Input is *x*.
* `a:-x-\:2*x` subtraction table of 2*x* - *x* stored as `a`
* `a*~=#` multiply *a* by inverse of eye of *a* (i.e. zero out *a*'s diagonals)
* `x^/` remove table elements from *x*
[Answer]
# [Scala](http://www.scala-lang.org/), 52 bytes
```
s=>s.filter(i=>s.forall(j=>i==j|s.forall(_*2!=i+j)))
```
[Try it online!](https://tio.run/##dZHBTsMwDIbvewpv2qEBD21di9BEKnHggDhMGuKEEMq2FKUKXWmyCQn27MVJuzLKuESO/8@/LdushBbVZpnJlYXHXOxkKV6lWGppQH5Yma8N3BQFfPZ6AGuZQjqDB/n@dJfbZ@DJUVwZnpiLVGkry0D5eFMKrYOMJ4rz7KtNvJyFfa7OM8ZYBbATmjqJt8K15M4woFYAgYsmGOIUY4Y@HzKGHe1/BaNG60gktIZRR4txMsZwjNG4AX6luuwlSUec/54YwxnEIb3Ohwq85FPu@7cgxiucTDGkUaOaZowY5i5AG6RT@AKVF1uLtLqCTifXDK5H7R49sdlaImilac06k31TXZQqtzqvNw2gUggOOP@xbFQAM5jfwwyG3gdGCQxretAQUht5BN8uFvPFKR76HIYH@7rYT9XbV98 "Scala – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes
```
f(εn¹Mo½+¹
```
[Try it online!](https://tio.run/##yygtzv7/P03j3Na8Qzt98w/t1T608////9GGOkY6xjomOoYGOqZGQNJAx8jAIBYA "Husk – Try It Online")
```
f(          )  # filter the input to keep only elements that satisfy:
         ½+    # half the sum
       Mo  ¹   # with each other element of the input
    ε          # has only 1 element
     n¹        # shared with any elements of the input
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 7 bytes
```
'?+½?↔₃
```
[Try it Online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInPyvCvT/ihpTigoMiLCIiLCJbMSwgMiwgMywgNCwgMTAsIDUyLCAxMDAsIDIwMF0iXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJhUGoiLCJ2aMabwqMiLCInwqUrwr3CpeKGlOKCgyIsIjs7wqhad0o7Osabw7figbxg4p2M4pyFYGk7wqhaJMO3JF9cImAgPT4gYGpcXCBKcCIsIlsxLCAyLCAzXSwgWzJdXG5bMSwgMiwgMywgNF0sIFtdXG5bMSwgMywgNCwgNV0sIFs0XVxuWzEsIDUsIDEwLCAyMCwgNDBdLCBbMSwgNSwgMTAsIDIwLCA0MF1cblsxLCA1LCA2LCAxMF0sIFsxLCA1LCA2LCAxMF1cblsxLCAyLCAzLCA0LCAxMCwgNTIsIDEwMCwgMjAwXSwgWzEwLCA1MiwgMjAwXVxuWzEsIDIsIDMsIDUsIDgsIDEzLCAyMSwgMzRdLCBbXSJd).
*-2 bytes by porting Unrelated String's Jelly answer*
## How?
```
'?+½?↔₃
'       # Filter for:
 ?+     #  Add the input (vectorizes)
   ½    #  Halve each
    ?↔  #  Remove elements that are not in the input
      ₃ #  Is the length equal to 1?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->l{l-l.permutation(2).map{|a,b|a*2-b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkc3R68gtSi3tCSxJDM/T8NIUy83saC6JlEnqSZRy0g3qbb2f4FCWnS0oY6RjnFsLBeUo2Cko2Cso2Cio2BooKNgagSigQwjAwOgmv8A "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/)
## 58 bytes with unordered sets
*Thanx to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!*
```
lambda l:{*l}-{a for a in l for b in{*l}-{a}if(a+b)/2in l}
```
[Try it online!](https://tio.run/##VY3RCsIgFIav6ynOpZbR5jRi0JMsL5SQBHNjeBPDZzfPMmIX4nfO9/@c6R2fY@iyvd2z1y/z0OD75eDTadFgxxk0uAB@RVOwquQs0UdDzxxtyqgjJoehZcAZdIrBDxmIOiEykHWSDNqmRMoTzX93wfW2/g1Kjv/a2PpSuhZViOMRoVS/302zC5FYEinNHw "Python 3 – Try It Online")
## ~~62~~ 61 bytes with ordered lists
```
lambda l:[a for a in l if{(a+b)/2in l for b in{*l}-{a}}=={0}]
```
[Try it online!](https://tio.run/##VY3NCsMgEITP7VPsUVtLjfmhBHwS60Ep0oBNQvBSxGe3bppSclh2Zr4ddn6H5zTW2cl79uZlHwZ8rwy4aQEDwwgeBheJOVt6FatFYguJJ58u0aQkZeRJZ8wDNpSqGAgGtWbwkwyazaFk0G6uZVDxclKm4f@sw3hf/x62Avfa2PNSuhVUlMAnjdb98TAvwxiII4HS/AE "Python 3 – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
|$~<<`&*2@+@_
```
```
|$~<<`&*2@+@_
|               # filter
 $              # input list
  ~             # keeping only elements that are falsy for
   <<           #   discard first element of
     `&         #   common elements of
       *2@      #     twice the input list
                #     and
          +@_   #   sum of this element and the input list
```
[![enter image description here](https://i.stack.imgur.com/D5Mig.png)](https://i.stack.imgur.com/D5Mig.png)
---
Works on the basis that if the average of X and Y is Z, then X+Y=2\*Z. So we just remove all Xs whenever there's a Y that when added to it gives twice one of the other elements of the input.
Step-by-step for input of `[1, 2, 3, 4, 10, 52, 100, 200]`:
```
|$              # for each element x in input=[1, 2, 3, 4, 10, 52, 100, 200]
  ~             # keep it if the following function returns an empty list (falsy):
     `&         #   find elements in common between:
       *2@      #      double the input: [2, 4, 6, 8, 20, 104, 200, 400]
                #   and:
          +@_   #      input + x:
                #         so, when x=1 => [2, 3, 4, 5, 11, 53, 101, 201]
                #               common elements = [2, 4]
                #             when x=10 => [11, 12, 13, 14, 20, 62, 110, 210]
                #               common elements = [20]
   <<           #   and remove the first element:
                #         so, when x=1 => [4] => so won't keep it
                #             when x=10 => [] => so we'll keep it
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒcSe¥ƇḤFḟ@
```
A monadic Link that accepts a list of positive integers and yields the filtered list.
**[Try it online!](https://tio.run/##y0rNyan8///opOTg1ENLj7U/3LHE7eGO@Q7///@PNtRRMNJRMNZRMNFRMDTQUTA1AtFAhpGBQSwA "Jelly – Try It Online")**
### How?
```
ŒcSe¥ƇḤFḟ@ - Link: list L
Œc         - ordered pairs (L)
      Ḥ    - double (L) (vectorises)
     Ƈ     - filter the pairs keeping those for which:
    ¥      -   last two links as a dyad - f(pair, doubled L)
  S        -     sum (pair)
   e       -     exists in (doubled L)?
       F   - flatten (this list of pairs whose sum is in the doubled L)
         @ - with swapped arguments:
        ḟ  -   filter discard (take L and remove the pair elements)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 10 bytes
```
-Qs-L-LydQ
```
[Try it online!](https://tio.run/##K6gsyfj/XzewWNdH16cyJfD//2hDHQVjHQUTHQXTWAA "Pyth – Try It Online") or [Verify all test cases](https://tio.run/##K6gsyfiv/F83sFjXR9enMiUwUMHW9f//aEMdBSMdBeNYLhhLR8EEwgGxdBRMIRxTHQVDA6ACIDYxgAuZgURRtEKUmRqBaLB6FGmgFgugDJBlBLLAJBYA "Pyth – Try It Online")
```
-Qs-L-LydQ
    L     (Q) # Left map over the implicit input with variable `d`:
      L  Q    #   Left map over the input with variable `k`:
     - yd     #     d*2 - k
   -          #   Remove d from the resulting list
  s           # Flatten
-Q            # Remove elements of the resulting list from the input
```
### 12-byte solutions
```
fqFf}-yYTQQQ
```
```
-Qsf}.OT-QT*
```
[Answer]
# [Factor](https://factorcode.org) + `math.unicode`, ~~57~~ ~~51~~ 50 bytes
```
[| s | s [ s n+v 2 v/n s ∩ length 1 > ] reject ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU-7bsJAEOz9FdNHEPvACAUpbURDE6VCFCezJkb22dydLfHq-QcaN0TKJ9Gm5CvYixvbK-1jZnd2tdefWEY21_X98fU5X3y8IZP2e1iqJMrXhEKTtftCJ8rC0K4kFZFBrPfNWEVOa7AhRVqmyUHaJFfmv4k0j2RqMPO8owe2IwIIjHDuoHELOxS2cIjAh_Ax9jvkxNH9LUyFgqMT9LshpghGEHzBnTvfShsPpnexPMHA-ZJdvVQ8XL0qrv8uv0hJbfiLAO9YQdOWX8WqUd4yWWDY1HXd5Cc)
[Answer]
# [Desmos](https://desmos.com/calculator), ~~80~~ 76 bytes
```
f(l)=l[[[(.5k-l)^2.minfork=l[m]+l[(L-m)^2>0]].minform=L]>0]
L=[1...l.length]
```
This is probably a terrible way of doing it, but whatever. Also, the "words" `minfork` and `minform` that appear in the code are very much intentional, though you will quickly see what they actually parse as in the graph links :P.
[Try It On Desmos!](https://www.desmos.com/calculator/xhboevghmj)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hflewhjjth)
[Answer]
# [T-SQL] 111 bytes
```
DELETE FROM T WHERE EXISTS(Select*From T Y Join T Z ON T.ID NOT IN(Y.ID,Z.ID)And Y.ID<>Z.ID And T.N+Y.N=2*Z.ID)
```
Formatted:
```
DELETE FROM T
WHERE EXISTS(
    Select *
    From T as Y
    Join T as Z
        ON T.ID NOT IN(Y.ID, Z.ID)
        And Y.ID <> Z.ID
        And T.N+Y.N = 2*Z.ID)
```
I *could* save one more byte by using the excremental SQL-89 joins, but my soul is worth more than one byte.
[Answer]
# [Arturo](https://arturo-lang.io), 41 bytes
```
$[a][a--map permutate.by:2a'p[-p\0*2p\1]]
```
[Try it](http://arturo-lang.io/playground?I0bU8I)
Port of G B's [Ruby answer](https://codegolf.stackexchange.com/a/249099/97916).
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 14\log\_{256}(96)\approx \$ 11.52 bytes
```
gz0+2/z0sAqS2<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbr0qsMtI30qwyKHQuDjWwgglC5BWuiDXUUjHUUTHQUTGMhYgA)
#### Explanation
```
g   # Filter:
z0+ # Add input
2/  # Halve each
z0  # Push input again
sAq # Each is in the input?
S2< # Sum is less than 2?
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 16 bytes
```
ĐĐ2*⇹ɐ-ĐŁřĐɐ≠*Ƒ\
```
[Try it online!](https://tio.run/##AS0A0v9weXT//8SQxJAyKuKHucmQLcSQxYHFmcSQyZDiiaAqxpFc//9bMSwyLDMsNF0 "Pyt – Try It Online")
Port of [Jonah's J answer](https://codegolf.stackexchange.com/a/248996/116013)
[Answer]
# [Julia 1.0](http://julialang.org/), 32 bytes
```
!l=l[l.|>i->sum(i.+l.∈[2l])<2]
```
[Try it online!](https://tio.run/##ZY5RCsIwDED/d4rsr8M6XN3EDze8gCcY@wisQiVWaaf44QE8pxeZrXEwsFCavLykOd3IYPEYx5Rqail/NmbZ@NtZmHxB@fv1ahV12U514/HiwICx4DT2ZKz2IksgHJQaatB3JHHQA@ZXdF4Lk3H16owdyAqEuoEUGe7Re@2GkEMdWhNt@7EtJCgJ6y6KreqSCUgomTGKuYSKUcmsklCsgh1uueLKH53ETaRzh8H8O@6rVHy/Ayb/RyOY@WHGNqghUnG/adsP "Julia 1.0 – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 68 bytes
```
($a=$args)|?{$_-notin($a|%{$a-ne($c=$_)|%{$_,$c*(($_+$c)/2-in$a)}})}
```
[Try it online!](https://tio.run/##lU/RSsMwFH3vV1zGVRJNcKub@FIsFH3wRXF7Eyk1Zm6yNbPJVGj77TVJtyLbHmagNPece07OWalvWeiZXCy4UIVscBqVDcEswqx417S6KTHluTLz3ILVSYkZzyVBEWFK3ZgyFGeEYHqOgl6EfJ5jRuua1k0dBDEJwB4GMYnJgEHI4JK6KaR0n2Ew9OQu5wgGI88Nd8kRg0Hf6u037PuVPXBfceX4P8vtfDhSazUK3d97boQb0M0Hhdb22mrsLXQdumoUKrhTxW0mZvzh9UMKA6XXo5HaMED5s7KgfIMIMG2ZQur1wljgFKcQuz2PPz@Ok7U2atn6vMStkTvjtRBSa3@PgGwdKhirwmzfrSBR@ZcszETxe61y4IlaruyqpsDlp5V1WY4Wdgl6ExsTkkzLnmviQh/t0pk8tbE3Nf7bwtvUQd38Ag "PowerShell Core – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 26 bytes
```
Js12CB:U_f{avg1j~[}g1jFL\\
```
[Try it online!](https://tio.run/##SyotykktLixN/V@tZGunZG2tG1uUqFmS8t@r2NDI2ckqND6tOrEs3TCrLroWSLr5xMT8rw3P@R9tqKNgpKNgHKtga6cQbRTLBRPQUTCBiMUqgMVAAjoKphAxE4g6Ux0FQwOgciA2MYDIYIjCFJqBRJHVQASQ7YPoMzUC0WADYOqhoiABJPVAMyyASoEsI5D7YM4FAA "Burlesque – Try It Online")
Takes input as block of doubles
```
J          # Duplicate
s1         # Store as 1
2CB        # Combinations of length 2
:U_        # Filter for unique (guaranteed safe by no dups)
f{avg1j~[} # Filter for average contained in original list (1)
g1         # Get 1
j          # Reorder stack
FL         # Flatten
\\         # Remove elements contained in (1) also in averages
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
ＩΦθ¬⊙θ∧⁻κμ№⊗θ⁺ιλ
```
[Try it online!](https://tio.run/##LYvBCoMwEER/ZY8rbCGm9tSTWLy1eBcPqQoN3SYYk4Jfv0ZwLvN4w4wfE0ZvWKQL1kVszBqxtRzngAvBy0es3XZg7SZ8WpdW/BL8CoLGp3x4@PTmecIlm47zagm4OHMX6fuSQBNcCSqCUhHc9NEZtFLDIJc/7w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
  θ                 Input list
 Φ                  Filtered where
     θ              Input list
   ¬⊙               No elements satisfy
       ⁻κμ          Indices differ
      ∧             Logical And
            θ       Input list
           ⊗        Doubled
          №         Does not contain
             ⁺ιλ    Sum of current elements
Ｉ                   Cast to string
                    Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org), 67 bytes
```
f a=[z|z<-a,not$elem z[x|x<-a,y<-a,x/=y,even$x+y,div(x+y)2`elem`a]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN53TFBJto6tqqmx0E3Xy8ktUUnNScxWqoitqKkAilSCiQt-2Uie1LDVPpUK7Uicls0wDSGsaJYCUJiTGxkKMgpoIMxkA)
[Answer]
# [Zsh](https://www.zsh.org/), 75 bytes
```
for x;for y;((s=x+y,s%2||x==y))||a+=(${=${(M)@:#$[s/2]}:+$x $y})
<<<${@:|a}
```
[Try it online!](https://tio.run/##bZDBbsIwEETv/oqpcNUEkAoBpAqIxKGH9tBjTxVSXLIBqyRGsQNJCd@e2gGKVPXitXbXM/P8rTdN4vlek6gc5cyd1czzdFj2qr6@D@q6DMPK9@ta9EKPH0N@9N78xbTDP/RjsDxNe7wEr04@m8/n/LiY1uLU@IwlGCLA@FJH13rp2IpJe5tgOEAwwHhwW3GtSWBPN7n1J3jCcITAPh8zRqU0jHXwrEhnDwYHlX/1IbIYZkPISWiV4bCpsFLFNsYnodCUFFs4xLXaJjJbT9l/1GloyW7sdX3HFx/eq8/T5e8/OGbf2b9QToh4GkFqULmzASiGtXYpuruc9lIVuou92BYElYCnNos1JMTKRmj3RC7NJiUjV2cJLVVmtd@1WziLZ9qQiJ1AtItazKi/C@3kL55MUKkCGdkYRkGLPbUe1yiQhnJhrEPzAw "Zsh – Try It Online")
Not as compact as I was expecting...
```
for x;for y   # for $x, $y in the Cartesian product of the list with itself
    ((s=x+y,s%2||x==y)) ||          # test if the sum is odd or x == y. If not,
    a+=(${=${(M)@:#$[s/2]}:+$x $y})
#          ${(M)@:#$[s/2]}          # substitute the average if found in $@
#       ${                :+$x $y}  # if non-empty, substitute "$x $y"
#   a+=(${=                      }) # split on spaces and add it to $a
<<<${@:|a}                          # set difference
```
[Answer]
# [Python](https://www.python.org) + NumPy, 50 bytes
```
lambda a:a[((a+[[a]]).T==a+a[:,1>0]).sum((0,1))<2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwEEX3PcUsExxLkrZSivUU7mIWI1Is2DTEFuxZ3BRE8Urexth24-q9_z8Dc3-5oTu3dnxU5eHZd9U6_6gLNccTARWkGaOV1mQMj_dlSSvSBcqdCPHaN4wJlJxvlVku33XjWt-B7Rs3AF3BuqhqPdwAagtaosLE4ExMJwvEbLIMpUAlMBVThAxhgyCXpBAShPRXhEn9GESJvzmc5GEJpkKXpKaIwPnadqxi1sXkPQ3sxjmf_x3HmV8)
Straightforward masking with a few tricks to shorten the required indexing operations without having to explicitly import numpy.
#### How?
Construct 3d table of *z,y,x* each running through the input list *a*. Each cell is True if *2z=y+x* and False otherwise. Fixing *x=a* count solutions *z,y*. If *a* is not part of an averaging pair there is only solution *z=a,y=a*, otherwise there are more. Use boolean indexing to filter *a* accordingly.
`(a+[[a]]).T` is a shorter surrogate for `2*a[:,None,None]` and `a[:,1>0]` is shorter than the more natural `a[:,None]`.
]


[Question]
      [
Say I have a ragged list, like:
```
[
  [1, 2],
  [3,
    [4, 5]
  ]
]
```
And I want to iterate over each item and delete it one-by-one. However, I don't know the structure of the list.
So, I have to iterate over the list, with the following algorithm:
* Look at the first item of the list.
* If it's a list, concatenate it to the start of the rest of the list.
* Else, delete it.
For example, with the above example `[[1, 2], [3, [4, 5]]]`:
* `[1, 2]` is a list. Concatenate it - `[1, 2, [3, [4, 5]]]`
* `1` is a number. Delete it - `[2, [3, [4, 5]]]`
* `2` is a number. Delete it - `[[3, [4, 5]]]`
* `[3, [4, 5]]` is a list. Concatenate it - `[3, [4, 5]]`
* `3` is a number. Delete it - `[[4, 5]]`
* `[4, 5]` is a list. Concatenate it - `[4, 5]`
* `4` is a number. Delete it - `[5]`
* `5` is a number. Delete it - `[]`
There are no more items left, so our work is done.
Your challenge is to compute the sizes of the lists resulting from applying this. For example, with the above, the list starts with length 2. It then goes to lengths 3, 2, 1, 2, 1, 2, 1, 0.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - that is, you may take a list \$l\$ and generate all terms, or take a list \$l\$ and a number \$n\$ and calculate the nth or first n terms. Your results may or may not contain the length of the initial list at the start, and the 0 at the end, and you may take \$n\$ 0-indexed or 1-indexed.
Since only the shape of \$l\$ matters, you may take it filled with any consistent value instead of arbitrary integers.
\$l\$ may contain empty lists. In this case, it's concatenated as normal and the length decreases by 1.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
These include the leading length but not the trailing 0. [Reference implementation](https://tio.run/##VY7BCgIxDETv/Yo5bnER19WL4JeUIsJm2UKopY3Ifn1Ne9JDSHjJzCTtsr3iXOtCK4JQfizEJDRwsTcDplhwh/MGny0wgYvSjo/PlCgug87t2CoOK2RPTetO3iIUcCjSBKpTm85xaH26qSWIC/2tO84k7xx7iDEphyjD72fOTSPOfoSbtS4jrt57a2v9Ag)
```
[[1, 2], [3, [4, 5]]] -> [2, 3, 2, 1, 2, 1, 2, 1]
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] -> [3, 5, 4, 3, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1]
[3, 4, 5] -> [3, 2, 1]
[[[[[[[[1]]]]]]]] -> [1, 1, 1, 1, 1, 1, 1, 1]
[] -> []
[1, [], 1] -> [3, 2, 1]
[[],[[[]]],[]] -> [3, 2, 2, 2, 1]
```

[Answer]
# [R](https://www.r-project.org), ~~62~~ 61 bytes
*Edit: -1 byte thanks to pajonk*
```
f=\(l)if(h<-length(l))c(h,f(c(if(is.list(g<-el(l)))g,l[-1])))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN23TbGM0cjQz0zQybHRzUvPSSzKAXM1kjQydNI1kDaB4ZrFeTmZxiUa6jW5qDkhOM10nJ1rXMBbIghqSkmMLVgImDHWMNHXALGMIZaJjClTKVVxSBNTNlQYikNVDFSMJaEKFUDVB7II5HAA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 25 bytes
Anonymous prefix lambda.
```
{√ó‚éï‚Üê‚â¢‚çµ:‚àá((0‚â†‚â°‚äÉ‚çµ)/‚äÉ‚çµ),1‚Üì‚çµ}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ed9Ux@1TXjUuehR71arRx3tGhoGjzoXPOpc@KirGSikqQ@ldQwftU0GMmr/pwHVazzq7QNLrHnUu@XQeuNHbROBBgUHOQPJEA/PYM1qqLm9W3XUFR61TQIS3S0KQEGvYH8/iDHq0dGGOgpGsToK0cZAbKKjYBobG6vOBZIw01EAiRmCKZNYoBqgdLQRmGsJZJnqKJjBFBuDJU2hOiHAMBYKwIIQEmhYNNAgw1h1AA "APL (Dyalog Unicode) ‚Äì Try It Online")
`{`‚Ä¶`}`‚ÄÉ"dfn"; argument is `‚çµ`:
‚ÄÉ`‚â¢‚çµ`‚ÄÉtally the argument
‚ÄÉ`‚éï‚Üê`‚ÄÉprint that
‚ÄÉ`√ó`‚ÄÉsignum of that
‚ÄÉ`:`‚ÄÉif 1 (i.e. there's content):
‚ÄÉ‚ÄÉ`1‚Üì‚çµ`‚ÄÉdrop the first element of the argument
‚ÄÉ‚ÄÉ`(`‚Ä¶`),`‚ÄÉprepend:
‚ÄÉ‚ÄÉ‚ÄÉ`‚äÉ‚çµ`‚ÄÉthe first element of the argument
‚ÄÉ‚ÄÉ‚ÄÉ`(`‚Ä¶`)/`‚ÄÉreplicated by (i.e. if the following holds true):
‚ÄÉ‚ÄÉ‚ÄÉ‚ÄÉ`‚äÉ‚çµ`‚ÄÉthe first element of the argument
‚ÄÉ‚ÄÉ‚ÄÉ‚ÄÉ`0‚â†‚â°`‚ÄÉis its depth different from zero? (i.e. a list)
‚ÄÉ‚ÄÉ`‚àá`‚ÄÉrecurse
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
def f(x,*r):print-~len(r);x>{}<f(*x+r);f(*r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENXMzVZpD80ikvvIdqgILWECCmiF3HTjXgaD-BtnPQjOEPyZvLeG5I8Xk3rDuc67brnxRk5_4h9ZcCgF4kl3dhj7eT9VNVoaenX19vKYOJn3DBaGj3v4NlgsiUdgbOtNqGOoPK7qnFaQQT9pFhKGUcsRFQCUhKAGa9cQEEcA1MKCIeqh5xYxDymfbvgqhBQ_tRZzxaTdwgl6D8HdgQejDxUTZ5wi7CHZIbGR00f8gU)
Prints to STDOUT; terminates with an error.
# [Whython](https://github.com/pxeger/whython), 37 bytes
-7 bytes thanks to @ovs
```
def f(x,*r):print(len(r)+1);f(*x+r?r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENBmGnTRfpD48Kd9xBNqCC1hIjtWdx0I97Gvbdx0rSCM0zm8948kjxe92ZwzbUdx-fNmWz9WZ20AYO9SCypzp5bhxfdoqVU0tZg0qd2Z2kmvz15j8mBVATODsr4OgLdH3XnlIwgKMRZlsUUMRNRCshJABYcpYCK2AJSC_BDOaWSmMQ45lO74aoSUP_YxYRWy24wKejfAzonFkYWlcuOv4U_vTNC86uWr_gC)
Despite being Whython, this still also terminates with an error.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~¬†55 53¬†~~ 52 bytes
*Saved 2 bytes thanks to [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*
*Saved 1 more byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) and [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*
```
f=a=>[n=a.length,...n?f(a.shift().concat?.(a)??a):a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBLDsIgEIb3noIlJDgJfUVNkIMQFqSW1qSBRfE0brrQQ3kFT-HQ1o0yCc_5_p8Z7g8fLt08P2_R7Q-vykkrz9pLC2Pn-zhwAPDKUQvTcHWRMmiDb21UQC1TyrKTNZv2jZkpjB2MoaeOai04KQwnusRRcVIbYxjb_VINJwkQy1IZFCCri-V4xF3NSZNVlgtZ5zzXEGaLfyJzhQVofFzk_FIXOKfidLJbO_7-2gc)
### Commented
```
f = a =>           // f is a recursive function taking the input list a[]
[                  // build the output:
  n = a.length,    //   append the length of a[] and save it in n
  ...n ?           //   if a[] is not empty:
    f(             //     do a recursive call:
      a.shift()    //       extract the leading entry and attempt to
      .concat?.(a) //       concatenate it with the remaining entries
      ??a          //       if it fails, just append a[] (the leading entry
                   //       was not an array)
    )              //     end of recursive call
  :                //   else:
    a              //     stop the recursion and return a[] (which is empty)
]                  // end of output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒîDg,ƒáDi\√´√¨
```
A byte is saved by taking the input filled with `1`s instead of positive integers.
Outputs the lengths on separated newlines to STDOUT, including a trailing 0.
[Try it online](https://tio.run/##yy9OTMpM/f//3BSXdJ0j7S6ZMYdXH17z/390tKGOYawOkAQzYmMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRfWgLh6fw/N8UlXedIu0tKZszh1YfX/K@tPbTN/n90dLShjmGsDpAEM2JjdRTAQmAuSADORFIAkQKphACQMBgAhSDyQAqqAGg21FQgKxrMBhEA).
**Explanation:**
```
Œî      # Loop until the result no longer changes (e.g. until the list is empty):
 D     #  Duplicate the current list
  g    #  Pop and push the length
   ,   #  Pop and output this length with trailing newline to STDOUT
 ƒá     #  Extract head; pop and push remainder-list and first item separately
  D    #  Duplicate this extracted head
   i   #  If it's a 1:
    \  #   Discard it from the stack
   √´   #  Else (it's a list instead)
    √¨  #   Prepend-merge it to the remainder-list
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes
```
#'{$[t~*t:*x;!0;t],1_x}\
```
[Try it online!](https://ngn.codeberg.page/k#eJxdT+1ugzAM/J+ncLVJgyoUEhK0EmkvkkUroqFFZWUr2UQ1tc8+89WxOtg4d76zUqQPTz+P2l2XLl22ahEpZyh7ay+vhLgUmfP1lBYA0KpNfVDepsjKSrXqrE6+uRCnPQZcebESIH1fcYiBA7tlZLoRL1GxYkgJXwnlcbytlYQEBTFIEDDVTiJmFr0cZSBV/AfQMRh6/j89jW+gw17WvYf5c63XsZiLaIBHgoRk79xHk4ZhXm/trq6KVeOy/GDbfJ8dd3aV1+/h55dtXFkfm5CL5yTiYensKXPlt63OwdZW1tkgC6qycYRozShwQ0HHmIKCNMZA8AKaU0AIK5tXg4qkZzoh/oRBMerG+TV2kkIyuSAke37eDHbibgFaxz0qb9Jp4xDMjNHTrBfefzg90NjgXZsOu7czFN3Qh2oz5/g0QX4BSgWRIw==)
Output includes the length of the initial list and a 0 at the end.
* `{...}\` set up a scan-converge, seeded with the (implicit) input and run until two successive iterations return the same result
	+ `$[t~*t:*x;!0;t]` using `$[c;t;f] cond`, check if the first item is a list or an atom. if it is an atom, return an empty list (`!0`); if it is a list, return the first element of that list
	+ `,1_x` append the remainder of the list (dropping the first item)
* `#'` return the number of items in each iteration
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
√ñ‚î¨‚òª‚ï™<√¶¬∑√´97‚ïûœÜ¬∫‚ô†B
```
[Run and debug it](https://staxlang.xyz/#p=99c202d83c91fa893937c6eda70642&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
√º‚ïú‚ÜêŒ¶‚ñ†Yxbo‚ïü‚Åø‚ñÄ√≠‚ñºŒµ~
```
[Run and debug it](https://staxlang.xyz/#p=81bd1be8fe5978626fc7fcdfa11fee7e&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
a generator.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
```
[Try it online!](https://tio.run/##JYwxC8IwEIX3/o1ABz3Rq2mhSCCLm4PgWDqE0NoMjSDZjvSvx6cO9917d@9udWmZVpeCd2U25f4OMQ1hb25TfKbFqgOP6nS0qh6C4Ysa6zLb3dUvr@3hXdykEmFqMsmZRFObcyaMOoJlQMNrkgayJ2mp@wewQBbiW0xo/LvDHwARoMrlAw "Wolfram Language (Mathematica) ‚Äì Try It Online")
Prints the lengths. Includes a trailing `0`.
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
                          [i=1;#]   initialize i=1 before run
                    #0/@#           in depth-first, prefix order:
      i+=Length@#-1                   add length-1 to i (atoms have length 0)
Print[             ]                  print i
```
[Answer]
# JavaScript (ES2019), ~~51~~ ~~48~~ 47 bytes
```
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_UzbQ2s02w1ymyjYzVt7aIztW3L9HJS89JLMnQVFTN19PT0yvTSchJLfBMLNNI0YyHabjGqJ-fnFZcolCrYKpTmpaSmZealpnCBxPJzUvVy8tM10jSio0t1FEpjdRRANIQdCyI0NYlQiEsVVAHMMAQXn06YDixmQgBIGxhgqsBuXDQun4B8ASRBjosGGQcJL1hwAwA)
Input requires `undefined` as leaves. Output includes initial size and trailing `0`.
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then there is this 40-byte solution:
```
i=0;f=(v=[])=>[i+=v.length-!!i,v.map(f)]
```
## Algorithm
Instead of implementing the specified process and constructing the intermediate arrays, this submission uses an analytical solution to calculate the output.
Notice that, with the process in the question, each item of the root array is completely deleted before moving on to the next item. Using the original example `[[1,2],[3,[4,5]]`, the `[1,2]` subarray is fully deleted before `[3,[4,5]]` is touched. This means that while processing `[1,2]`, the sizes of the intermediate arrays at each step is the same as those while processing `[1,2]` as a root, but plus 1 because we have to count `[3,[4,5]]`
```
[[1, 2], [3, [4, 5]]]
[1, 2, [3, [4, 5]]]   (size: 3)        |        [1,2]   (size: 2)
[2, [3, [4, 5]]]      (size: 2)        |        [2]     (size: 1)
[[3, [4, 5]]]         (size: 1)        |        []      (size: 0)
```
Take another example from the test cases
```
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]]
[6, 3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]]   (size: 5)        |        [6, 3, [1, 3, 4]] (size: 3)
[3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]]      (size: 4)        |        [3, [1, 3, 4]]    (size: 2)
[[1, 3, 4], 4, [2, 3, 9, [5, 6]]]         (size: 3)        |        [[1, 3, 4]]       (size: 1)
[1, 3, 4, 4, [2, 3, 9, [5, 6]]]           (size: 5)        |        [1, 3, 4]         (size: 3)
[3, 4, 4, [2, 3, 9, [5, 6]]]              (size: 4)        |        [3, 4]            (size: 2)
[4, 4, [2, 3, 9, [5, 6]]]                 (size: 3)        |        [4]               (size: 1)
[4, [2, 3, 9, [5, 6]]]                    (size: 2)        |        []                (size: 0)
```
The size difference is 2 here because there are 2 items after the item being processed (`[6, 3, [1, 3, 4]]`).
This shows that this problem can be solved with a recursive algorithm
```
f([1, 2]) = [2, 1, 0]
f([3, [4, 5]]) = [2, 1, 2, 1, 0]
                                [2, 1, 0][2, 1, 2, 1, 0]
                           + [2,       1,             0]
                           --------------------------------
f([[1, 2], [3, [4, 5]]]) =   [2, 3, 2, 1, 2, 1, 2, 1, 0]
```
More precisely, the output of processing an array consists of:
* The initial length of the array, then
* For each item, the result of processing that item, plus adding the number of items after it to each element.
### Naive, readable implementation
```
function f(value) {
    if (value !== undefined) {
        return [
            value.length,
            ...value.flatMap((item, index) => f(item).map((n) => n + value.length - index - 1))
        ]
    }
    return [0]
}
```
## Golfing
First, of course, is to apply basic golfing techniques
```
// 70 bytes
f=v=>v?[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]:[0]
```
Then, since leaves are `undefined`, we can actually use default argument to treat leaves as `[]` and merge the two branches
```
// 69 bytes
f=(v=[])=>[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]
```
Then, instead of mapping a second time to add the "base" value `v.length-j-1`, we can make `f` accept a second argument for a value to add to everything.
```
// 67 bytes
f=(v=[],i=0)=>[v.length+i,...v.flatMap((u,j)=>f(u,v.length+i-j-1))]
```
Next, we can pull `i` up to the global scope and mutate it instead of passing it around and using a lengthy expression to calculate the base
```
// 53 bytes
i=0;f=(v=[])=>[i+=v.length,...v.flatMap(u=>f(u,i--))]
```
Finally, we can move the `i--` decrement into `f` so that, instead of decrementing at each `flatMap` iteration, we just decrement `i` at the start of `f`.
```
// 45 bytes
i=1;f=(v=[])=>[i+=v.length-1,...v.flatMap(f)]
```
**BUT**, this breaks because the global variable `i` is changed after calling `f`, which is [forbiddened](https://codegolf.meta.stackexchange.com/a/4940/6972). Specifically, `i` is decremented by 1 for each root call to `f`. Before the change, `i` is decremented by 1 by one per child while looping in `flatMap`, but now `i` is decremented by 1 per call (i.e. per node), and the root is the only node that is not a child.
To counter this, we need to change the increment to "number of children" (instead of "number of children - 1") but only for the root node. This is doable by noticing that `i` is at its initial value only at the start of a root `f` call and after processing the last leaf. So we can initialize `i` to 0 and when we increment `i`, we increment by "number of children" if `i` is 0 but by "number of children - 1" otherwise.
```
// 47 bytes
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), (16) 21 bytes
```
Ôº∑Œ∏¬´‚ü¶Ôº©Ôº¨Œ∏‚üß‚âî‚Å∫‚à®ÔºÜ‚Å∞¬ßŒ∏‚Å∞œÖŒ¶Œ∏ŒªŒ∏
```
[Try it online!](https://tio.run/##HYxLC8IwEITP7a/Y4wYi1FdBPFVBEAR7DzmENrSBEMmjVhB/e9x2YWd2voHtRhW6l7I5z6OxGtAz@JZFG4xLKK4qJnxoN6SRCibZuSyaGM3gsLVTxGfAi0mzibpxPVYcmnR3vf6g51AxxmGivRmbdFiQXZCnJ7@chRA1hz0HsV3tICUJxd0aT3QdOdSSJm/e9g8 "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
Ôº∑Œ∏¬´
```
Repeat until the input list is empty.
```
‚ü¶Ôº©Ôº¨Œ∏‚üß
```
Output its length on its own line.
```
‚âî‚Å∫‚à®ÔºÜ‚Å∞¬ßŒ∏‚Å∞œÖŒ¶Œ∏ŒªŒ∏
```
Add the tail of the list to the first element.
* This would be three bytes shorter if the list was to be iteratively deleted from the end rather than the start.
* This would be four bytes shorter if Charcoal's vectorising `Add` worked properly, but unfortunately it only vectorises to depth 1. (Other operators, such as `BitwiseAnd`, do vectorise correctly, so I'm assuming this is an oversight. Edit: Ironically, `Times` also doesn't vectorise correctly, so I needed to replace it with `BitwiseAnd` to fix a bug.)
* Alternatively, this could be two bytes shorter if the input integers were all zero. (Not applicable when vectorising `Add` works properly.)
* This could be one byte shorter by outputting the last length instead of the first.
16 bytes using the newer version of Charcoal on ATO:
```
Ôº∑Œ∏¬´‚âî‚Å∫¬ßŒ∏‚Å∞Œ¶Œ∏ŒªŒ∏‚ü¶Ôº©Ôº¨Œ∏
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfDyzMyc1IVNAo1Faq5OB2LizPT8zQCckqLNRxLPPNSUis0CnUUDDR1FNwyc0pSi0C8HE0gt1DTmoszoCgzr0Qj2jmxuETDJzUvvSQDaI5mLFCqdklxUnIx1JLl0Uq6ZTlKsTe1o6OjzXQUjHUUog3BlElsLJAAco3AXEsgy1RHwSwWCCBaAQ "Charcoal ‚Äì Attempt This Online") Link is to verbose version of code. Outputs the last length instead of the first.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O·∏¢;$·∏ä‚Åº¬°¬µ∆¨·∫à·πñ
```
A monadic Link that accepts a ragged list of integers and yields the lengths as a list, including both the initial length and a trailing `0`.
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP///0dHm@koGOsoRBuCKZPYWCAB5BqBuZZAlqmOgllsbCwA "Jelly ‚Äì Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP86h9uPTnq4c8ajpjVZjxr36dppRv7/Hx0dbaijYBSroxBtDMQmOgqmsbGxXDrR0WY6CiARQzBlEgtUAZSMNgJzLYEsUx0FM4hSY7CUKVgXBBjGQgFQCISBhkQDDTAEKwHZBSRBJgJJrlgA "Jelly ‚Äì Try It Online").
### How?
```
O·∏¢;$·∏ä‚Åº¬°¬µ∆¨·∫à·πñ - Link: ragged list of positive integers, L
        ∆¨   - collect input, X (initially L), while distinct, applying:
       ¬µ    -   this monadic chain - f(X):
O           -     ordinal value (vectorises) -- only here to get us a copy of X
                                                so that we don't mutate it with ·∏¢
   $        -     last two links as a monad - f(Y=that):
 ·∏¢          -       head Y (alters Y, yields the first element or 0 when given [])
  ;         -       concatenate that with (the altered Y)
      ¬°     -     if...
     ‚Åº      -     ...condition: that equals X? (head of X was an integer)
    ·∏ä       -     ...then: dequeue
         ·∫à  - length of each
          ·πñ - pop the last length (removes the trailing 1, the length of 0)
```
---
Also 11 with no `·∏¢` and, therefore, no `O`: `1·ªã;·∏ä·∏ä‚Åº¬°¬µ∆¨·∫à·πñ`
[Answer]
# JavaScript (ES5), ~~¬†84¬†~~ 80 bytes
*Saved 4 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
```
function(a){for(r=[];m=a.shift(r.push(a.length));)a=m[0]?m.concat(a):a;return r}
```
[Try it online!](https://tio.run/##jVJPT4MwFL/vUzx3WNqkNmODRSXEkwc96MFj00NF2DCsJW1ZYpZ9dnyUbcGpiS/QPt77/WlpP9ROudxWjb/e3XSlsSQ32nkQlW5az8C0HmcJpgQxAQwBQkQMFpKBWOIbM0iklIDpggFWcIzGowTJzsxVgPQCOMUSReIz8RazhMHqqIaVJLTHySAbXxiNLZahnZwkfqxgiEgeA4bV/PKMWQE2LkT9dwD9YSMZuqA@E3KEWYyQksI@wIcfbgsHGZCubHXuK6OJovv@OGwmZLrNFHebqvTE8qZ1G6J4Xei131CaUpVtxVzebzkK5coj8U6ltvCt1WAPXW9BSThOmgbDqiRPry/P3Hlb6XVVfhI0p3CVZXBRF5zz4QYwmEsa2LMZ/Jc@UCmlYY@mLnht1mT6YK2xU9Zv@XTBcGWHyTfQYwnaHLug3syuYKDqGnzhvINGOVe8T2nafQE "JavaScript (V8) ‚Äì Try It Online")
Formatted and renamed:
```
function(array){
    result = [];
    while(
        result.push(array.length),
        current = array.shift()
    ) {
        if(current !== +current) { // if current is not a number
            array = current.concat(array);
        }
    }
    return result;
}
```
[Answer]
# Rust, ~~19~~ ~~194~~ ~~185~~ 174 bytes
Even defining a type for a ragged list is bytes intensive in rust. Still shorter than C :)
```
enum K{N,Y(Vec<K>)}fn f(k:&K,n:usize)->Vec<usize>{if let K::Y(b)=k{[n+b.len()].into_iter().chain((1..).zip(b).map(|(i,z)|f(z,b.len()+n-i)).flatten()).collect()}else{vec![n]}}
```
Sequences will have a extra 0 at the end. [Verify all test cases](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c8474744bc710deb37a6d0546f7a477b)
-9 bytes by using `Vec` instead of array slices
-11 bytes by replacing `enumerate` with `zip` and `match` with `if let`
[Answer]
# BQN, 26 bytes
```
{(‚â†‚àæ¬∑ùïä=‚àò‚äë‚ó∂‚ü®‚ü©‚Äø‚äë‚àæ1‚ä∏‚Üì)‚çü(√ó‚â†)ùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiaDiirjiiL4o8J2Vij3iiJjiipHil7bin6jin6nigL/iipHiiL4x4oq44oaTKeKNnyjDl+KJoCnwnZWpfQoKKOKAolNob3cgRuKImOKAokpzKcKo4p+oCiJbWzEsIDJdLCBbMywgWzQsIDVdXV0iCiJbWzYsIDMsIFsxLCAzLCA0XV0sIDQsIFsyLCAzLCA5LCBbNSwgNl1dXSIKIlszLCA0LCA1XSIKIltbW1tbW1tbMV1dXV1dXV1dIgoiW10iCiJbMSwgW10sIDFdIgoiW1tdLFtbW11dXSxbXV0iCuKfqQpA)
-1 byte thanks to @DLosc!
## Explanation
* `‚â†‚àæ¬∑...` append input length to...
* `(...)‚çü(√ó‚â†)ùï©` if input is nonempty...
* `...‚àæ1‚ä∏‚Üì` append tail to...
* `=‚àò‚äë‚ó∂‚ü®‚ü©‚Äø‚äë` head if head is rank 1 (i.e. list), otherwise empty list
* `ùïä` recurse
[Answer]
# [Factor](https://factorcode.org/), 57 bytes
```
[ [ dup length . unclip [ prepend ] when* ] until-empty ]
```
[Try it online!](https://tio.run/##lZFNb8IwDIbv/RXvrpOKBC0XkLhOu@yCOFUcqmDWiuCGNNWGqv72zsDSrwvCr2InVvzYSo6pcoVtd9vPr48VTmSZNEq6VMSKShhLzl2Nzdn12Rn9OpuWyAusg6AOIFaLjqLmHv3@pqm9IdzIhQUiWfNuNSPMwz8Q/WmI/cdEWCLu/A0UD8Ae6mHPrIOOJxrK9@81KZ5P5DHPu48w/ej1/Q2a10ZvgjZBgkNloIm/XYYZKlY6N5KVXzXEB@zxkxG/S6zY5Tqks3FX7KWStSRVcTZFSaBUZe0f "Factor ‚Äì Try It Online")
Input consists of ragged sequences of `f` ‚Äî Factor's canonical false value ‚Äî as this saves about 20 bytes over integers.
* `[ ... ] until-empty` Call `[ ... ]` on the input until it's empty.
* `dup length .` Print the current length of the input non-destructively.
* `unclip` Remove the first element from the sequence and place it on top of the data stack.
* `[ prepend ] when*` `when*` is like `when` except it drops its input value if it's false, but retains its input if it's true (which is any non-false value in Factor). So, prepend it to the input if it's a sequence, or drop it if it's `f`.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L140), 15 (non-competing‚Ä†) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{‚îú_nn¬°¬ø\;+ho}‚ñ≤;
```
‚Ä† The program above doesn't compile due to a bug in MathGolf with (do-)while loops using blocks above 8 characters. `{...}` is supposed to be a block for when `...` contains more than 8 characters, but instead the `{` behaves as a for-each.
We can remove the `{}` and trailing `;` so the do-while works on all preceding characters, so we can verify the test cases. Unfortunately, all test cases will then output an additional trailing empty list `[]`.
Both programs also fail with an error for input `[]`.
Outputs each length to STDOUT, without leading length and with trailing 0.
`‚îú_nn¬°¬ø\;+ho‚ñ≤`: [Try it online](https://tio.run/##LUq7DYNAFOtZJW4eHCdFGcVYiIZQEGgySpQqTVbIAkiMwiLHy4FlWf49uudwn8c@pe31aadp/a5Lc7sM8/b@pUQaSoEVGFBLKsgIT@YSJASwdHsFa8S8e@9P/x0wnSjoNFCw/ypkntZFOe4).
**Explanation:**
```
{           }‚ñ≤  # Do-while true with pop:
 ‚îú              #  Extract and push the left item of the list
                #  (this is where the `[]` test case errors)
  _             #  Duplicate it
   n            #  If it's a list: join it with newline delimiter to a string
                #  If it's an integer: push a newline "\n" character
    n¬°          #  Check that this string is NOT equal to "\n"
      ¬ø         #  If it's indeed not "\n" (thus it's a list)
       \        #   Swap the top two values
      ¬ø         #  Else (it's an integer):
        ;       #   Discard it from the stack
         +      #  If it's a list: merge the top two lists together
                #  If it's an integer: add it to each inner-most value
          h     #  Push the length (without popping the list)
           o    #  Output it with trailing newline (without popping)
             ‚ñ≤  #  Once the length is 0, the do-while stops
              ; # After the do-while: discard the empty list (since MathGolf
                # implicitly outputs the entire stack at the end of a program)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 266 bytes
```
#define S *w++=*r++
#define B b+=*r==91?1:-(*r==93)
f(r,b,w)char*r,*w;{w=++r;if(*++r==93)r++,r+=*r?*r==44:-1;else{if(*r!=44)for(b=1;b;B)S;r++;}for(;*r;)S;*w=0;}i;main(b,v,r)char**v,*r;{for(v++;*(*v+2);printf("%d ",i),f(*v))for(b=0,r=*v,i=1;*++r;B)(!b&&*r==44)&&i++;}
```
[Try it online!](https://tio.run/##PY7LbsIwEEX3fEWgauTHRMKUDYwsJH6BJfICh7i1VNJqWtmLiG93x6HtZh5X986Zvnvt@1KerkOI49CcGpW1toq0Xvxpx8ZXxdqdOZh9J@bxRS6CIPCQZf92IUWgMk7Zak0Yg1DcZxcfAqrxQ41tt/vO4PD@NUzVREtWZPgg4a1Bj0d5Qg7gvUqoCHlX2a7xHvF2iaPwkIAeQJWADVN1Jo4ooZLeSPykOH4HsXq@NiuIEpiS5C9iDWQ5FplV/2OcWPq2fTwm2zZWdCnlfDZgYC7Guf9xbs65Hw "C (gcc) ‚Äì Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes
```
0
[]
+`..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
$&¬∂[$2$5
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
[Try it online!](https://tio.run/##RY5LCsJADIb3OcWAo2TaGJy2UxDEHiQNVNCFGxfisufyAF5sTKeCgTz/LyHP2@v@uOQtTuO1hgM4yAcQhXpiRqVhRsRRwozDad@dNcwU6qABuQoe/O7zFt/4BIz859qVq5RDxQP4TcxZJJJrlJy05h25pKoAIj25ZRJL6tQIE6Up7dGqRK5f0bZIqWytFvVnsLwMyxGxA7EgSkaYRha@ "Retina 0.8.2 ‚Äì Try It Online") Outputs both leading and trailing counts and takes `0` as the consistent value (since `[]` is disallowed), but link is to test suite that replaces all non-negative integers with zero and deletes spaces for convenience. Explanation:
```
0
[]
```
Replace `0`s with empty lists.
```
+`
```
Repeat until the last line is an empty list.
```
..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
```
On the last line, match a list containing either an empty list as its first or only element, or otherwise the contents of the list at the first element.
```
$&¬∂[$2$5
```
Keep the original list to count its elements later and create a new list obtained by prepending the contents (if any) to the rest of the list.
```
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
Count the number of elements of each list.
[Answer]
## Brev, 85 bytes
```
(fn(descend(x)(cons(length x)(desc(if(pair?(car x))(append(car x)(cdr x))(cdr x))))))
```
Example:
```
((fn (descend (x)
              (cons
               (length x)
               (desc
                (if (pair? (car x))
                    (append (car x) (cdr x))
                    (cdr x))))))
 '((1 2) (3 (4 5))))
```
`fn` makes a function with an argument `x`. `descend` checks if it's null, if it is, return it. Otherwise, `cons` its `length` onto a recursive call of `descend`, where the `car` of `x` has been spliced if it's a `pair?` or dropped if it's an atom. For the test example, it returns `(2 3 2 1 2 1 2 1)`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
#l=+|hQYt
```
[Try it online!](https://tio.run/##K6gsyfj/XznHVrsmIzCy5P//6GgDHQWDWB0FEA1hx8YCAA "Pyth ‚Äì Try It Online")
Accepts a ragged list filled with 0s.
Excludes the length of the initial list, and includes the 0 for the final list.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
saj{g_Jto'B~[{j_+}qvvIEsaj}qL[w!
```
[Try it online!](https://tio.run/##VU3LCoJQEN33FZObFuHiPhTCcFG0KNy3kJACCUQoM20xTL9@O/lAPJcZLuc1t@ZV5nXV5I49P/aiyL88c1dfC75np/djtfumXGRrqdr2eAAtVZJ@lq4F9snWl3PpmBVpITbElgIRIT8m1mRIkxpHFswhKHgNWXhsb9kQBxSOIUMBhHH/o3aqQQWiuDBYh9YeSgZ0oqLZg63n8VHYYOYdggZkWSZed9oP "Burlesque ‚Äì Try It Online")
```
saj      # Get initial length
{
 g_      # Pop head from list
 J       # Dup
 to'B~[  # Is Block
 {j_+}   # Prepend elements
 qvv     # Drop
 IE      # If (isBlock) else
 saj     # Length
}
qL[w!    # While non-empty
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
```
{‚ç¥‚ç¥‚çµ:‚àä(‚ç¥,‚àá¬®+‚ç¥-‚ç≥‚àò‚ç¥)‚çµ‚ãÑ0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvFjDaavWoo0sDyNR51NF@aIU2kKX7qHfzo44ZQJYmUP5Rd4tB7f@0R20TgKr6HnU1P@pdA5Q6tN74UdvER31Tg4OcgWSIh2ewJpD2Cvb3@5@mHh1tqKNgFKujEG0MxCY6CqaxsbHqXCAJMx0FkJghmDKJBaoBSkcbgbmWQJapjoIZTLExWNIUqhMCDGOhACwIIYGGRQMNMoQqjNUBqgOq0AES6gA "APL (Dyalog Classic) ‚Äì Try It Online")
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then `‚àä` is not needed for -1 byte
Uses the same algorithm as my [other submission](https://codegolf.stackexchange.com/a/251282/6972), but pretty much ungolfed because tacit APL is that good
```
{‚ç¥‚ç¥‚çµ:‚àä(‚ç¥‚çµ),(‚àá¬®‚çµ)+(‚ç¥‚çµ)-(‚ç≥‚ç¥‚çµ)‚ãÑ0}  With trains expanded

 ‚ç¥‚ç¥‚çµ:                           If argument is array
           (‚àá¬®‚çµ)                  recursive call with each element
                 +(‚ç¥‚çµ)-(‚ç≥‚ç¥‚çµ)      add (length of argument - index)
                                    note that APL arrays are 1-based by default
      (‚ç¥‚çµ),                       prepend length of argument
     ‚àä                            flatten
                           ‚ãÑ0   Else return 0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth) (arbitrary values), 15 bytes
```
lM.u+.x[.*hN[)t
```
[Test suite](https://pythtemp.herokuapp.com/?code=lM.u%2B.x%5B.%2ahN%5B%29t&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B3%2C+%5B4%2C+5%5D%5D%5D%0A%5B%5B6%2C+3%2C+%5B1%2C+3%2C+4%5D%5D%2C+4%2C+%5B2%2C+3%2C+9%2C+%5B5%2C+6%5D%5D%5D%0A%5B3%2C+4%2C+5%5D%0A%5B%5B%5B%5B%5B%5B%5B%5B1%5D%5D%5D%5D%5D%5D%5D%5D%0A%5B%5D%0A%5B1%2C+%5B%5D%2C+1%5D%0A%5B%5B%5D%2C%5B%5B%5B%5D%5D%5D%2C%5B%5D%5D&debug=0)
Takes a ragged list of arbitrary values (even accepts floats). Includes length of original list and final 0.
##### Explanation:
```
lM.u+.x[.*hN[)t   | Full code
lM.u+.x[.*hN[)tNQ | with implicit variables
------------------+----------------------------------------------------------------------------------------------------------------
  .u            Q | Collect N, starting with the input, with each succussive N defined by the following until a result is repeated:
    +         tN  |  Prepend to the tail of N:
       [.*hN      |   N if N is a list
     .x     [)    |   or the empty list if N is not a list
lM                | Convert each element to its length
```
]


[Question]
      [
A *run ascending list* is a list such that runs of consecutive equal elements are strictly increasing in length. For example `[1,1,2,2,1,1,1]` can be split into three runs `[[1,1],[2,2],[1,1,1]]` with lengths `[2,2,3]`, since two runs are the same length this is **not** a run ascending list. Similarly `[2,2,1,3,3,3]` is not run ascending since the second run (`[1]`) is shorter than the first (`[2,2]`). `[4,4,0,0,0,0,3,3,3,3,3]` is run ascending since the three runs strictly increase in length.
An interesting challenge is to figure out for a particular set of symbols whether they can be arranged into a run ascending list. Of course the values of the individual symbols don't matter. It just matters how many of each there are.
In this challenge you will be given a list of \$n\$ positive integers, \$x\_i\$, as input. Your task is to determine if a run ascending list can be made from the numbers \$1\$ to \$n\$ with each number \$k\$ appearing *exactly* \$x\_k\$ times.
For example if the input is `[4,4,7]` it means you must determine if a run ascending list can be made with four 1s, four 2s and seven 3s. The answer is yes:
```
[1, 3,3, 1,1,1, 2,2,2,2, 3,3,3,3,3]
```
If the input is `[9,9,1]` it means you must try to find a run ascending list made of nine 1s, nine 2s and one 3. This cannot be done. It must start with the single `3` since that run can only be 1 long. Then the 1s and 2s must alternate to the end, since each run must larger than the previous, there must be more of whichever number goes last.
## Rules
You should take as input a non-empty list of positive integers. You should output one of two distinct values. One if a run ascending list can be made the other if it cannot.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
## Testcases
Inputs that cannot make a run ascending list
```
[2,2]
[40,40]
[40,40,1]
[4,4,3]
[3,3,20]
[3,3,3,3]
```
Inputs that can make a run ascending list
```
[1]
[10]
[6,7]
[7,6]
[4,4,2]
[4,4,7]
[4,4,8]
```

[Answer]
# [Python 3](https://docs.python.org/3/), 106 bytes
```
def f(a,n=-1,x=0):a[n]-=x;return~-any(a)^any(f(1*a,i,j+1)for i,k in enumerate(a)for j in range(x,k)if i-n)
```
[Try it online!](https://tio.run/##NY3BboMwDIbvfQofk81IhKAydeLYXnfZDTEp25w2pQ3IChtc9uosYezi79fn3/Iwh0vv9bJ8kgUrDPo6UzjVuTyYxrdZPT0zhZH9T2b8LIx8S7BCPRh0eH1U0vYMDjtwHsiPd2ITKPaSvibJxp9JTNhJZ8FlXi7fF3cjeOWRDjuAwHMCxO4ANdCXuYkYxyCkXP3Azof4MsrV0PRBQ4Djy@nI3PPf8TuT6ZamwKLdNWWOZf5PVClhiTpSo8Yi34JeVVqrpPZYxVnhfusXG6uNT@0v "Python 3 – Try It Online")
Brute force search. Recursively subtracts a strictly increasing value from every index in the input, as long as it is not equal to the prviously picked index. This continues until all values in the input are zero or the options to continue are exhausted.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āsÅΓœεÅγü›P}à
```
Brute-force approach, so extremely slow.
[Try it online](https://tio.run/##yy9OTMpM/f//SGPx4dZzk49OPrcVSG8@vOdRw66A2sML/v@PNtIxigUA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I43Fh1vPTT46@dxWIL358J5HDbsCag8v@K/zPzraSMcoVifaWMcYSBrqQHhAEsw3htAK0YYgQYgCsDCIbwJmm4AVGukYQjWYAOViAQ).
**Explanation:**
```
ā           # Push a list in the range [1, (implicit) input-length]
 s          # Swap so the input-list is at the top
  ÅΓ        # Run-length decode using the two lists
    œ       # Get all permutations of this list
     ε      # Map over each permutation:
      Åγ    #  Run-length encode the list, pushing the values and counts as two
            #  separated lists to the stack
        ü›P #  Check if this counts-list is strictly increasing:
        ü   #   For each overlapping pair of the counts-list:
         ›  #    Check if the first is larger than the second
          P #   Product to check if all of them are truthy
            #   (or if the list is empty after the overlapping pairs builtin,
            #   which means the counts-list only contains a single value)
     }à     # After the map: max to check if any of them is truthy
            # (which is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
{igᵗj₍}ᶠcpḅlᵐ<₁
```
[Try it online!](https://tio.run/##ATAAz/9icmFjaHlsb2cy//97aWfhtZdq4oKNfeG2oGNw4biFbOG1kDzigoH//1s0LDQsMl0 "Brachylog – Try It Online")
Times out on most of the test cases. I believe the algorithm is something like \$O(S!)\$, where \$S\$ is the sum of the input list.
### Explanation
```
{igᵗj₍}ᶠcpḅlᵐ<₁
{     }ᶠ         Find all ways to satisfy this predicate:
 i                 [E, I] pair where E is an element of the input and I is its index
  gᵗ               Turn that into [E, [I]]
    j₍             Concatenate [I] to itself E times
                 Result: a list of lists like [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2]]
        c        Concatenate those lists into one big list
         p       Consider some permutation of that list
          ḅ      Break it into blocks (i.e. runs of the same value)
           lᵐ    Take the length of each block
             <₁  Assert that the list of lengths is strictly increasing
```
[Answer]
# JavaScript (ES6), 84 bytes
Returns \$0\$ or \$1\$.
```
f=(a,i=0,p,g)=>a.some((v,j)=>v&&(g=_=>p!=j&v>i&&f(a,v,j,a[j]-=v)|g(a[j]+=v--))())|!g
```
[Try it online!](https://tio.run/##dY7LDoIwEEX3/gWb0sYp4RVwU5Z@gTskpkGoNEgJYBMT/h1r3GhsdzPnzONKrvlcT9240EFdm21rGebQsRBGEIQVPJjVvcFYgzSdRggLdmHF6DGJdNEh1JpxI4GXsqJMk1Xgd7lnmlJCMCGrJ7ZaDbPqm6BXAvvlkffzs/LJ7hu3uIwhrsgfTUNIQxeHyGYghcTCE0ggDh0i@az8KP88lKfpsdxsaW2fI9v1DHILzSFzRI8dPHfwg@HbCw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (             // f is a recursive function taking:
  a,              //   a[] = input array
  i = 0,          //   i = previous run length
  p,              //   p = previous index
  g               //   g = variable used to store a local
                  //       helper function and as a flag
) =>              //
a.some((v, j) =>  // for each value v at position j in a[]:
  v && (          //   abort if v = 0
  g = _ =>        //   g is a helper function which ignores its argument
  p != j &        //     if the index is not equal to the previous one
  v > i &&        //     and v is greater than the previous run length:
    f(            //       do a recursive call to f:
      a,          //         pass a[]
      v,          //         update i to v
      j,          //         update p to j
      a[j] -= v   //         subtract v from a[j]
    ) |           //       end of recursive call
    g(            //       do a recursive call to g:
      a[j] += v-- //         restore a[j] and decrement v
    )             //       end of recursive call
  )()             //   initial call to g
) |               // end of some()
!g                // success if some() is truthy or g = 0,
                  // which means that a[] is now filled with 0's
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
żZødṖƛĠvL2lvƒ>A;G
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvFrDuGThuZbGm8SgdkwybHbGkj5BO0ciLCIiLCJbMSwyXSJd)
Port of 05AB1E. ~~`vw` and `f` are only needed due to [a bug](https://github.com/Vyxal/Vyxal/issues/995), and `ƒ∴` is needed instead of `G` due to [another bug](https://github.com/Vyxal/Vyxal/issues/997).~~ Bugs fixed.
[Could be 13 bytes](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvMO44biK4bmWxpvDuMSWwqhwPkE7RyIsIiIsIlsxLDJdIl0=), but, well, this challenge is what inspired me to create all those new builtins, so, I guess it doesn't count.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
{+.bxj.*}wiFLr@{gw)-]qU_qsom&}ay
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@L9aWy@pIktPq7Y8082nyKE6vVxTN7YwNL6wOD9XrTax8v//aBMdEx2jWAA "Burlesque – Try It Online")
Drastically inefficient brute force
```
{    # Generate initial list, e.g. for [2,2] builds {1 1 2 2}
 +.  # Increment (indexed from zero)
 bx  # Box
 j.* # Product
}wi  # Zip with indices and map
FL   # Flatten (strictly builds {{{1}{1}}{{2}{2}}})
r@   # All possible permutations (even repeated ones)
{
 gw  # Group like with length (count)
 )-] # Get length (count)
 qU_ # Quoted Unique
 qso # Quoted sorted
 m&  # Make and (is sorted and unique)
}ay  # Any
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
⊞υ⟦±¹θ⁰⟧ＦυＦ…⊟ι⌈§ι¹ＦＬθＦ∧⁻λ§ι⁰›§§ι¹λκ⊞υ⟦λＥ§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧⬤υ⌈⊟ι
```
[Try it online!](https://tio.run/##ZY/NCsIwEITvPkWOG4hgQfDgqQcRQaV4LT2Edm2D6damifTtY2JV/AmEsGHmm52ykabspPY@c0MDTrD8iLW0CAkXrBdsUfD17NwZBo6zx3uSVCNk3RVUkBzkqFrXQmp3VOEISrCE86d0j1TbBvrXnFIFB0VuAC3Yh2PBA2lrMOSaN@mLKJgO9xLJ70V1TL/@6iY@BX4I2/RO6gHGyb6j0mCLZLGCiPr7il0zo8hCqnXMeLWb2oaz9j7Pl2IpVkXh5zd9Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs nothing if a run ascending list can be made, `-` if not. Explanation: Inspired by @Jitse's Python answer.
```
⊞υ⟦±¹θ⁰⟧Ｆυ
```
Start a search with a previous run of `0` `-1`s and the original input still to process.
```
Ｆ…⊟ι⌈§ι¹
```
Loop over potential next run lengths.
```
ＦＬθ
```
Loop over potential next run values.
```
Ｆ∧⁻λ§ι⁰›§§ι¹λκ
```
If this is a new run and there are enough of the value remaining, then...
```
⊞υ⟦λＥ§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧
```
... add a new search entry of the run and updated array of counts.
```
⬤υ⌈⊟ι
```
See whether an array of all zeros was achieved.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
¬ΛȯV≤mLgP`ṘN
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNedmn1gf9qhzSa5PekDCw50z/P4b6hjpGNqmJeYUpyqA2EZIbGPbkqJSCNMEzPz/PzoarCFWB0wbQWljKG0SGwsA "Husk – Try It Online")
Brute force approach, times out for even moderate inputs. TIO link includes a set of very short true & false inputs.
```
¬ΛȯV≤mLgP`ṘN
           N  # for each integer 1..N
         `Ṙ   # replicate it the number of times in the input array;
        P     # now get all permutations of this list
 Λȯ           # and output zero if none of these satisfy:
   V          #   there is at least one pair of adjacent elemnts
    ≤         #   for which the left is smaller or equal to the right,
     mL       #   for the lengths of each
       g      #   group of equal elements;
              # (at this point truthy (nonzero) means a run-ascending list cannot be made,
              # falsy (zero) means a run-ascending list can be made)
¬             # so NOT the result to get a consistent output
              # 1=can be made, 0=cannot be made
```
(Omit the final `¬` for falsy & truthy-but-non-consistent output)
]