P Pr Pre Pref Prefix Prefiks Prefiksy Prefiksy


Biorąc pod uwagę skończoną listę, zwróć listę wszystkich jej prefiksów, w tym pustą listę, w porządku rosnącym według ich długości.

(Zasadniczo implementacja funkcji Haskell inits.)


  • Lista wprowadzania zawiera liczby (lub inny typ, jeśli jest to wygodniejsze).
  • 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.


[] -> [[]]
[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]]

If a language does not define any types except for characters, can I take input as a string and separate the input by newlines, in the case of a full program?

@NieDzejkob I'm not sure what consensus there is for this case, but the Brainfuck answer seems to do something like that.

Can we expect the list to be null-terminated?

It's especially common in C/C++, main use being strings.

@Rogem If it is that common I think allowing it is reasonable.



Haskell, 20 bytes

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

An anonymous function slightly beating the trivial import.


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.


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.


-              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

This only works on BF implementations with 8-bit, unsigned, wrapping cells.


JavaScript (ES6), 33 bytes


Try it online!


+--- 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

wow, that's a whole new level of code explanation, awesome job :O
Brian H.

@BrianH. Thank you! Simple tasks are good opportunities to write detailed explanations that can't be brought up in denser code.

Did you make it by hand? or did you get help from any weird software i've never heard about?
Brian H.

Just Notepad++ with some column mode editing.


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.


Japt, 4 bytes


Try it online!


²       :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


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 |.

O_o what is even happening here


R, 40 39 bytes


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

[[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 lists.

@digEmAll thanks!


Mathematica, 22 21 bytes

-1 byte thanks to Misha Lavrov!


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

We can write the same solution more compactly as {}~FoldList@Append~#&.
Misha Lavrov

@MishaLavrov Thanks! I didn't think to use the curried 1+2-argument form like that.


PowerShell, 65 bytes


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.

Wrapping it in parens instead of assigning it saves 20 bytes. Unless you don't think that counts as returning a list of lists. I've always been fuzzy on that distinction.

@veskah Yeah, that's almost what I had before my edit to this version. The problem with your solution or my earlier solution -- it doesn't return a list-of-lists. TIO1 vs TIO2


K (ngn/k), 8 bytes


Try it online!

This is some kind of voodoo. ,\(,()), in K4. Joining enlisted null along enlisted input? howsitwork?

@streetster () is an empty list. (,()),x prepends it to x. finally ,\ does a concat-scan. the x is omitted to form a composition. note that the trailing , is dyadic, so it's "concat", not "enlist".

@streetster in k4 it can be a byte shorter: 1_',\0, but my parser isn't smart enough to handle this...


Common Lisp, 39 bytes

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

Try it online!


(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


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!

fun s->Seq.map(fun n->Seq.take n s){0..Seq.length s} saves 1 byte
Embodiment of Ignorance


MATL, 15 12 bytes

3 bytes saved thanks to @Giuseppe


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.


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

use v instead of []. And doesn't : use 1 as the default first argument? So this could be vin:"G@:)]Xh for 12 bytes.

@Giuseppe Thanks! My MATL is a little rusty it seems :(


Charcoal, 6 bytes


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

 θ      Input array
E       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.


RAD, 7 bytes


Try it online!

This also works in Dyalog APL as a function.


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.)


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!

Another answer outgolfed me by more than a half, because I didn't think about printing output while reading. Of course that method won't work with printing increasing suffixes.

40 bytes with some rearranging
Jo King


C# (Visual C# Interactive Compiler), 39 bytes


Try it online!

You need to include the using System.Linq; in your bytecount. And it seems some of your output logic is in your outputting of the arrays. Because empty array just returns empty array.

@LiefdeWen - my understanding is that since this interpreter includes a reference to System.Linq, I don't have to include this in the byte count. My submission would be considered a different language than say .NET Core. github.com/dotnet/roslyn/wiki/C%23-Interactive-Walkthrough - You mention printing which is a separate issue, I'd like to get clarity on this first.

With regards to printing, here is a version that basically dumps the result to the console - tio.run/##XY29CsIwGEX3PEXGBGKhtVt/… - not as pretty for sure! The question I have is when is it acceptable to use Array vs IList vs IEnumerable.


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.


Java 8+, 86 77 bytes

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


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

You can golf it to 77 bytes by just using java.util.stream.IntStream directly and drop the import.
Kevin Cruijssen

@KevinCruijssen: Oh thanks! I didn't even know that this was possible, that's certainly helpful (at least for golfing purposes).

x->{for(int i=0;i<=x.size();)System.out.println(x.subList(0,i++));} (67 bytes). This prints instead of using streams. Printing is usually the shortest way to output complex structures.
Olivier Grégoire

@OlivierGrégoire: In that case you can probably get away with System.out.print since the output is still unambiguous.

@BMO Indeed, that would be possible!
Olivier Grégoire


Brachylog, 9 bytes


Try it online!


a₀ᶠ           Find all prefixes of the input
   ~b         Add an element at the beginning of that list of prefixes
      hĖ      This element is the empty list
     .  ∧     (the list with the additional empty list is the output)


Ruby, 31 29 bytes


Try it online!


->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
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.