title: Number-only switch

text:
# Question
Title: Number-only switch
Write a function that takes an ASCII-printable-only (all charcodes ∈ \[32..126\]) string input `x` and provides an ASCII-printable-only output string `f(x)`, such that for every x

* `f(f(x))=x`
* `f(x)` is all-numeric (all charcodes ∈ \[48..57\]) iff `x` is not all-numeric

You can assume input is not empty and never provide empty output, or treat empty input as "all-numeric". Shortest code in each language wins.

Some examples of "not all-numeric":

```
abc
a1b2c3
a333333

```

# Answer
> 9 votes
# Vyxal -Ṡ flag, ~~41~~ ~~40~~ ~~34~~ 30 bytes

```
λ[±[‹n⌊₇τCṅkQ↔|fC₇βnṪ]:xn≠ß_;†

```

Try it Online! or verify all test cases

This uses two injections to generate a bijection. The first injection \\$f\\$ from numeric to non-numeric is  (append "-") and the second \\$g\\$ from non-numeric to numeric is `fC₇β` (get ascii values and convert from base 128). It is similar to https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein\_theorem#Proof but we make sure that there are no doubly infinite sequences or cyclic sequences by carefully choosing \\$f\\$ and \\$g\\$.

It works reasonably well for large inputs.

The simplified algorithm is the following:

```
def encode(S):
    if S is numeric:
        if there is a non-numeric T such that encode(T) == S:
            return T
        else:
            return f(S)
    else:
        if there is a numeric T such that encode(T) == S:
            return T
        else:
            return g(S)

```

Full explanation:

```
λ             # start a lambda
 [            # base case for recursion, only continue if the argument is not empty
  ±           # is the argument numeric?
   [          # if it is:

```

Compute `f(S)` and find the only candidate for `T`

```
‹             #   append "-"
 n            #   push argument
  ⌊           #   convert string to number
   ₇τ         #   convert to base 128
     C        #   chr(x)
      ṅ       #   join by nothing
       kQ↔    #   only keep printable ASCII
|             # else:

```

Compute `g(S)` and find the only candidate for T

```
f             #   list of characters
 C            #   ord(x)
  ₇β          #   convert from base 128
    n         #   push argument
     Ṫ        #   remove tail
]             # end if

:             # duplicate T candidate
 x            # compute encode(T)
  n≠          # is not equal to argument
    ß_        # if true pop
      ;†      # end lambda and call it

```

# Answer
> 6 votes
# 05AB1E, ~~37~~ ~~36~~ ~~33~~ 32 bytes

```
žQ∞δã˜Dʒ9ÝKĀ}sþI9ÝKĀis}ÅΔI‚1ìË}è

```

Try it online or verify some test cases (times out for most test cases).

**Explanation:**

Pairs all *all-numeric* strings with all *ASCII-printable-only-not-all-numeric* strings. If the input is all-numeric, outputs the corresponding ASCII-printable-only-not-all-numeric, or vice-versa if not.

```
žQ        # Push a builtin string of all printable ASCII
  ∞       # Push an infinite positive list: [1,2,3,...]
   δ      # Apply double-vectorized:
    ã     #  Cartesian power
     ˜    # Flatten this infinite list of lists
D         # Duplicate it
 ʒ    }   # Filter it by:
  9Ý      #  Push list [0,1,2,3,4,5,6,7,8,9]
    K     #  Remove all those digits from the string
     Ā    #  Python-style truthify to check if anything remains (aka NOT all-numeric)
          #  (Note: `d≠` or `DþÊ` wouldn't work here for test cases like 0.1 or +1)
s         # Swap, so the other infinite list is at the top again
 þ        # Only keep all all-numeric values
I         # Push the input
 9ÝKĀi }  # Pop, and if it's NOT all-numeric (with a similar check as in the filter):
      s   #  Swap the two infinite lists on the stack
ÅΔ     }  # Pop the top list, and find the first index that's truthy for:
  I‚      #  Pair the current value with the input
    1ì    #  Prepend a 1 before each (workaround, since "02"=="+2"=="2.0"==2 in 05AB1E)
      Ë   #  Check that both values in the pair are the same
        è # Get the value at the found index from the other infinite list
          # (after which the result is output implicitly)

```

See all pairs in the infinite lists.

# Answer
> 5 votes
# Haskell, 153 bytes

```
c=(head.).filter
d=['0'..'9']
e=(mapM id=<<).(<$>[0..]).flip replicate
f x=c(/=x).c(elem x).zipWith((.pure).(:))(e d)$filter(any(`notElem`d))$e[' '..'~']

```

Try it online!

enumerates all all-decimals and all some-non-decimal strings and pairs them for lookup to bypass "0001"→base94(1)→"1" or n→all-decimals-base94(n)→base94(base94(n)) mismatches

# Answer
> 3 votes
# , ~~172~~ 168 bytes

*Edit: -4 bytes thanks to pajonk*

```
\(x,`?`=unlist,m=match){d=?Map(f<-\(n)if(n)?lapply(intToUtf8(32:126,T),paste0,f(n-1)),1:(2*nchar(x)))
a=d[e<-grepl("^\\d*$",d)]
`if`(i<-m(x,b<-d[!e],0),a[i],b[m(x,a)]

```

Attempt This Online! or Attempt a simpler version

**How? - ungolfed code**

```
switch=function(x){
    f=function(n)if(n)unlist(lapply(c(intToUtf8(32:126,T)),paste0,f(n-1)))
        # f is a recursive function that generates all 'words' of size n
    d=unlist(lapply(1:(2*nchar(x)),f))
        # d is the 'dictionary' of all words of size 1..n
        # using a max size of twice the length of input
    e=grepl("^[0-9]*$",d)
        # e is the indices of all-number words
    a=d[e]
        # a is the set of all-number words
    b=d[!e]
        # b is the set of mixed all-letter or number-letter words
    `if`(i<-match(x,b,0),a[i],b[match(x,a)])
        # if the input matches an all-number word, get its index i,
        # and return the mixed word at the corresponding index;
        # otherwise vice-versa
}

```

---
Tags: code-golf, open-ended-function, printable-ascii
---


# Question
Title: Surjection from one string to two strings
This is the inverse of negative seven's question.

Write a program or function which, given **any** single, possibly-empty string of printable ASCII (codes \\$\[32,126\]\\$) outputs or returns two strings of printable ASCII.

For any two ordered, possibly empty strings \\$s\_1\\$ and \\$s\_2\\$, there **must** be third string \\$s\_0\\$, which input to your program, outputs \\$s\_1\\$ and \\$s\_2\\$.

---

In other words, if \\$\mathbb S\\$ is the set of all ASCII strings (including the empty string):

\\$f\\$ is well-defined on \\$\mathbb S\\$: \\$(\forall s\in\mathbb S)(f(s)\in\mathbb S\times\mathbb S)\\$

\\$f\\$ is a surjection to \\$\mathbb S\times\mathbb S\\$: \\$(\forall s\_1,s\_2\in\mathbb S)(\exists s\_0\in\mathbb S)(f(s\_0)=(s\_1,s\_2))\\$

## Test cases:

For each of these strings (surrounding «quotes» excluded), your output should be two strings:

```
«»
«hello world»
«'one' 'two' 'three' 'four'»
«"one" "two" "three" "four"»
«["one", "two", "three"]»
«; exit()»

```

For each of these pairs of strings, there must be at least one string you can provide to your program such that that pair is output (surrounding «quotes» excluded):

```
 s_1     |  s_2
---------|----------
«hello » | «world»
«hell»   | «o world»
«hello»  | « world»
« »      | «»
«»       | « »
«»       | « !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~»
«\r\n»   | «\r\n»

```

As always, you are encouraged to add test cases pertinent to your method.

## Rules:

* Input must be a single string/character array/byte array consisting of only ASCII characters.
* Output is *ordered*; \\$(a,b)\neq(b,a)\\$. Output can be any ordered structure in your language, or printed with a newline (LF or CR LF) separator and optional trailing newline.
* I/O must be consistent. If one case handles input as an argument and outputs to stdout with a trailing newline, all cases must handle input as an argument and output to stdout with a trailing newline.
* Standard loopholes are forbidden.
* This is , so shorter programs are better!

As a reminder, this is only a surjection, not a bijection: Your program/function will likely map many different strings to the same output.

# Answer
# Python 2, 42 bytes

```
lambda s:(s.split("1"+len(s)/2*"0")*2)[:2]

```

Try it online!

The inverse is:

```
def F(a,b):
    return a+"1"+len(a+b)*"0"+b

```

A tempting idea for the inverse is to encode the pair of input strings by putting some separator string in between them. That way, we can extract the pair by splitting on this separator. The issue is that the separator may appear in the inputs string.

We get around this by making the separator longer than the total length of both strings. We use `1` followed by a number of `0`'s equal to the number of characters in both strings. For example,

```
abc, defgh -> abc100000000defgh

```

Note that no matter how many 0's and 1's are in the two inputs, there's no way to get another copy of the separator to appear.

We can recover the separator from the combined string by using a number of zeroes equal to half its length rounded down. I had wanted to compute this as `10**_`, but Python's repr appends an annoying `L` to large numbers, which messes it up.

We need to the submission function still give two outputs when the input string doesn't contain the required separator. In this case, splitting just gives the original string, but we copy it twice to be compliant.

---

**Python 2, 35 bytes** (not working)

```
lambda s:s.split(s[:len(s)/3])[-2:]

```

Try it online!

This would work except it gives an error for the empty string. The idea is to have the inverse encode `a,b -> sep + a + sep + b`, where the separator `sep` has the same length as `a+b` so we can extract it as the first third of the string. A similar idea of putting the separator interspersed runs into the same issue.

---

**Python 2, 43 bytes**

```
lambda s:[s[i::2].lstrip()[1:]for i in 0,1]

```

Try it online!

The idea for encoding is to intersperse the two input strings with alternating characters. The problem there is that they may have different lengths. So, we pad them to the same length by prepending each one with some number of leading spaces then `|` (any non-space char will do). For example, `abcd, ef` goes to

```
|abcd
  |ef

```

This can be undone for each string by stripping off all leading spaces then removing the first character. Note that any spaces or `|` in the actual strings are left unharmed.

**Python 3.8 (pre-release), 44 bytes**

```
lambda s:(s[(i:=s.find('_'))+1:2*i],s[2*i:])

```

Try it online!

Inverse:

```
F=lambda a,b:(len(a)+1)*"?"+"_"+a+b

```

For instance, `F("ab","cdef") = ???_abcdef`. The number of symbols before the `_` tells us where to split the remainder -- it's one more than the length of the first string.

We need the submission not to error when there's no `_`, but this works out because Python's string `find` uses `-1` for missing, which still gives valid slices.
> 9 votes

# Answer
# Haskell, 38 bytes

```
f(' ':a:b)=(a:)<$>f b
f s=(drop 1s,"")

```

Try it online!

Not using built-in parsing.

---

**21 bytes (doesn't quite work)**

```
last.(("",""):).reads

```

Try it online!

(As pointed out by @benrg, this produces unprintable characters outside the valid range on some inputs like `"\1"` that decode to escape characters.)

The inverse is

```
g(a,b)=show a++b

```

This puts the first string in quotes, escaping any characters as needed, and appends the second string. This is undone by `reads`, which looks for a prefix that's a string representation of the correct type (here, string), reads it, and puts it in a pair with the remainder.

To make the function total, if this fails, we just return two empty strings. Note that `reads` only does lexing, not evaluation, so it won't mess up on weird inputs.

If we may output a singleton list of a two-string pair, we can save 3 bytes:

**18 bytes**

```
max[("","")].reads

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~53~~ 52 bytes

```
lambda s:(s.split('_x'+s.count('x')/2*'x')+[''])[:2]

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
g2÷°¡2∍

```

-1 byte thanks to *@Grimy*.

Try it online or verify all test cases.

**Inverse (4 bytes):**

```
Jg°ý

```

Try it online or verify all test cases.

Port of *@xnor*'s first Python 2 approach, so make sure to upvote him as well!!

**Explanation:**

```
g        # Get the length of the (implicit) input-string
 2÷      # Integer-divide it by 2
   °     # Take 10 to the power this
    ¡    # And split the (implicit) input-string by this integer
     2∍  # Extend this list to (or keep it at) size 2
         # (after which this pair is output implicitly as result)

J        # Join the strings in the (implicit) input-list together to a single string
 g       # Get the length of this
  °      # Take 10 the power this
   ý     # And join the strings of the (implicit) input-list with this as delimiter
         # (after which the resulting string is output implicitly as result)

```
> 3 votes

# Answer
# Retina 0.8.2, 33 bytes

```
^(("[^"]*")*),?
$1¶
%`^"|"("?)
$1

```

Try it online! Link includes test cases. Takes as input the output from my Charcoal answer to @negativeseven's question and outputs the two strings on separate lines. Explanation:

```
^(("[^"]*")*),?
$1¶

```

My Charcoal answer always outputs a number of quote-surrounded strings followed by a comma. Find that comma and split the strings there. If there's no comma, the split happens after the quote-surrounded strings, if any.

```
%`^"|"("?)
$1

```

Decode each string by deleting the first quote, one quote of each pair, and the last quote. (Assuming this is an encoded string, of course... otherwise this just deletes arbitrary quotes.)
> 2 votes

# Answer
# Ruby, 81 bytes

```
->s{s.match(/^(\d+)\.(.*)/m){|m|l=m[1].to_i;[m[2][0,l],m[2][l..-1]||'']}||['',s]}

```

Try it online!

I don't golf much in Ruby so this can surely be shortened -- tips appreciated.

Idea is to to provide a meta-prefix `<number>.rest of string` which will split "rest of string" at number. Strings without the meta-prefix just return `["", <original string>]`
> 2 votes

# Answer
# Retina 0.8.2, 17 bytes

```
^(.*)(.*)\1\1
$2¶

```

Try it online!

This parses the string as \\$xs\_1xxs\_2\\$ for the longest possible \\$x\\$ due to the greedy nature of regexes. We may choose \\$x = 10^{\max \\{|s\_1|, |s\_2|\\}}\\$ to ensure the desired parse.
> 2 votes

# Answer
# Haskell, 67 bytes

```
p""=["",""]
p(' ':c)="":p c
p('#':b:c)|h:t<-p c=(b:h):t
p c=p$'#':c

```

Try it online!
> 1 votes

# Answer
# Zsh, 37 bytes

```
a=("${(@Q)${(z)1}}")
<<<$a[1]'
'$a[2]

```

Try it online!

* `(z)` splits a string according to shell grammar
* `(Q)` removes quotes
* `(@)` prevents array joining in quotes
* `" "` are needed to preserve empty elements

Finally we print the first two strings with a quoted newline between them.
> 0 votes

---
Tags: code-golf, string, open-ended-function
---


# Question
Title: Third Stirling numbers of the second kind
\\$\left\\{ n \atop k \right\\}\\$ or \\$S(n, k)\\$ is a way of referring to the Stirling numbers of the second kind, the number of ways to partition a set of \\$n\\$ items into \\$k\\$ non-empty subsets. For example, to partition \\$\\{1,2,3,4\\}\\$ into \\$2\\$ non-empty subsets, we have

$$\begin{matrix} \\{\\{1\\},\\{2,3,4\\}\\} & \\{\\{2\\},\\{1,3,4\\}\\} & \\{\\{3\\},\\{1,2,4\\}\\} & \\{\\{4\\},\\{1,2,3\\}\\} \\ \\{\\{1,2\\},\\{3,4\\}\\} & \\{\\{1,3\\},\\{2,4\\}\\} & \\{\\{1,4\\},\\{2,3\\}\\} \end{matrix}$$

So \\$\left\\{ 4 \atop 2 \right\\} = S(4,2) = 7\\$

Here, we'll only be considering the sequence \\$\left\\{ n \atop 3 \right\\} = S(n, 3)\\$, or the ways to partition \\$n\\$ items into \\$3\\$ non-empty subsets. This is A000392. There is also the related sequence which ignores the three leading zeros (so is \\$1, 6, 25, 90, 301, ...\\$)\\${}^\*\\$.

This is a standard challenge, where you can choose which of the two related sequences to handle (leading zeros or not). Regardless of which sequence you choose, you should do one of the following:

* Take an integer \\$n\\$ and output the \\$n\\$th element of the sequence. This can be \\$0\\$ or \\$1\\$ indexed, your choice, and \\$n\\$'s minimum value will reflect this.
* Take a positive integer \\$n\\$ and output the first \\$n\\$ elements of the sequence
* Take no input and infinitely output the sequence

This is so the shortest code in bytes wins.

\\${}^\*\\$: I'm allowing either sequence, as handling the leading zeros can "fail" for some algorithms that have to compute empty sums

---

## Test cases

If you ignore the leading zeros, the first 20 elements are

```
1, 6, 25, 90, 301, 966, 3025, 9330, 28501, 86526, 261625, 788970, 2375101, 7141686, 21457825, 64439010, 193448101, 580606446, 1742343625, 5228079450

```

Otherwise, the first 20 elements are

```
0, 0, 0, 1, 6, 25, 90, 301, 966, 3025, 9330, 28501, 86526, 261625, 788970, 2375101, 7141686, 21457825, 64439010, 193448101

```

# Answer
# Jelly, 6 bytes

```
3Ḋ*)SI

```

Try it online!

*-1 byte thanks to Jonathan Allan*

1-indexed sequence without leading zeros. Uses the formula \\$\sum\_{k=1}^{n} 3^k - 2^k\\$.

## Explanation

```
3Ḋ*)SI Main monadic link
   )   For each k in the range [1..n]:
3Ḋ       Remove the first element from the range [1..3]
  *      Raise each to the power of k
    S  Sum (producing [sum(2^k), sum(3^k)])
     I Increments

```
> 11 votes

# Answer
# Jelly, 7 bytes

```
cþæ*2FS

```

Try it online!

Now that xigoi has outgolfed me, I thought I'd share my answer.

This outputs the \\$n\\$ term of the sequence without leading zeroes.

## How it works

We generate the matrix

$$\left\[\begin{matrix} \binom 1 1 & \binom 2 1 & \cdots & \binom n 1 \\ \binom 1 2 & \binom 2 2 & \cdots & \binom n 2 \\ \vdots & & \ddots & \vdots \\ \binom 1 n & \binom 2 n & \cdots & \binom n n \end{matrix}\right\]^2 = \left\[\begin{matrix} 1 & 2 & \cdots & n \\ 0 & 1 & \cdots & \frac {n(n-1)} 2 \\ \vdots & & \ddots & \vdots \\ 0 & 0 & \cdots & 1 \end{matrix}\right\]^2 = \left\[\begin{matrix} 1 & 4 & \cdots & \sum^n\_{i=1} i \binom n i \\ 0 & 1 & \cdots & \sum^n\_{i=1} \binom i 2\binom n i \\ \vdots & & \ddots & \vdots \\ 0 & 0 & \cdots & 1 \end{matrix}\right\]$$

We then calculate \\$A^2\\$ and get the sum of each element, by flattening and taking the total sum. As to *why* this works, I have no idea - I just discovered it after playing around with `þæ*` patterns in Jelly.

```
cþæ*2FS - Main link. Takes n on the left
 þ      - Generate an n x n matrix where each cell (i,j) is:
c       -   iCj (binomial choose)
  æ*2   - Matrix square
     FS - Flatten and sum

```
> 9 votes

# Answer
# , 23 bytes

```
3^(n=scan()+2)/2-2^n+.5

```

Try it online!

Outputs without the leading zeros, 0-indexed.

Uses formula from OEIS page: $$ a(n) = 9 \cdot 3^n/2 - 4 \cdot 2^n + 1/2 $$
> 8 votes

# Answer
# Alchemist, 76 bytes

```
_+0j->2c
b+0j->3d
0j+0_+0b->j
c+j+x->_+j
d+j->x+b+j
j+0c+0d->Out_x+Out_" "!b

```

Try it online!

Outputs nonzero values infinitely using the formula \\$S(n, 3) = \sum\_{k=1}^{n-2} (3^k - 2^k)\\$.

On TIO, this computes up to the 13th element (2375101) before timing out.
> 7 votes

# Answer
# Python 2, 24 bytes

```
lambda n:3**n/6-~-2**n/2

```

Try it online!

Formula from OEIS for \\$n\>0\\$:

$$ f(n) = \frac{1}{2}(3^{n-1}-2^n+1)$$
> 6 votes

# Answer
# APL (Dyalog Unicode), 14 bytes

Anonymous tacit prefix function using xnor's formula. 1-indexed.

```
2÷⍨1-2∘*-3*-∘1

```

Try it online!
> 6 votes

# Answer
# Jelly, 9 bytes

Port of xnor's answer, made/fixed and golfed with hyper-neutrino's and caird coinheringaahing's help.

```
’3*_2*$‘H

```

Try it online!

This doesn't handle leading zeroes.

```
’3*_2*$‘H
’         n-1
 3*       3^(n-1)
   _      From that, subtract
    2*$   2^n
       ‘  Increment that
        H Halve it

```
> 6 votes

# Answer
# Jelly, 12 bytes

```
3ẹ@þṗ¥ẠƇṢ€QL

```

Try it online!

A monadic link that takes \\$n\\$ as its argument and returns \\$a(n)\\$. This is longer and less efficient than the answers based on the OEIS formulae, but should work for any value of \\$k\\$ by varying the first number in the link from 3. Also, removing the `L` at the end yields the actual sets.

## Explanation

```
3    ¥       | Using 3 as the left argument and n as the right argument:
    ṗ        | - Cartesian power of 3 and n (call this x)
 ẹ@þ         | - Find indices of each of 1 to 3 in each of x
      ẠƇ     | Keep only those lists where all are non-empty
        Ṣ€   | Sort each list
          Q  | Unique
           L | Length

```
> 6 votes

# Answer
# Jelly, 9 bytes

Surely there is an eight or less out there...

```
1×Ɱ3$¡FQS

```

A full program that accepts a non-negative integer from STDIN and prints the result using the 0-indexed, no leading zeros option.

**Try it online!**

### How?

```
1×Ɱ3$¡FQS - Main Link: no arguments
1         - start with x=1
     ¡    - repeat this (read from STDIN) times:
    $     -   last two links as a monad, x=f(x):
   3      -     three
 ×Ɱ       -     map (across y in [1..3]) with multiplication
      FQS - flatten, deduplicate, sum -> sum of the set of integers encountered

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 15 bytes

```
#~StirlingS2~3&

```

Try it online!
> 5 votes

# Answer
# Scala, 132 bytes

```
n=>(for{i<-1 to n-1
j<-i+1 to n-1
p<-1.to(n).permutations}yield{Set(p.slice(0,i),p.slice(i,j),p.slice(j,n))map(_.toSet)}).toSet.size

```

Try it online!

Is it short? No. Is it efficient? No. Is it clever? No. Why did I make it? I...don't know. I'll try golfing it later, if possible.
> 5 votes

# Answer
# Rattle, 24 bytes

```
|s>-s=3e~s<=2e~sg1-~+/R1

```

Try it Online!

This is a port of xnor's Python answer into Rattle using this formula:

$$ f(n) = \frac{1}{2}(3^{n-1}-2^n+1)$$

# Explanation

```
|                          takes the user's input
 s                         saves the user's input (n) to memory slot 0
  >                        move pointer right
   -                       decrement user's input
    s                      save (n-1) to memory slot 1
     =3                    set the value on top of the stack to 3
       e~                  perform 3^(n-1)
         s                 save in memory slot 1
          <                move pointer left
           =2              set the value on top of the stack to 2
             e~            perform 2^(n)
               s           save in memory slot 0
                g1         get value from slot 1
                  -~       subtract value in slot 0
                    +      increment
                     /     divide by 2
                      R1   reformat as int (which is printed implicitly)

```
> 5 votes

# Answer
# C (gcc), 34 bytes

```
f(n){n=n<3?0:5*f(n-1)-6*f(n-2)+1;}

```

Try it online!

Inputs \\$0\\$-based \\$n\\$.
Returns \\$S(n,3)\\$.
Uses the formula: \\$a(n) = 5\cdot a(n-1) - 6\cdot a(n-2) + 1\\$, for \\$n \> 2\\$.
> 4 votes

# Answer
# Factor \+ `math.extras`, 18 bytes

```
[ 3 + 3 stirling ]

```

Ignoring leading zeroes. Zero-indexed. `stirling` is bugged in the build TIO uses. It was fixed about three years ago, so here's a picture of running it in the listener with a more recent build.
> 4 votes

# Answer
# Risky, 10 bytes

```
+0?+1+_0+0__!2?-+_{0

```

Try it online!

1-indexed sequence without leading zeros. Uses the formula \\$\sum\_{k=0}^{n} 3^k - 2^k\\$.

## Explanation

```
+ sum
0       range
?           n
+         +
1           1
+     copy-last
_
0           0
+         +
0           0
_   map
_
!           3
2         ^
?           k
-     -
+       2^
_           [k,n]
{         index
0           0

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 14 bytes

```
-/3 2⊥¨∘⊂1,⍴∘1

```

Try it online!

A function implementing the sum formula using base conversion:

$$ a(n) = \sum\_{k=0}^n \left( 3^k-2^k \right) = \sum\_{k=0}^n 3^k - \sum\_{k=0}^n 2^k = (\underbrace{1 \cdots 1}\_{n+1})\_3 - (\underbrace{1 \cdots 1}\_{n+1})\_2 $$

```
           ⍴∘1   ⍝ a vector of n 1's
         1,      ⍝ prepend an additional 1
        ⊂        ⍝ enclose in a length 1 list
  3 2⊥¨          ⍝ for each of 2 and 3 decode the vector from that base
-/               ⍝ reduce the result by subtraction

```

If we use a full program instead of a function, this and a port of caird's Jelly answer are 13 bytes:

`-/3 2⊥¨⊂1,⎕⍴1` and `+/∊+.×⍨∘.!⍨⍳⎕`
> 3 votes

# Answer
# 05AB1E, 8 bytes

Same approach as my APL answer.

```
$>и32SβÆ

```

Try it online!

```
$          # push 1 and input n
 >         # increment n
  и        # a list of n+1 1's
   32S     # push list [3, 2]
      β    # for each of those numbers, convert the list of 1's from that base
       Æ   # reduce by subtraction

```

The first three bytes could be `>Å1` instead: Try it online!

A few alternatives from 8 to 11 bytes:

```
o3I<mα>;       port of xnor's answer          Try it online!
32SILδmOÆ      the sum formula                Try it online!
o<·3ILmOα      sum(3^k, k=1..n)-(2^n-1)*2     Try it online!
Î>FNo-3Nm+     sum using a for loop           Try it online!
LDδcDøδ*˜O     port of caird's answer         Try it online!
3Å0λ5*₂6*->    a(n)=5*a(n-1)-6*a(n-2)+1       Try it online! (infinite sequence)

```
> 3 votes

# Answer
# Add++, 16 bytes

```
L,Rd3€^¦+$2€^¦+_

```

Try it online!

Frick you caird for making such a painful esolang (:p). Port of everyone's favourite Jelly answer by xigoi.

## Explained

```
L,Rd3€^¦+$2€^¦+_
L,               # make a lambda that:
  Rd             #   pushes the range [1, input] twice and
    3€^          #   raises 3 to the power of each item,
       ¦+        #   summing that list (can't use s to sum here because frick you caird)
         $2€^¦+  #   do the same with 2
               _ #   subtract the two items. The i flag automatically runs the lambda and implicitly outputs the result

```
> 3 votes

# Answer
# Vyxal `sr`, 6 bytes

```
ƛ23fe¯

```

Try it Online!

A port of xigoi's Jelly answer

## Explained

ƛ23fe¯
ƛ      # over the range [1, input] (call each item n)

 23f   #   the list [2, 3]
    e  #   ^ ** n
     ¯ #   deltas of ^
       # the s flag auto-sums the result
```
</code></pre>
> 2 votes

# Answer
# Charcoal, 12 bytes

```
ＩΣＥ⊕Ｎ⁻Ｘ³ιＸ²ι

```

Try it online! Link is to verbose version of code. Uses @xigoi's Risky formulation of @Nitrodon's formula. Explanation:

```
    Ｎ           Input integer
   ⊕            Incremented
  Ｅ             Map over implicit range
      Ｘ³ι       Power of 3
     ⁻          Subtract
         Ｘ²ι    Power of 2
 Σ              Sum
Ｉ               Cast to string
                Implicitly print

```

I tried porting a couple of the other formulae too but they weighed in at 14 bytes.
> 2 votes

# Answer
# Haskell, 21 bytes

```
s n=div(3^n-3*2^n+3)6

```

$$\left\\{n\atop3\right\\}=\frac{3^n-3!\left\\{n\atop2\right\\}-3\left\\{n\atop1\right\\}}{3!}=\frac{3^n-3!\frac{2^n-2}{2!}-3}{3!}=\frac{3^n-3(2^n-2)-3}{3!}=\frac{3^n-3\cdot2^n+6-3}{6}=\frac{3^n-3\cdot2^n+3}6$$

Try it online!
> 2 votes

# Answer
# PARI/GP, 17 bytes

```
n->(2^n-3^n\3)\-2

```

With leading zeros.

Attempt This Online!

---

# PARI/GP, 18 bytes

```
n->stirling(n,3,2)

```

With leading zeros.

Attempt This Online!

---

# PARI/GP, 14 bytes

```
n->-3^n\-2-2^n

```

Attempt This Online!

This gives the sequence `0, 0, 1, 6, 25, 90, 301, 966, ...`. I'm not sure if this is allowed.
> 1 votes

# Answer
# Japt `-mx`, 9 bytes

```
3p°U -2pU

```

Try it

```
3p°U -2pU     :Implicit map of each U in [0,input)
3p            :3 raised to the power of
  °U          :  U, prefix incremented
     -        :Subtract
      2pU     :2 raised to the power of U
              :Implicit output of sum of resulting array

```
> 0 votes

# Answer
# Pyt, 13 bytes

```
Đ1⇹«⇹⁻3⇹^⇹-⁺₂

```

Try it online!

Port of xnor's answer
> 0 votes

---
Tags: code-golf, math, sequence, set-partitions
---


title: Counting overlapping objects

text:
# Question
Title: Counting overlapping objects
Consider a NxN pixel grid with up to M objects drawn on it, either squares or diamonds:

square diamond

The objects may overlap, so recognition is hard. The task is to give the minimal possible **numbers of objects per shape** that can be "seen" in the picture and tell how many squares, how many diamonds, and how many objects with unknown shape there are.

You can find a reference algorithm that solves the problem **here**.

Here are some examples with their intended numbers (nsquare, ndiamond, nunknown). The examples with nunknown = 1 are those with pixels that may either come from a square or a diamond (highlighted in black, but not bearing any information that may be used).

The program with shortest mean runtime in terms of grid size N wins!

And this is a simple test case generator:

```
let N = 10

// initialize the grid
let grid = Array.from(Array(N), () => new Array(N));

// choose a random number of objects <= M
let n = Math.ceil(Math.random()*M)

// create objects
while (n-- > 0) {

    // choose random position, but not on the border of the grid
    var i = Math.ceil((N-2)*Math.random())
    var j = Math.ceil((N-2)*Math.random())

    if (Math.random() > 0.5) {
        // draw a square
        for (var k = -1; k <=1; k++) {
            for (var l = -1; l <=1; l++) {
                grid[i+k][j+l] = 1
            }
        }
    } else {
        // draw a diamond
        for (var k = -1; k <=1; k++) {
            for (var l = -1; l <=1; l++) {
                if (!(k && l)) {
                    grid[i+k][j+l] = 1
                }
            }
        }
    }
}

```

Some small test cases:

# Answer
# Haskell, O(2ⁿ)

```
import Data.Bits
import Data.List
listFromPair=uncurry((.pure).(:))
s`isSubsetOf`p=s.&.p==s
bsum=foldl(.|.)0::[Integer]->Integer
numbers n p=let
 w=[0..n-3]
 diamond=[1,n+0,n+1,n+2,2*n+1]
 square=diamond++[0,2,2*n,2*n+2]
 solutions=sortOn length$filter((p==).bsum)$subsequences$
   filter(`isSubsetOf`p)[bsum[bit(r*n+c+d)|d<-s]|r<-w,c<-w,s<-[diamond,square]]
 minlength=length$solutions!!0
 best=takeWhile((minlength==).length)solutions
 numb=map minimum.transpose$map(map length.listFromPair.partition((9==).popCount))best
 in numb++[minlength-sum numb]

```

Try it online!
> 2 votes

---
Tags: grid, counting, fastest-algorithm, pattern-matching
---


title: Fractional Unicode Bars

text:
# Question
Title: Fractional Unicode Bars
Your program should take as input a number `n` that is greater than 0 and output a bar composed of `n // 8` ▉ characters (U+2588), as well as a final character which should be one of ▉ ▊ ▋ ▌ ▍ ▎▏(U+2589 to U+258F) representing `n % 8`. If `n % 8` is 0, your program should not output any additional characters. This is difficult to explain well in text, so here are some examples:

```
Input: 8
Output: █
Input: 32
Output: ████
Input: 33
Output: ████▏
Input: 35
Output: ████▍
Input: 246
Output: ██████████████████████████████▊

```

This is , so shortest answer wins.

# Answer
# Excel (ms365), 56 bytes

Formula in `B1`:

```
=REPT("█",A1/8)&IF(MOD(A1,8),UNICHAR(9616-MOD(A1,8)),)

```
> 15 votes

# Answer
# Julia 0.7, ~~35~~ ~~32~~ 27 bytes

```
!n='▐'.-diff((0:8:n)∪n)

```

Try it online!

Generates a range from 0 to n with step 8, and n itself force-included. Then taking the `diff` produces our codepoint offsets, e.g. `35` gives `8 8 8 8 3`, etc. Returns character arrays.

Analogous solution in R:

# , ~~45~~ ~~44~~ 43 bytes

```
\(n)intToUtf8(9616-diff(c(0:(n/8-.1)*8,n)))

```

Attempt This Online!

Thanks to amelies and MarcMush for -3 and -5 on Julia and pajonk for -1 on R.
> 13 votes

# Answer
# Python 3, ~~43 41~~ 36 bytes

```
lambda n:~-n//8*'▉'+chr(9608-n%-8)

```

Try it online! (Fails for n=0)

* -2 thanks to 97.100.97.109
* -5 thanks to loopy walt

(Note: 9608 is the decimal value of 0x2588)
> 10 votes

# Answer
# x86-64 machine code, ~~18~~ 16 bytes

```
AB B8 88 25 00 00 83 EE 08 77 F5 29 F0 48 AB C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated UTF-32 string, and takes the number `n` in ESI. The starting point is after the first byte.

In assembly:

```
r:  stosd           # Write EAX to the string, advancing the pointer.
f:  mov eax, 0x2588 # (Start here) Set EAX to 0x2588.
    sub esi, 8      # Subtract 8 from the input number in ESI.
    ja r            # Jump back if the number was greater than 8.
    sub eax, esi    # Subtract ESI from EAX, increasing it by 0 to 7.
    stosq   # Write RAX (the 64-bit register containing EAX) to the string,
            #  advancing the pointer. Because it's little-endian,
            #  the first 32 bits are the value of EAX, and the next 32 bits are 0
            #  (as the high bits are zeroed when operating on only EAX)
            #  to add the null terminator.
    ret             # Return.

```
> 10 votes

# Answer
# Jelly, 8 bytes

```
s8Ẉ⁽"s_Ọ

```

A monadic Link that accepts a non-negative integer and yields a list of characters.

**Try it online!**

### How?

```
s8Ẉ⁽"s_Ọ - Link: integer, n   e.g. 17
 8       - eight
s        - split (implicit [1..n]) into chucks of length (8)
                                   [[1..8],[9..16],[17]]
  Ẉ      - length of each          [8,8,1]
   ⁽"s   - 9616
      _  - subtract (vectorises)   [9608,9608,9615]
       Ọ - cast to characters      ['█','█','▏']

```
> 10 votes

# Answer
# Factor, 66 65 64 46 bytes

```
[ [1,b] 8 group [ length ] map 9616 v-n vabs ]

```

Attempt This Online!

* -1 byte from Mama Fun Roll
* -1 more by taking an entirely different approach
* -18(!) by porting Jonathan Allan's amazing Jelly answer.
> 7 votes

# Answer
# JavaScript (Node.js), 50 bytes

*-2 thanks to @Neil*

```
f=n=>n?Buffer([226,150,144-(q=n>7?8:n)])+f(n-q):''

```

Try it online!

### How?

We use `Buffer()` to build the characters from their UTF-8 encodings.

For instance, the character with code point `9608` (0x2588) is generated with:

```
Buffer([226,150,136]) // 0xE2, 0x96, 0x88

```

That's a bit lengthy, but still shorter than the infamous `String.fromCharCode(9608)`.
> 4 votes

# Answer
# Charcoal, 14 bytes

```
⭆⪪×ψＮ⁸℅⁻⁹⁶¹⁶Ｌι

```

Try it online! Link is to verbose version of code. Explanation:

```
   ψ            Predefined variable null byte
  ×             Repeated by
    Ｎ           Input integer
 ⪪              Split into substrings of maximum length
     ⁸          Literal integer `8`
⭆               Map over substrings and join
             ι  Current substring
            Ｌ   Length
       ⁻        Subtract from
        ⁹⁶¹⁶    Literal integer `0x2590`
      ℅         Convert to Unicode

```
> 4 votes

# Answer
# sclin, 25 bytes

```
O>a8/`"len"map9616- _ c>S

```

Try it here! Port of @Jonathan Allan's clever Jelly answer!

For testing purposes:

```
[8 32 33 35 246] ( ; n>o ) map
O>a8/`"len"map9616- _ c>S

```

## Explanation

Prettified code:

```
O>a 8/` \len map 9616- _ c>S

```

Assuming input *n*.

* `O>a` range \[0, *n*)
* `8/`` chunk into lengths of max 8
* `\len map` get lengths of each chunk
* `9616- _` subtract from 9616
* `c>S` convert to fractional block char

---

# sclin, 38 bytes

```
8/%"█"rot ** >o""Q"9616- _ c>S >o"&#

```

Try it here! Outputs the bars.

For testing purposes:

```
[8 32 33 35 246] ( ; ""n>o ) map
8/%"█"rot ** >o""Q"9616- _ c>S >o"&#

```

## Explanation

Prettified code:

```
8/% "█" rot ** >o dup ( 9616- _ c>S >o ) &#

```
* `8/%` divmod by 8
* `"█" rot **` repeat  \
 times
* `>o` output
* `dup (...) &#` execute if \<mod part\> is truthy (i.e. greater than 0)...
    + `9616- _ c>S` convert to fractional block char
    + `>o` output
> 4 votes

# Answer
# Ruby, ~~46~~ 36 bytes

```
->n{?█*(n/8)<<(n%8>0?9616-n%8:"")}

```

Attempt This Online!

A whopping 10 bytes saved by G B.
> 4 votes

# Answer
# , ~~51~~ ~~49~~ 46 bytes

```
\(n)intToUtf8(9616-c(rep(8,n/8),if(b<-n%%8)b))

```

Attempt This Online!

Still not as golfy as Kirill L's approach, unfortunately...
> 4 votes

# Answer
# Vyxal, 12 bytes

```
ɾ8ẇvL9616εCṅ

```

Try it Online!

Yet another port of Jonathan Allan's Jelly answer.
> 4 votes

# Answer
# Mathematica, 59 bytes

```
FromCharacterCode[9616-Tr[1^#]&/@Range@#~Partition~UpTo@8]&

```

View it on Wolfram Cloud!
> 3 votes

# Answer
# ///, 73 bytes

```
/d/iii//ddii/█//ddi/▉//dd/▊//dii/▋//di/▌//d/▍//ii/▎//i/▏/

```

Try it online!

Input is a unary.
> 3 votes

# Answer
# Rust, 61 bytes

```
|n,r|{*r=[9608].repeat((!-n/8)as _);r.push((9615-!-n%8)as _)}

```

A `fn(i32,&mut Vec<u32>)`, where the first argument is `n`, and `r` is a mutable reference to a vector where the output will be stored.

Attempt This Online!
> 3 votes

# Answer
# Retina 0.8.2, 30 bytes

```
.+
$*
1{1,8}
$.&
T`8-1`▉-▏

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
1{1,8}
$.&

```

Convert groups of up to 8 to decimal.

```
T`8-1`▉-▏

```

Map digits to the appropriate Unicode character.
> 2 votes

# Answer
# Sequences, 30 bytes

```
iH8/nx$\▉$""Jfh8%H?9616h-VF:

```

Sequences was definitely not made for this!

**Explained:**

```
iH8/nx$\▉$""Jfh8%H?9616h-VF:
iH                            // Get an integer input and store in `h`
  8/                          // Divide by 8
    n                         // Convert to integer (floor)
     x$  $                    // This many times:
       \▉                     //   Push the string "▉"
                              // Implicitly put into a list
          ""J                 // Join by empty strings
             f                // Output with no newline
              h               // Push `h`
               8%H            // Mod by 8 and store in `h`
                  ?           // If this is truthy (h != 0)
                       h      //   Push `h`
                   9616 -     //   Subtract from 9616
                         V    //   Get chr of the result
                          F   //   Output with a newline
                           :  // Else: (do nothing)

```

In Sequences there is no way of multiplying an integer with a string, so we have to settle for making a list of that string, repeated, and then join it by an empty string.

Also, Sequences uses the 96 printable ASCII characters as its codepage, but because we have  in our code, we have to use UTF-8.
> 2 votes

# Answer
# 05AB1E, ~~14~~ ~~11~~ 10 bytes

```
L8ô€gŽb¶αç

```

Try it online! (I've put `J` for join in the footer, but apparently outputting a list of characters is ok)

* -3 thanks to Sʨɠɠan
* -1 thanks to Kevin Cruijssen

### Explained

```
L8ô€gŽb¶αç  # Implicit integer input          17
L           # Inclusive range                 [1, 2, ..., 17]
 8ô         # Split into groups of 8          [1, ..., 8], [9, ..., 16], [17]
   €g       # Length of each                  [8, 8, 1]
     Žb¶    # 9616
        α   # Absolute difference from 9616   [9608, 9608, 9615]
         ç  # chr of each                     ["█", "█", "▏"]
            # Implicit output

```
> 2 votes

# Answer
# Java 11, ~~58~~ ~~48~~ 39 bytes

```
n->"█".repeat(--n/8)+(char)(9615-n%8)

```

-9 bytes thanks to *@Neil*.

Doesn't support `n=0`.

Try it online.

**Explanation:**

```
n->                  // Method with integer parameter and String return-type
  "█".repeat(        //  Repeat this character
             --n/8)  //  `n-1` integer-divided by 8 times
                     //  (by first decreasing `n` by 1 with `--n`)
  +(char)            //  Append an integer casted to a character:
         (9615-n%8)  //   9615 minus (`n-1` modulo 8)

```
> 2 votes

# Answer
# Go, ~~91~~ ~~81~~ 73 bytes

```
func f(n int)(s string){
for;n>8;n-=8{s+="▉"}
s+=string(9616-n)
return}

```

Attempt This Online!

* -10 bytes by @jdt
* -8 bytes by @Neil
> 2 votes

# Answer
# Haskell, ~~44~~ 40 bytes

```
f n|n<9=[toEnum$9616-n]
f n='█':f(n-8)

```

Attempt This Online!

-4 bytes by ignoring `n=0`
> 2 votes

# Answer
# C (clang), ~~54~~ 50 bytes

-4 bytes thanks to @Neil!

```
f(*o,n){for(;n>8;n-=8)*o++=9608;*o++=9616-n;*o=0;}

```

Try it online!
> 2 votes

# Answer
# \>\<\>, 43 bytes

```
:8,:1%-v
v1-"█"$>:?!
>~{8%:"█"+$?!~}>o<

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 45 bytes

```
f=n=>n>8?'█'+f(n-8):Buffer([226,150,144-n])

```

Try it online!

52 bytes without `Buffer`:

```
f=n=>n>7?'█'+f(n-8):['▏▎▍▌▋▊▉'[n-1]]

```
> 2 votes

# Answer
# C (clang), ~~46~~ 44 bytes

```
f(*o,n){for(;*o=n>0;*o++=9608-(n<0)*n)n-=8;}

```

Try it online!

From jdt's solution, support 0
> 2 votes

# Answer
# jq, 43 bytes

```
[9616-((range(1;./8)|8),(.-1)%8+1)]|implode

```

Try it online!
> 1 votes

# Answer
# BQN, 23 bytes

```
@+9608+{>7?0∾-8;7-}

```

Try it at BQN REPL

```
@+9608+{>7?0∾-8;7-}
       {              }  # recursive function  with argument
        >7?             # if x is greater than 7
            0∾           #   prepend zero onto
              -8       #   result of recursive call with agument -8
                  ;      # otherwise
                   7-   #   7-
      +                  # now, add the result of this to
@                        #   the null character
 +9608                   #   +9608

```

We could use the literal character '▉' instead of `@+9608`, but this would prevent the code from being encoded with the BQN single byte character system, so the UTF8-encoded code would end-up longer.
> 1 votes

# Answer
# Thunno `J`, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
R8Ap.L9616_C

```

Attempt This Online!

Yet another port of Jonathan Allan's Jelly answer.
> 0 votes

---
Tags: code-golf, unicode
---


title: Fill in the next numbers

text:
# Question
Title: Fill in the next numbers
Given a list of integers, output a list where the \\$ i \\$th element of the list equals the first number in the input list which is \\$ \ge i \\$, until there are no such numbers.

For example, if the input is:

```
2 3 5 7 11

```

then we "expand" the sequence out to show where the gaps are:

```
_ 2 3 _ 5 _ 7 _ _ __ 11     # input
1     4   6   8 9 10        # gaps

```

Now we fill in the blanks with the next number that is in the sequence in each case:

```
2 2 3 5 5 7 7 11 11 11 11
1     4   6    8  9 10

```

This is the output.

## Test cases

```
[1]               -> [1]
[3]               -> [3, 3, 3]
[1, 2, 3]         -> [1, 2, 3]
[1, 3, 4, 9]      -> [1, 3, 3, 4, 9, 9, 9, 9, 9]
[2, 3, 5, 7, 11]  -> [2, 2, 3, 5, 5, 7, 7, 11, 11, 11, 11]

```

## Rules

# Answer
> 13 votes
# , 30 bytes

Or **\>=4.1, 23 bytes** by replacing the word `function` with a `\`.

```
function(x)rep(x,diff(c(0,x)))

```

Try it online!

# Answer
> 12 votes
# Python 3, 37 bytes (@Jitse)

```
f=lambda l=[],*L:l and[l]*l+f(*L)[l:]

```

Try it online!

### Original Python 3, 38 bytes

```
f=lambda l,*L:(l,)*l+(L and f(*L)[l:])

```

Try it online!

Takes the splatted input and returns a tuple.

### How?

This is entirely based on the observation that the first original number `k`, say, will occur `k` times in the output. Working back to front we can treat each number `k[n]` as if it were the first and at the next iteration `n-1` replace the `k[n-1]` excess copies of `k[n]` with copies of `k[n-1]`.

# Answer
> 8 votes
# BQN, 5 bytes

```
+`⁼/⊢

```

Try it at BQN online REPL

BQN has a lovely 'undo' modifier () which calculates the inverse of any function, where this is possible.
Here we use it with cumulative sum (`+`` ) to get the cumulative differences starting from zero.
After that we just need to replicate (`/`) the input values () this number of times.

```
   /    # Replicate the elements of
    ⊢   # the right-hand argument
        # by
  ⁼     # undo the
+`      # cumulative sum of
        # the right-hand argument

```

# Answer
> 6 votes
# Vyxal, 4 bytes

```
ẋ∩vg

```

Try it Online!

```
ẋ    # Repeat the numbers by themselves
     # [[2, 2], [3, 3, 3], [5, 5, 5, 5, 5]]
 ∩   # Transpose
     # [[2, 3, 5], [2, 3, 5], [3, 5], [5], [5]]
  vg # Get the minimum of each

```

# Answer
> 6 votes
# Ruby, 36 bytes

```
->l{x=0;l.flat_map{|a|[a]*(-x+x=a)}}

```

Try it online!

# Answer
> 6 votes
# PARI/GP, 35 bytes

```
a->vector(a[#a],n,[m|m<-a,m>=n][1])
```

Attempt This Online!

```
a->                                   Define a function with argument `a`
   vector(                        )   that returns a vector
          a[#a],                      whose length is the last term of `a`
                n,                    and the `n`th term
                  [m|m<-a,    ][1]    is the first `m` in `a` such that
                          m>=n        `m` is larger than `n`.

```

# Answer
> 5 votes
# JavaScript (Node.js), 40 bytes

```
a=>a.map(g=n=>n>o.push(n)&&g(n),o=[])&&o

```

Try it online!

# Answer
> 5 votes
# Python 3.8 (pre-release), 43 bytes

```
f=lambda n,i=2:n and[n[0]]+f(n[[i]>n:],i+1)

```

Try it online!

Thanks @dingledooper for -2 bytes.

# Answer
> 5 votes
# K (ngn/k), 6 bytes

```
(-':)#

```

Try it online!

## Explanation

```
(-':)#
(-':)  deltas
     # replicate

```

# Answer
> 4 votes
# Factor, 44 bytes

```
[ dup last iota [ '[ _ > ] find ] with map ]

```

Try it online!

Let \\$L\\$ be the last element of the input. Then map \\$\[0..L)\\$ to the first element of the input that is greater.

# Answer
> 3 votes
# APL+WIN, 13 bytes

Prompts for input

```
(-2-/0,v)/v←⎕

```

Try it online! Thanks to Dyalog APL Classic

# Answer
> 3 votes
# Halfwit, 7.5 bytes

```
MZ;RZMR[$

```

Try It Online!

I think I made it too minimalistic...

## Explanation

```
M ;       # Map over each value...
 Z        # Fill an array of length (itself) with (itself)
   R      # Reduce by (taking two lists)
    Z     # Zip
     M    # For each pair...
      R   # Reduce by...
       [  # If the first is truthy (nonzero)...
        $ # return it, otherwise return the other value

```

# Answer
> 3 votes
# Julia 1.0, 29 bytes

```
!x=[fill.(x,diff([0;x]))...;]

```

Try it online!

# Answer
> 3 votes
# MATL, 6 bytes

```
0yhdY"

```

Try it online!

Take a `diff` and `repelem` the input that many times (same as @pajonk's R answer among others).

I thought this sounded ideal for an `interp1` based answer, but that comes out to 16 bytes: `0ihttX>:IG1)5$Yn` Try it online!

# Answer
> 3 votes
# Octave, 26 bytes

```
@(v)repelem(v,diff([0,v]))

```

Ideone link (TIO's version of Octave doesn't seem to have `repelem`.)

This started off as seeing if I'd have better luck with `interp1` on Octave directly (than via MATL), but it's again longer here, at 45 bytes:

```
@(v,w=[0,v])interp1(w,w,1:max(v),'next',v(1))

```

Try it online!

(the `w=[0,v]` is because `interp1` doesn't like operating on single element vectors like the `[3]` testcase, wants at least two elements.)

# Answer
> 3 votes
# Pip, ~~13~~ 11 bytes

*-2 bytes by porting Neil's Charcoal answer because I was seriously overthinking things*

```
FngT Ui=Pn0

```

Takes input as separate command-line arguments; gives output as lines of stdout. Attempt This Online!

### Explanation

```
FngT Ui=Pn0
             ; i is 0, g is list of command-line args (implicit)
Fng          ; For each n in g:
   T         ;   Till
     Ui      ;   increment i
       =     ;   equals
        Pn   ;   print n:
          0  ;     No-op

```

# Answer
> 3 votes
# Haskell, ~~37~~ 34 bytes

```
f l=do(a,b)<-zip(0:l)l;b<$[a+1..b]

```

Try it online!

* Saved 3 Bytes thanks to @Unrelated String suggesting using do notation which reveals how emphatic Haskell is.

Old version

```
f l=(\(a,b)->b<$[a+1..b])=<<zip(0:l)l

```

# Answer
> 3 votes
# Desmos, 45 bytes

```
M=l.max
f(l)=[\{l<i:M,l\}.\min\for i=[1...M]]

```

Try It On Desmos!

Try It On Desmos! - Prettified

I feel like this could be a bit shorter, though I don't see it at the moment. I tried to take out the two uses of `l.max` but the strategies I tried didn't work. Also that piecewise expression is a bit annoying, though I don't see a shorter way (it causes me to add `\`'s everywhere in the list comprehension. Without the `\`'s the code won't work.).

# Answer
> 3 votes
# HBL, 9 bytes

```
-(2*(<1.?)(2-.(10.

```

The online interpreter doesn't support `zip-with` yet, but here's a version with a hacked-together reimplementation of `zip-with` on the first line: Try it!

### Explanation

```
-(2*(<1.?)(2-.(10.
          (2       )   Zip
            -          with the subtraction function:
             .          The input list, and
              (1  )     Cons
                0        0 to
                 .       the input list
                       Result: pairwise differences
    (<   )             For each item in
       .               the input list:
      1                 cons it to
        ?               nil
                       Result: input list but with each number in a singleton list
 (2                 )  Zip those two lists
   *                   with the list-repetition function
                       Result: for each n in the input list, a length-n list of n's
-                      Flatten

```

# Answer
> 2 votes
# Jelly, 4 bytes

```
xŻI$

```

A monadic Link that accepts a strictly increasing list of positive integers and yields a non-strictly increasing list of positive integers.

**Try it online!**

### How?

If the input is `A=[a1, a2, a3, ...]` then the output needs to be `a1` `a1`s followed by `a2-a1` `a2`s then `a3-a2` `a2s` etc.

```
xŻI$ - Link: strictly increasing list of positive integers, A
   $ - last two links as a monad - f(A=[a1, a2, a3, ...]):
 Ż   -   prepend a zero -> [0, a1, a2, a3, ...]
  I  -   incremental differences -> [a1, a2-a1, a3-a2, ...]
x    - times (vectorises) -> [a1, ..., a1, a2, ..., a2, a3, ...]

```

# Answer
> 2 votes
# Perl 5, 39 bytes

```
sub{$l=0;map{($_)x($l+=$r=$_-$l,$r)}@_}

```

Try it online!

# Answer
> 2 votes
# , 41 bytes

```
function(x)x[cumsum(y<-1:rev(x)%in%x)+!y]

```

Try it online!

Quite a lot longer than pajonk's answer, but a nice little bit of index calculation all the same.

This ports to other matrix languages such as, for instance, MATL, but it's longer than the `diff` approach there as well.

# Answer
> 2 votes
# Arturo, 42 bytes

```
$[a][map 1..max a'x[min select a'y[y>=x]]]

```

Try it

```
$[a][                 ; a function taking an argument a
  map 1..max a'x[     ; map over the range 1..max(a) and assign current value to x
    min select a'y[   ; select the smallest number in a that...
      y>=x            ; is greater than or equal to x
    ]                 ; end select
  ]                   ; end map
]                     ; end function

```

# Answer
> 2 votes
# JavaScript (Node.js), 38 bytes

```
a=>a.map(g=n=>n>++i?[n,g(n)]:n,i=0)+''

```

Try it online!

# Answer
> 1 votes
# Jelly, 4 bytes

```
x)o/

```

Try it online!

Shamelessly sandbox sniped, but I didn't start it :P

```
 )      For each element of the input, as a monadic chain:
x       repeat it by itself.
  o/    Reduce the resulting list of lists by logical OR.

```

# Answer
> 1 votes
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

```
Å1*ζ€ß

```

-1 byte porting *@emanresuA*'s Vyxal answer

Try it online or verify all test cases.

**Original ~~8~~ 7 bytes answer:**

```
0š¥Å1*˜

```

Try it online or verify all test cases.

**Explanation:**

```
         #  e.g. input=[2,3,5]

Å1       # Map each value in the (implicit) input-list to that many 1s
         #  → [[1,1],[1,1,1],[1,1,1,1,1]]
 *       # Multiply each to the (implicit) input-list at the same positions
         #  → [[2,2],[3,3,3],[5,5,5,5,5]]
  ζ      # Zip/transpose; swapping rows/columns, using " " as filler
         #  → [[2,3,5],[2,3,5],[" ",3,5],[" "," ",5],[" "," ",5]]
   €ß    # Get the minimum of each inner list, ignoring the " "
         #  → [2,2,3,5,5]
         # (after which the resulting list is output implicitly)

0š       # Prepend a 0 to the (implicit) input-list
         #  → [0,2,3,5]
  ¥      # Pop and push its deltas/forward-differences
         #  → [2,1,2]
   Å1*   # Similar as above
         #  → [[2,2],[3],[5,5]]
      ˜  # Flatten this list of lists
         #  → [2,2,3,5,5]
         # (after which the resulting list is output implicitly)

```

# Answer
> 1 votes
# Python 3.8 (pre-release), 75 bytes

```
def f(a):
 s=[i:=(c:=a[-1])]
 while i:=i-1:s=[c:=[c,i][i in a]]+s
 print(s)

```

Try it online!

Ungolfed:

```
def fill_numbers(original):
    current_number = last_valid = original[-1]
    result = [original[-1]]
    while current_number-1 > 0:
        current_number -= 1
        if current_number in original:
            last_valid = current_number
        result = [last_valid] + result
    print(result)

```

# Answer
> 1 votes
# Pyth, 9 bytes

```
hM.Tm*d]d

```

Try it online!

# Answer
> 1 votes
# Charcoal, 9 bytes

```
ＦＡＷ‹ⅉι⟦Ｉι

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＡ

```

Loop over the input list.

```
Ｗ‹ⅉι

```

Repeat until the appropriate line is reached...

```
⟦Ｉι

```

... output the current value on its own line.

# Answer
> 1 votes
# PHP, 71 bytes

```
$n=[];for($i=max($a);$i;$i--){$n=[in_array($i,$a)?$h=$i:$h??$i,...$n];}

```

Try it online!

Ungolfed:

```
$n = [];
for ($i = max($a); $i; $i--) {
  $n = [in_array($i, $a) ? $h = $i : $h ?? $i, ...$n];
}

```

---
Tags: code-golf, number, array
---


# Question
Title: Remove duplicates from my academic transcript
Consider a list of subject, grade pairs. E.g.

```
[("Latin", "A"),  ("French", "A*"),  ("Math", "B"), ("Latin", "A*")]

```

The task is to return the same list but with each subject given at most once. Where a subject occurred more than once originally, the returned list should have the highest grade for that subject.

Using the UK system, "A\*" is a better grade than "A" and of course "A" is better than "B" etc. Only "A" can be followed by an asterisk.

The output for this case should be:

```
[("Latin", "A*"),  ("French", "A*"),  ("Math", "B")]

```

Another example:

```
[("Latin", "A*"),  ("French", "A*"),  ("Math", "B"), ("French", "A*"), ("Math", "C")]

```

The output should be:

```
[("Latin", "A*"),  ("French", "A*"),  ("Math", "B")]

```

Your returned output list can be in any order you like.

This is , so the shortest code in bytes wins.

Languages I am hoping for:

* Python, because I wrote a terrible solution in python which inspired this question. **Done**.
* C. Because real men/women code in C when it makes no sense for the problem at hand. **Done**.
* Julia. Because it's an awesome language.

# Input assumptions

You can assume there are no more than 10 subject/grade pairs, the input is printable ASCII and there are no spaces within the subject names.

# Answer
> 8 votes
# Vyxal, ~~9~~ 8 bytes

```
⁽hġ‡tṘv∵

```

Try it Online!

Sort by the reverse of each grade, group by subject, best of each subject group

*-1 thanks to emanresuA*

## Explained

```
⁽hġ‡tṘv∵
⁽hġ       # Group subjects by their subject
      v∵  # Get the maximum of each group by
   ‡tṘ    # Reversed grade.

```

# Answer
> 8 votes
# Haskell, 58 bytes

```
import Data.List
s=nubBy((.fst).(==).fst).sortOn(last.snd)

```

Try it online!

# Haskell, 77 bytes

```
import Data.List
(c?f)a=c(f a).f
s=nubBy((==)?fst).sortBy(compare?(last.snd))

```

Try it online!

# Haskell, 84 bytes

```
import Data.List;import Data.Function
s=nubBy(on(==)fst).sortBy(on compare$last.snd)

```

Try it online!

# Haskell, 97 bytes

```
import Data.List;import Data.Function
g"A*"="@";g s=s
s=nubBy(on(==)fst).sortBy(on compare$g.snd)

```

Try it online!

# Answer
> 8 votes
# Python, 52 bytes

```
lambda x:dict(sorted(x,key=lambda n:n[1][~0])[::-1])

```

is there a way to golf the list reversal?

Attempt This Online!

# Answer
> 7 votes
# Elm, 82 bytes

```
import Dict
List.sortBy(Tuple.second>>String.reverse)>>List.reverse>>Dict.fromList

```

Takes a list and returns a dict.

`>>` is function composition in the reversed direction: `f>>g` in Elm is `g.f` in Haskell.

According to the source code of Elm's core package, `Dict.fromList` will keep the last value when there are duplicate keys.

You can try it here. Here is a full test program:

```
import Html exposing (text)

import Dict
f=List.sortBy(Tuple.second>>String.reverse)>>List.reverse>>Dict.fromList

main =
  [("Latin", "A*"),  ("French", "B"),  ("Math", "A"), ("French", "A*"), ("Math", "C")]
  |> f
  |> Debug.toString
  |> text

```

# Answer
> 6 votes
# Jelly, ~~10~~ ~~9~~ ~~7~~ 5 bytes

```
ZḢ«/ƙ

```

Try it online!

```
    ƙ    Group pairs by
ZḢ       their first elements,
    ƙ    and for each group
   /     reduce by
  «      recursively vectorizing minimum.

```

The vectorizing minimum leaves the shared subject name unchanged while taking the minimum of the letter grades, and the vectorization mechanism's length mismatch handling adds an asterisk if any of the grades for that subject has an asterisk.

# Answer
> 6 votes
# Factor \+ `sets.extras`, ~~65 49~~ 47 bytes

```
[ [ last last ] sort-with [ first ] unique-by ]

```

Attempt This Online!

* `[ last last ] sort-with` Sort the input by the last character of each grade.
* `[ first ] unique-by` Retain every entry that has a subject that has not been encountered before.

# Answer
> 5 votes
# Charcoal, 30 bytes

```
≔⦃⦄ηＦθＦ‹⮌§ι¹⮌∨§η§ι⁰Z§≔η§ι⁰§ι¹η

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
≔⦃⦄η

```

Start with no grades.

```
Ｆθ

```

Loop over the input grades.

```
Ｆ‹⮌§ι¹⮌∨§η§ι⁰Z

```

If the reversed grade is less than the subject's reversed grade so far or `Z` if there is no grade yet, then...

```
§≔η§ι⁰§ι¹

```

... update the grade for that subject.

```
η

```

Output all of the grades in Python `dict` format.

# Answer
> 5 votes
# Japt, ~~9~~ 7 (6?) bytes

The second `Ô` could be removed if we could output the pairs in reverse order.

```
üÎËñÔÎÔ

```

Try it

```
üÎËñÔÎÔ     :Implicit input of 2D array
ü           :Group & sort by
 Î          :  First element
  Ë         :Map
   ñ        :  Sort by
    Ô       :    Reverse (mutating the arrays)
     Î      :  First element
            :  Reverse

```

---

## 6 bytes

I *think* this works but it needs more testing.

```
üÎËñÍÎ

```

Try it

# Answer
> 4 votes
# JavaScript (Node.js), 42 bytes

```
x=>x.sort().filter(v=>[v[0]!=x,x=v[0]][0])

```

Try it online!

Requiring an extra empty slot after each pair, which looks not that elegant

# JavaScript (Node.js), 55 bytes

```
x=>x.filter((v,i)=>!x.some(w=>v[0]>w[0]^[v,i--]>[w,0]))

```

Try it online!

# JavaScript (Node.js), 53 bytes

```
x=>x.map(v=>!v.l[1]&v.l>o[v.n]||[o[v.n]=v.l],o={})&&o

```

Try it online!

# Answer
> 4 votes
# Retina 0.8.2, 23 bytes

```
A\*
@$&
O`
D`.*,
G`,
@

```

Try it online! Takes input as a newline-separated list of subject, grade pairs. Explanation:

```
A\*
@$&

```

Prefix `@` to any `A*` grades.

```
O`

```

Sort everything into lexical order.

```
D`.*,

```

Delete duplicate subjects.

```
G`,

```

Remove lines whose subjects were deleted.

```
@

```

Remove any `@` prefixes.

# Answer
> 4 votes
# awk, 53 bytes

51 bytes of AWK, in quotes, and 9 for shell invocation…

```
awk -F, '{if(t[$1]<$2)t[$1]=$2}END{for(s in t) print s,t[s]}'

```

As noticed by user Dominic van Essen, there're cases that should be fixed that way (from 51 to 53):

```
awk -F, '$2$2<=t[$1]$2$2{t[$1]=$2}END{for(s in t)print s,t[s]}'

```

If use of blank delimiters (space or tab) is allowed, we can shorten invocation with removal of `-F,`  (4 bytes)

## Usage and notes

…assuming that the table/list is represented by a pair `subject,grade` per line. Then, you can echo the list directly

```
... | invocation

```

or put the list in a file

```
invocation < grades.txt

```

To try, first create the `grade.txt` file this way

```
cat >grade.txt <<-EOF
  foo,A
  bar,A
  foo,A*
  baz,D
  fiz,E
  baz,B
EOF

```

or with `nano grade.txt` for example.

## Ungolfed/explanation

For golfing purposes I've used one letter variables and removed some extra spaces usually good for readability.

```
BEGIN {           # this block is processed once before main
IFS=","           # change Input Field Separator to comma...
}                 # ...or done via command option `-F ','`
{                 # this is the main block, executed for each line
  if (T[$1]<$2)   # build a Table indexed by first field (subject)
                  # when the second field (current grade) is greater
                  # than the existing value (cell initially empty)
      T[$1]=$2    # then replace the table value with current grade
}
END {             # this block is executed once after main processing
  for(S in T)     # loop over the grades Table indexed by Subject
     print S,T[S] # for each entry, output the key (the Subject then)
                  # and the associated value (the maximum grade then)
}

```

I'm sure an AWK guru can improve it a little.

# Answer
> 3 votes
# 05AB1E, 10 bytes

```
.¡н}εΣθR}н

```

Try it online.

**Explanation:**

```
.¡ }        # Group the (implicit) input-list of pairs by:
  н         #  The first string of the pair (the subject)
    ε       # Then map over each group:
     Σ  }   #  Sort the list of pairs in this group by:
      θ     #   The last string of the pair (the grade)
       R    #   Reversed
         н  #  Then just keep the first pair
            # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Perl 5 `-a`, 66 bytes

```
$f{$F[0]}.=$F[1]}{pairmap{say"$a ",(sort$b=~/./g)[0]=~s/\*/A*/r}%f

```

Try it online!

# Answer
> 3 votes
# Excel (ms365), 88 bytes

Formula in `C1`:

```
=LET(x,SORTBY(A1:B4,"*"&B1:B4,-1),y,TAKE(x,,1),FILTER(x,MATCH(y,y,0)=SEQUENCE(ROWS(x))))

```

# Answer
> 3 votes
# Bash, 72 bytes

```
tr 'ABC*' '3210' | sort -k 2,2 -n -r | sort -k 1,1 -u | tr '3210' 'ABC*'

```

Try it online!

---

**Original Input**

```
Latin A*
French A
Math B
French A*
Math C

```

**`tr 'ABC*' '3210'`**
*Convert marks into numbers*

```
Latin 30
French 3
Math 2
French 30
Math 1

```

**`sort -k 2,2 -n -r`**
*Numeric sort using the 2nd field; reverse order*

```
French 30
French 3
Latin 30
Math 2
Math 1

```

**`sort -k 1,1 -u`**
*Sort using the 1st field only (already sorted); keep unique entries*

```
French 30
Latin 30
Math 2

```

**`tr '3210' 'ABC*'`**
*Reverse conversion*

```
French A*
Latin A*
Math B

```

# Answer
> 1 votes
# C (gcc), ~~183~~ ~~177~~ ~~164~~ 155 bytes

*-7 bytes thanks to ceilingcat; -13 bytes thanks to Neil; -8 bytes thanks to l4m2*

```
#define F for(j=0;j<l;j++){for(i=0;strcmp(s[i],s[j]);i++);
i,j;f(s,g,l)char**s,**g;{F*g[i]>*g[j]|g[j][1]?g[i]=g[j]:0;}F i-j?:printf("%s %s\n",s[i],g[i]);}}

```

Defines a function `f` that takes an array of subjects, an array of grades, and an integer representing the length of both arrays. It prints each subject and the best grade in that subject to stdout. Try it online!

### Ungolfed/explanation

This is ~~an awful mess~~ still pretty hacky, but looking a bit nicer than it originally did.

```
#include <stdio.h>
#include <string.h>

int i, j;
int f(char *subjects[], char *grades[], int length) {
  // Loop through the arrays using index j
  for(j = 0; j < length; j++) {
    // For each j, loop through the indices i before it until reaching one with the
    // same subject (i.e. the first entry for that subject)
    for(i = 0; strcmp(subjects[i], subjects[j]); i++);
    // Compare the grades by comparing their first characters (smaller characters
    // are better); if the first characters are the same, check if the second
    // grade has a second character (star is better than no star)
    // If the grade at index j is better than the grade at index i...
    if(grades[i][0] > grades[j][0] || grades[j][1]) {
      // Change the grade at index i to point to the grade at index j instead
      grades[i] = grades[j];
    }
  }
  // Loop through the arrays again
  for(j = 0; j < length; j++) {
    // Find the first entry for this subject
    for(i = 0; strcmp(subjects[i], subjects[j]); i++);
    // If the current entry is the first entry for this subject...
    if(i == j) {
      // Output the subject and the associated grade
      printf("%s %s\n", subjects[i], grades[i]);
    }
  }
}

```

# Answer
> 1 votes
# Arturo, 66 bytes

```
$[a][select a'x[every? select a'y->x\0=y\0'z[>=last z\1last x\1]]]

```

Try it

```
$[a][                                ; a function taking an argument a
  select a'x[                        ; select pairs in a; assign current pair to x
    every?      <block>       'z[    ; is every element z in <block> true?
           select a'y->x\0=y\0       ; select pairs in a where subject = x's subject
      >=last z\1last x\1             ; is the last letter of z's grade >= x's?
    ]                                ; end every?
  ]                                  ; end select
]                                    ; end function

```

---
Tags: code-golf, string, array
---


# Question
Title: P Pr Pre Pref Prefi Prefix Prefixe Prefixes
Given some finite list, return a list of all its prefixes, including an empty list, in ascending order of their length.

(Basically implementing the Haskell function `inits`.)

### Details

* The input list contains numbers (or another type if more convenient).
* The output must be a *list of lists*.
* The submission can, but does not have to be a function, any default I/O can be used.
* There is a CW answer for all trivial solutions.
* This is , so the shortest code in bytes wins

### Example

```
[] -> [[]]
[42] -> [[],[42]]
[1,2,3,4] -> [[], [1], [1,2], [1,2,3], [1,2,3,4]]
[4,3,2,1] -> [[], [4], [4,3], [4,3,2], [4,3,2,1]]

```

# Answer
> 19 votes
# Haskell, 20 bytes

Edit: Yet a byte shorter with a completely different scan.

An anonymous function slightly beating the trivial import.

```
scanr(\_->init)=<<id

```

Try it online!

* Uses `=<<` for the abbreviation `(scanr(\_->init)=<<id) l = scanr(\_->init) l l`.
* Scans a list `l` from right to left, collecting intermediate results with the function `\_->init`.
* That function ignores the elements scanned through (they're only used to get the right total length for the collected results), so really iterates applying `init` to the initial value of the scan, which is also `l`.

# Answer
> 16 votes
# brainfuck, ~~21~~ 12 bytes

*-9 bytes thanks to Arnauld suggesting the separator `ÿ` instead of newlines*

```
-[[<]>[.>],]

```

Try it online!

Takes bytes through STDIN with no null bytes and prints a series of prefixes separated by the `ÿ` character with a leading `ÿ` character. For example, for the input `Prefixes`, the output is `ÿÿPÿPrÿPreÿPrefÿPrefiÿPrefixÿPrefixeÿPrefixes`.

For readability, here's a version with newlines instead.

# Explanation:

```
-              Create a ÿ character in cell 0
 [        ,]   While input, starting with the ÿ
  [<]>           Go to the start of the string
      [.>]       Print the string
          ,      Append the input to the end of the string

```

# Answer
> 12 votes
# JavaScript (ES6), 33 bytes

```
a=>[b=[],...a.map(n=>b=[...b,n])]

```

Try it online!

### How?

```
+--- a = input array
|
|       +--- initialize b to an empty array and include it as the first entry
|       |    of the output (whatever the input is)
|       |
|       |          +--- for each value n in a[]:
|       |          |
|       |          |        +--- append n to b[] and include this new array in
|       |          |        |    the final output
|       |          |        |
a => [b = [], ...a.map(n => b = [...b, n])]
               |                  |
               +---------+--------+
                         |
      spread syntax: expands all elements of
      the child array within the parent array

```

# Answer
> 10 votes
# CW for all trivial entries

# Clean, 19 bytes

Haskell version works in Clean too.

```
import StdLib
inits

```

Try it online!

# Haskell, 22 bytes

```
import Data.List
inits

```

Try it online!

# Prolog (SWI), 6 bytes

```
prefix

```

Try it online!

# Answer
> 7 votes
# Jelly, 3 bytes

```
ṭṖƤ

```

Try it online!

### How it works

```
ṭṖƤ  Main link. Argument: A

  Ƥ  Map the link to the left over all non-empty(!) prefixes of A.
 Ṗ       Pop; remove the last element.
ṭ    Tack; append A to the resulting list.

```

# Answer
> 7 votes
# , ~~40~~ 39 bytes

```
function(L)lapply(0:length(L),head,x=L)

```

Try it online!

*-1 byte thanks to digEmAll*

The output of R's `list` type is a bit weird; it uses sequential indexing, so for instance, the output for

`list(1,2)` is

```
[[1]]                     # first list element
list()

[[2]]                     # second list element
[[2]][[1]]                # first element of second list element
[1] 1

[[3]]                     # third list element
[[3]][[1]]                # first element of third list element
[1] 1

[[3]][[2]]                # etc.
[1] 2

```

Taking input as a vector instead gives a neater output format, although then the inputs are not technically `list`s.

# Answer
> 6 votes
# Japt, 4 bytes

```
²£¯Y

```

Try it online!

Explanation:

```
²       :Add an arbitrary extra item to the end of the array
 £      :For each item in the new array:
  ¯Y    : Get an array of the items that are before it

```

# Answer
> 6 votes
# Python 2, 32 bytes

```
f=lambda l:(l and f(l[:-1]))+[l]

```

Try it online!

# Answer
> 6 votes
# Perl 6, 13 bytes

```
{(),|[\,] @_}

```

Try it online!

To explain:

In Perl 6 you can wrap an operator in square brackets as an alternate way to write a list reduction. `[+] @array` returns the sum of the elements in `@array`, `[*] @array` returns the product, etc. You can also precede the operator with a backslash to make a "triangular" reduction, which some languages call "scan." So `[\+] @array` returns a list consisting of the first element of `@array`, then the sum of the first two elements, then the sum of the first three elements, etc.

Here `[\,] @_` is a triangular reduction over the input array `@_` using the list construction operator `,`. So it evaluates to a lists of lists: the first element of `@_`, the first two elements of `@_`, etc. That's almost what's needed, but the problem calls for a single empty list first. So the first element of the return list is a literal empty list `(),`, then the reduction over the input list is flattened into the rest of the return list with `|`.

# Answer
> 4 votes
# JavaScript, 36 bytes

```
a=>[...a,0].map((x,y)=>a.slice(0,y))

```

Try it online!

# Answer
> 4 votes
# Mathematica, ~~22~~ 21 bytes

*-1 byte thanks to Misha Lavrov!*

```
{}~FoldList@Append~#&

```

Pure function. Takes a list as input and returns a list of lists as output. I believe this is the shortest possible solution.

# Answer
> 4 votes
# Husk, 2 bytes

```
Θḣ

```

Gets all the eads and then prepends `Θ` (in this case `[]`):

Try it online!

(needs type annotation for empty list: Try it online!)

# Answer
> 3 votes
# , 5 bytes

```
a:,<\

```

Try it online!

# Answer
> 3 votes
# PowerShell, 65 bytes

```
param($a)'';$x=,0*($y=$a.count);0..--$y|%{$x[$_]=@($a[0..$_])};$x

```

Try it online!

PowerShell *helpfully* unrolls lists-of-lists when the default `Write-Output` happens at program completion, so you get one item per line. Tack on a `-join','` to see the list-of-lists better, by converting the inner lists into strings.

(Ab)uses the fact that attempting to output an empty array (e.g., `@()`) results in no output, so an empty array input just has `''` as the output, since the `$a[0..$_]` will result in nothing. It will also throw out some spectacular error messages.

# Answer
> 3 votes
# K (ngn/k), ~~8~~ 7 bytes

```
1_',\0,

```

Try it online!

# Answer
> 3 votes
# Common Lisp, 39 bytes

```
(defun f(l)`(,@(if l(f(butlast l))),l))

```

Try it online!

### Explanation

```
(defun f(l)                           )  ; Define a function f
           `(                        )   ; With the list (essentially capable of interpolation), containing:
             ,@                          ;     The value of, flattened to one level
               (if l              )      ;         If l is not the empty list (which is the representation of nil, i.e. the only falsy value)
                    (f(butlast l))       ;         Recurse with all of l but the tail
                                   ,l    ;     The value of l

```

# Answer
> 3 votes
## F#, 53 bytes

I've actually got two pretty similar answers for this, both the same length. They both take a generic sequence `s` as a parameter.

First solution:

```
let i s=Seq.init(Seq.length s+1)(fun n->Seq.take n s)

```

Try it online!

`Seq.take` takes the first `n` elements of the sequence. `Seq.init` creates a new sequence with a count (in this case) of the length of sequence `s` plus 1, and for each element in the sequence takes the first `n` elements in `s`.

Second solution:

```
let i s=Seq.map(fun n->Seq.take n s){0..Seq.length s}

```

Similar to before, except it creates a sequence from 0 to the length of `s`. Then takes that number of elements from `s`.

Try this online too!

# Answer
> 3 votes
# Ruby, ~~31~~ 29 bytes

```
->a{[a*i=0]+a.map{a[0,i+=1]}}

```

Try it online!

Explanation:

```
->a{             # take array input a
  [a*i=0]+       # set i to 0 and add whatever comes next to [[]] (a*0 == [])
  a.map{         # for every element in a (basically do a.length times)
    a[0,i+=1]  # increment i and return the first i-1 elements of a to map
  }
}

```

# Answer
> 3 votes
# MATL, ~~15~~ 12 bytes

*3 bytes saved thanks to @Giuseppe*

```
vin:"G@:)]Xh

```

Try it at MATL Online.

Due to the way that MATL displays the output, you can't explicitly see the empty array in the cell array. Here is a version that shows the output a little more explicitly.

**Explanation**

```
v       # Vertically concatenate the (empty) stack to create the array []
i       # Explicitly grab the input
n       # Compute the number of elements in the input (N)
:       # Create an array from [1, ..., N]
"       # Loop through this array
  G     # For each of these numbers, M
  @:    # Create an array from [1, ..., M]
  )     # Use this to index into the initial array
]       # End of the for loop
Xh      # Concatenate the entire stack into a cell array

```

# Answer
> 3 votes
# SWI PROLOG 22 bytes

`i(X,Y):-append(X,_,Y).`

# Answer
> 3 votes
# Brachylog, ~~9~~ 8 bytes

```
{∧Ė|a₀}ᶠ

```

Try it online!

### Explanation

```
{     }ᶠ    Find all:
 ∧Ė          The empty list
   |         Or
    a₀       A prefix of the input

```

# Answer
> 2 votes
# Charcoal, 6 bytes

```
Ｅθ…θκθ

```

Try it online! Link is to verbose version of code. Explanation:

```
 θ      Input array
Ｅ       Map over elements
   θ    Input array
  …     Moulded to length
    κ   Current loop index
        Implicitly print each array double-spaced
     θ  Input array
        Implicitly print

```

It's possible at a cost of 1 byte to ask Charcoal to print an `n+1`-element array which includes the input as its last element, but the output is the same, although the cursor position would be different if you then went on to print something else.

# Answer
> 2 votes
# 05AB1E, 3 bytes

```
η¯š

```

Explanation:

```
η    Prefixes
  š  Prepend
 ¯   Global array (empty by default)

```

Try it online!

# Answer
> 2 votes
# RAD, 7 bytes

```
(⊂⍬),,\

```

Try it online!

This also works in Dyalog APL as a function.

## How?

This works the same for both APL and RAD, given their close relation.

* `(⊂⍬)` the empty array
* `,` prepended to
* `,\` the prefixes (which exclude the empty array.)

# Answer
> 2 votes
# Groovy, 37 bytes

```
{x->(0..x.size()).collect{x[0..<it]}}

```

Try it online!

# Answer
> 2 votes
# Java 8+, ~~86~~ 77 bytes

-9 bytes thanks to Kevin Cruijssen (getting rid of the import)!

```
x->java.util.stream.IntStream.range(0,x.size()+1).mapToObj(t->x.subList(0,t))

```

Try it online!

## Alternative, 65 bytes

The following will print the results to *stdout* (due to Olivier Grégoire):

```
x->{for(int i=0;i<=x.size();)System.out.print(x.subList(0,i++));}

```

Try it online

# Answer
> 2 votes
# Japt, 5 bytes

```
Êò@¯Y

```

Try it online!

# Answer
> 2 votes
# brainfuck, 43 bytes

Take a list of non-null characters as input and returns all prefixes separated by newline. Requires double-infinite or wrapping tape.

```
,>-[+>,]<[-<]<<++++++++++[[<]>[.>]>[-<+>]<]

```

Try it online!

# Answer
> 2 votes
# Powershell, 24 bytes

```
,@()
$args|%{,($x+=,$_)}

```

Explanation:

1. The trivial accumulator wrapped to array by unary `,`.
2. The script uses splatting. See parameter `@a`.

Test script:

```
$f = {

,@()
$args|%{,($x+=,$_)}

}

@(
    ,( @()        , @() )
    ,( @(42)      , @(@(),@(42)) )
    ,( @(1,2,3,4) , @(@(), @(1), @(1,2), @(1,2,3), @(1,2,3,4)) )
    ,( @(4,3,2,1) , @(@(), @(4), @(4,3), @(4,3,2), @(4,3,2,1)) )
) | % {
    $a,$expected = $_
    $result = &$f @a

    $false -notin $(
        $result -is [array]
        $result.Count -eq $expected.Count
        for($j=0; $j-lt$result.Count; $j++){
            "$($result[$j])" -eq "$($expected[$j])"
        }
    )

    # $result   # uncomment this line to display a result

}

```

Output:

```
True
True
True
True

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 39 bytes

```
x=>x.Select((_,i)=>x.Take(i)).Append(x)

```

Try it online!

# Answer
> 2 votes
# F# (Mono), 45 bytes

```
fun x->List.mapi(fun i y->List.take i x)x@[x]

```

Try it online!

I am not totally sure if this is valid, but it seems like it follows the same "anonymous lambda" syntax that I've seem used in several other languages.

# Answer
> 2 votes
# C (gcc), ~~102~~ 97 bytes

Pretty long, as C quite obviously isn't well-suited to manipulating lists of lists. Dependent on certain behavior; running on some platforms requires changing `int` to `short` (for +2 bytes), due to `wchar_t` being UTF-16 rather than UTF-32. Should work on Linux as-is.

Takes in a pointer to the first element of the input array, the length of the array, and a pointer to the variable in which the pointer to output will be stored. Produces a list of lists such that the first integer in the linear array stores the number of sub-lists. Sub-lists start with the number of elements, and are stored in memory in a contiguous manner.

```
p(r,e,f,i,x)int*e,**r,*x;{x=*r=malloc(4-++f*~f*2);*x++=f;for(i=0;i<f;x+=++i)wmemcpy(x+1,e,*x=i);}

```

Try it online!

## Degolf

```
p(r,e,f,i,x) int**r,*e,*x; // Function p(), where r is a pointer to the output variable,
                           // e is a pointer to the input location and f is the size of
                           // the input.
{
  x=*r=malloc(4-++f*~f*2); // Allocate 4*(x+1)*(x+2)/2+4 bytes of memory.
                           // This is the exact amount of memory needed.
  *x++=f;                  // Store n+1 (number of sub-lists) in the first four bytes.
  for(i=0;i<f;x+=++i)      // Iterate over [0, n]->i and
                           // increment the pointer to x by i+1 every iteration.
    wmemcpy(x+1,e,*x=i);   // Set first element at location pointed to by x to i,
                           // then copy i of either 2 or 4 byte elements, depending on
                           // the system wchar implementation, to location pointed to
                           // by x+1.
}

```

# Answer
> 2 votes
# Scala, 21 bytes

```
_.inits.toSeq.reverse

```

Try it online!

Not quite a trivial answer, since I had to deal with the fact that the `inits` method returns an iterator in the reverse of the required order.

# Answer
> 2 votes
# 05AB1E, 8 bytes

That was my first succesfull golf! Thanks for being such a nice community!

```
)UŒ¹g£Xš

```

Try it online!

## Explanation:

```
)UŒ¹g£Xš
)        : Create an empty list
 U       : Save it to variable ˙X˙
  Œ      : Make the "substrings" of the implicit input
   ¹g£   : Take the first n elements of the result where n is the lenght of input
      Xš : Add the empty list to the beginning

```

# Answer
> 2 votes
# Swift, ~~60~~ 54 bytes

```
let f={(i:[Int])in return[[]]+i.indices.map{i[...$0]}}

```

Try it online!

Defines a function that takes an array of ints and returns an Array of ArraySlices (i.e, they reference the same memory as the input array). To turn into real arrays, it's ~~67~~ 61 bytes.

```
let f={(i:[Int])in return[[]]+i.indices.map{Array(i[...$0])}}

```

# Answer
> 1 votes
# MY, 7 bytes

```
ωωι0;↑←

```

Try it online!

Woah ... never thought MY would actually come in handy.

## How?

`ωωι0;↑←`

* `ω` = `push(arg[0])`
* `ω` = `push(arg[0])`
* `ι` = `push([1 ... pop()])`
* `0` = `push(0)`
* `;` = `push(pop() + pop())`
* = does the prefixing work by vecifying in a stupid manner.
* output

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 48 bytes

```
l=>new int[l.Count()+1].Select((_,n)=>l.Take(n))

```

Try it online!

### Explanation

```
l=>                                                // Function with list l as argument
   new int[l.Count()+1]                            // A new array (int is shortest type available) of length l + 1
                       .Select((_,n)=>l.Take(n))   // Where every element is mapped to the first n elements of the input list, where n is the index

```

# Answer
> 1 votes
# Lua 5.3, 92 bytes

```
function f(...)t=...if#t>0then return f({table.unpack(t,1,#t-1)},...)else return{...}end end

```

Keeps creating a copy of the array-like table with the element at the end removed and prepending it to the varargs until the length of the table is 0, then puts the varargs in a table. Relies on defining the variable `f` to allow recursion.

# Lua 5.1, 87 bytes

```
function f(...)t=...if#t>0 then return f({unpack(t,1,#t-1)},...)else return{...}end end

```

`unpack` is a global variable rather than a member of the `table` library. `0then` is syntactically invalid in Lua 5.1, but strangely not in Lua 5.3.

# Answer
> 1 votes
# Pari/GP, 23 bytes

```
a->[a[1..n]|n<-[0..#a]]

```

Try it online!

# Answer
> 1 votes
# Pip, 16 bytes

```
{h@<a}M,1+#(h:a)

```

Try it online!

### Explanation

```
      M            Map
{h@<a}                 Function returning global variable h, cut at index a, and left part taken (0-indexed)
       ,               Range from 1 to
        1+#(   )           1 + the length of
            h:a                Assign global variable h to a, evaulating to the value of h (which is also the value of a - the first parameter to the function)

```

# Answer
> 1 votes
# Ruby, ~~34~~ 31 bytes

```
->l{(0..l.size).map{|i|l[0,i]}}

```

Try it online!

Thanks @ConorO'Brien!

# Answer
> 1 votes
# Factor, 63 bytes

```
USE: fry [ [ dup '[ nip _ swap head ] map-index ] keep suffix ]

```

Keeps a copy of the input to tack on at the end, like C#.

# Answer
> 1 votes
# Z80Golf, 18 bytes

```
00000000: 2511 00ff 1b1a ffa7 20fa cd03 802b 7730  %....... ....+w0
00000010: f076                                     .v

```

Try it online!

Takes bytes through STDIN with no null bytes and prints a series of prefixes, each terminated by a null byte.

Source code:

```
    dec h
start:
    ld de, $ff00
.printloop:
    dec de
    ld a, (de)
    rst $38
    and a
    jr nz, .printloop
    call $8003
    dec hl
    ld (hl), a
    jr nc, start
    halt

```

# Answer
> 1 votes
# FALSE, 57 bytes

```
1^[$~][\1+^]#%a:0[$a;1->~][0[$@$@>][\$a;\-ø,1+]#\%10,1+]#

```

Try it online! (you'll have to copy paste the code. Click "Show" and then run)

Like brainf\*ck, FALSE only takes one char at a time as input, so this program splits a string into prefixes, separating them with a newline.

Explanation:

```
1^         {push 1 {counter) and first character onto stack}
[$~][      {while a character is input:}
  \1+^     {add 1 to the counter}
]#

%          {drop truth value from stack}
a:         {define the counter as the variable "a'}
0          {push 0 onto stack (loopvar)}
[$a;1->~][ {while loopvar is less than a-1:}

  0        {push 0 (loopvar2)}
  [$@$@>][ {while loopvar is greater than loopvar2}
    \$a;\- {a-loopvar2 (to get index of char to print)}
    ø,     {copy value at index to top of stack and print}
    1+     {increment loopvar2}
  ]#
  \%       {swap'n'drop (get rid of loopvar2)}
  10,      {print newline}
  1+       {increment loopvar}
]#

```

A FALSE expert could probably do this using no variables (pure stack) but since I only learnt this language yesterday I think this is alright.

# Answer
> 1 votes
# MathGolf, ~~9~~ ~~7~~ 6 bytes

```
hÅ_╡]x

```

-1 byte thanks to *@maxb*.

Try it online or verify all test cases.

**Explanation:**

```
h        # Push the length of the (implicit) input-array, without popping the array
 Å       # Loop this length amount of times,
         # and do the following two commands each iteration:
  _      #  Duplicate the array at the top of the stack
   ╡     #  Remove the right-most item of the array
    ]    # After the loop, wrap everything on the stack in an array
     x   # Reverse it (and output implicitly)

```

# Answer
> 1 votes
# , 49 bytes (11 imports, 38 expression)

```
import std;
alias prefixes = t=>iota(t.length+1).map!(i=>t.take(i));

```

Try it online!

edit: Do I count the `alias prefixes =` part? You can use the lambda without it, but you have to add parens to disambiguate, so should I count it as 42?

edit: We now got `import std;` as a shortcut. That solves things!

# Answer
> 1 votes
# MathGolf, 7 bytes

```
hæ_ï<\]

```

Try it online!

## Explanation

```
h         length of array/string without popping
 æ        start block of length 4
  _       duplicate TOS
   ï      index of current loop, or length of last loop
    <     slice list
     \    swap top elements
      ]   end array / wrap stack in array

```

# Answer
> 1 votes
## Clojure, 21 bytes

```
#(reductions conj[]%)

```

# Answer
> 1 votes
# Gambit Scheme (gsi), ~~77~~ 72 bytes

```
(define(p z)(if(pair?(car z))(p(cons(reverse(cdr(reverse(car z))))z))z))

```

Try it online!

First time using Scheme. It's a function that takes a wrapped list (`(list (list 1 2 3 4))`) as an argument.

# Answer
> 1 votes
# Google Sheets, 102

* Input is in Row 1
* A2: `COUNTA(1:1)`
* Output: `=ArrayFormula(IF(A2,{T(SEQUENCE(1,A2));IF(SEQUENCE(A2)>=SEQUENCE(1,A2),OFFSET(A1,,,,A2),)},`

## Output Formatted:

```
=ArrayFormula(IF(
  A2,
  {
    T(SEQUENCE(1,A2));
    IF(
      SEQUENCE(A2)>=SEQUENCE(1,A2),
      OFFSET(A1,,,,A2),
    )
  },
))

```

# Answer
> 1 votes
# Add++, 14 bytes

```
L*,¬b[€bFbUBpA

```

Try it online!

## How it works

```
L		; Lambda function. Takes A as argument
	*,	; Return the enire stack
		; E.g. A = [1 2 3 4]
	¬b[	; Scan pair;	STACK = [[1 [1 2] [[1 2] 3] [[[1 2] 3] 4]]]
	€bF	; Flatten each;	STACK = [[[1] [1 2] [1 2 3] [1 2 3 4]]]
	bU	; Splat;	STACK = [[1] [1 2] [1 2 3] [1 2 3 4]]
	Bp	; Pop each;	STACK = [[] [1] [1 2] [1 2 3]]
	A	; Push A;	STACK = [[] [1] [1 2] [1 2 3] [1 2 3 4]]

```

# Answer
> 1 votes
# Vyxal, 3 bytes

```
K¾p

```

Try it Online!

# Answer
> 1 votes
# Julia 1.0, 26 bytes

```
~l=0:length(l).|>i->l[1:i]

```

Try it online!

**alternative solution in Julia 1.6+, 26 bytes:**

`~l=first.([l],0:length(l))` Try it online!

# Answer
> 1 votes
# Pip, 6 bytes

```
_H,U#_

```

Anonymous function that takes an iterable and returns a list of iterables. (A full program would be the same number of bytes, but would require flags.) Attempt This Online!

### Explanation

```
    #_  ; Length of function argument
   U    ; Incremented
  ,     ; Range from 0 up to one less than that number, i.e. 0..len
_H      ; For each of those numbers n, get the first n elements of the function argument

```

# Answer
> 1 votes
# Go, 72 bytes

```
func(I[]int)(o[][]int){for i:=0;i<=len(I);i++{o=append(o,I[:i])};return}

```

Attempt This Online!

## Generic, 77 bytes

```
func f[T any](I[]T)(o[][]T){for i:=0;i<=len(I);i++{o=append(o,I[:i])};return}

```

Attempt This Online!

# Answer
> 0 votes
# Haskell, 27 bytes

```
i[]=[[]]
i l=i(init l)++[l]

```

Try it online!

# Answer
> 0 votes
# Canvas, ~~6~~ 5 bytes

```
）╶［｝）

```

Try it here!

Outputs to the stack; Linked with a trailing `ｒａｗ` so that's visible.

```
)      wrap the (currently empty) stack in an array
 ╶[}   map nothing over the prefixes of the input
    )  wrap the stack (the empty array and the prefixes) in an array

```

2 bytes without the starting empty array.

# Answer
> 0 votes
# Tcl, 81 bytes

```
set i -1
set a {{}}
foreach _ $argv {lappend a [lrange $argv 0 [incr i]]}
puts $a

```

Try it online!

# Answer
> 0 votes
# Attache, 13 bytes

```
{_[0...0:#_]}

```

Try it online!

## Explanation

```
{_[0...0:#_]}
{           }    block taking `_` as input
 _[        ]     index from the input
       0:#_      range from 0 to the length of `_` inclusive
   0...          range from 0 to each number that range, right exclusive

```

# Answer
> 0 votes
# Red, 76 bytes

```
func[b][a: copy[[]]c: b until[append/only a copy/part b c: next c tail? c]a]

```

Try it online!

# Answer
> 0 votes
# Kotlin, 32 bytes

```
{l->(0..l.size).map{l.take(it)}}

{ list ->
    (0..list.size).map {  // map over range [0, length of list]
        list.take(it)  // first n items of list
    }
}

```

Try it online!

# Answer
> 0 votes
# Pushy, 7 bytes

```
1@$O_vI

```

**Try it online!**

# Answer
> 0 votes
# Tcl, 65 bytes

```
proc P {L J\ {{}}} {lmap e $L {lappend J [lappend K $e]}
list $J}

```

Try it online!

# Answer
> 0 votes
# Forth (gforth), 57 bytes

```
: x here 0 begin 2dup type cr 1+ key dup c, 5 < until ; x

```

Try it online!

Takes bytes through STDIN and prints a series of prefixes, each terminated by a newline.

# Answer
> 0 votes
# str, 6 bytes

```
e;:dno

```

Try it online!

Each output line corresponds to an entry in the prefix array.

## Explanation

```
e;:dno
            -- preamble --
e           push empty string
            -- iteration --
  :         append current char to build string
   d        duplicate it
    n       push "\n"
     o      output it
            (implicitly output duplicated entry)

```

# Answer
> 0 votes
# Perl 5 \+ `-a`, 24 bytes

```
say"@F[0..$_]"for-1..$#F

```

Try it online!

# Answer
> 0 votes
# Actually, 13 bytes

```
;╗ru⌠╜H⌡M[]@o

```

Try it online!

Explanation:

```
;╗ru⌠╜H⌡M[]@o
;╗             save a copy of input in register 0
  ru           range(1, len(input)+1)
    ⌠╜H⌡M      for i in range:
     ╜H          first i elements of input
         []@o  prepend an empty list

```

# Answer
> 0 votes
# Elixir, 37 bytes

```
fn x->Enum.scan [[]|x],&(&2++[&1])end

```

Try it online!

Looking at other languages, this looks rather verbose, but I'm definitely not an expert in Elixir, so please let me know if I missed something obvious.

# Answer
> 0 votes
# APL (Dyalog Unicode), 12 bytes

```
(0,∘⍳∘≢⊢)↑¨⊂

```

Try it online!

Prefix tacit function. TIO link has boxing enabled to make the output more readable.

### How:

```
(0,∘⍳∘≢⊢)↑¨⊂ ⍝ Tacit fn, taking a vector as argument, which will be called ⍵ for simplicity.
         ↑   ⍝ Take the first ⍺ (left arg) elements of ⍵
          ¨⊂ ⍝ Since the ⍺ for ↑ is a vector, we enclose the ⍵ and apply ↑ to it for each of the elements in ⍺.
(      ⊢)    ⍝ Use ⍵ as argument for
      ≢      ⍝ Tally; yields the number of elements in ⍵
    ⍳∘       ⍝ Then, yield the range [1..≢⍵]
 0,∘         ⍝ and prepend a 0.

```

The function returns a vector of vectors, each with the first `[0..≢⍵]` elements of the argument.

# Answer
> 0 votes
## Bash, 34 bytes

I output each list element on a new line as someone else did - bash only has 1-D arrays:

```
for((;c<=$#;c++)){ echo ${*:1:c};}

```

Could be 1 byte less but this does not work for null case - don't see why... c++ does not get evaluated...

```
for((;c<=$#;)){ echo ${*:1:c++};}

```

This can output text as suggested by OP:

```
C='echo -n ';A=(${1//[],[]/ });$C[[];for((c=0;c<${#A[*]};)){ B=${A[*]::++c};$C,[${B// /,}];};echo ]

```

No one should have to decode that. Here is annotated version:

```
C='echo -n '              # basically a macro to improve my golf
A=( ${1//[],[]/ } )       # convert [,] to spaces - like magic this one
$C[[]                     # echo [[] since every list needs this
for((c=0;c<${#A[*]};)){   # for all elements of list
  B=${A[*]::++c}          # make space separated list of first c elements
  $C,[${B// /,}]          # prefix with ,[ and convert space to comma
}
echo ]                    # terminate list with ]

```

# Answer
> 0 votes
# Reticular, 60 bytes

```
Bql:D=:D`:E=l[:D`@d]~*[:E`b@qM[$]:D`:E`-*:E`1-:E=]:D`1+*lbo;

```

Try it online!

Assumes that the input list is at the top of the stack. To test input, run the following code

```
'1''2''3''4''5'lbBql:D=:D`:E=l[:D`@d]~*[:E`b@qM[$]:D`:E`-*:E`1-:E=]:D`1+*lbo;

```

## Explanation

```
B                         # Push every element from the input list to the stack.
 q                        # Reverse stack.
  l                       # Push the size of the stack to the stack.
   :D=                    # Save it as the variable D.
      :D`:E=              # Define the variable E = D.
            l             # Push D to the stack.
             [:D`@d]      # Push the function which duplicates the top D items in the stack
                    ~     # Swap the top two items in the stack
                     *    # Call the above function D number of times.

[                          ]            # Push a function that does the following:
 :E`b                                   # Put the top E items in a list.
     @q                                 # Reverse list that is at the top of the stack.
       M                                # Rotate stack so that top of stack -> bottom of stack.
        [$]:D`:E`-*                     # Delete the top D-E items from the stack.
                   :E`1-:E=             # Define E = E - 1.
                            :D`1+*      # Call the above function D+1 number of times.
                                  q     # Reverse stack.
                                   lb   # Put every item in the stack into a list.
                                     o; # Output the resulting list and exit.

```

# Answer
> 0 votes
# Scala, 28 bytes

```
_.scanLeft(Seq[Int]())(_:+_)

```

Try it online!

This is longer than the Scala answer that's already here, but uses a different method. Unfortunately, the `[Int]` must be used to avoid `Nothing` being inferred.

# Answer
> 0 votes
# Factor \+ `grouping.extras`, 25 bytes

```
[ head-clump { } prefix ]

```

Try it online!

Mostly a built-in. Just have to add the empty list at the beginning.

Compare to a non-trivial answer:

```
[ dup length [0,b] [ head ] with map ]

```

Try it online!

# Answer
> 0 votes
# Pyth, 6 bytes

```
Sa._QY

```

Try it online!

# Answer
> 0 votes
# Arturo, ~~31~~ 29 bytes

```
$[a][map 0..size a=>[take a]]

```

Try it

# Answer
> 0 votes
# x86 opcode, 11 bytes

```
xor eax, eax
inc ecx
P:
xchg eax, esi
stosd
xchg eax, esi
stosd
inc eax
loop P
ret

```

Take `ecx(length) esi(input array) edi(output buffer)` output `(array,length)` pairs

Somehow cheaty :)

# Answer
> 0 votes
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
0TzreRz0sAI

```

Attempt This Online!

#### Explanation

```
0TzreRz0sAI  # Implicit input
0T           # Append a 0 (so the length is increased by 1)
  zr         # Length range, [0..len)
    e        # Map over this list:
     R       #   Range from 0 to this number
        sAI  #   Index this into
      z0     #   The input
             # Implicit output

```

---
Tags: code-golf, array
---