# Question
Title: It took me a lot of time to make this, pls like. (YouTube Comments #1)
Hold up..... this isn't trolling.

---

# Background

These days on YouTube, comment sections are littered with such patterns:

```
S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S

```

where `String` is a mere placeholder and refers to any combination of characters. These patterns are usually accompanied by a `It took me a lot of time to make this, pls like` or something, and often the OP succeeds in amassing a number of likes.

---

# The Task

Although you've got a great talent of accumulating upvotes on PPCG with your charming golfing skills, you're definitely not the top choice for making witty remarks or referencing memes in YouTube comment sections. Thus, your constructive comments made with deliberate thought amass a few to no 'likes' on YouTube. *You want this to change.* So, you resort to making the abovementioned clichéd patterns to achieve your ultimate ambition, but without wasting any time trying to manually write them.

Simply put, your task is to take a string, say `s`, and output `2*s.length - 1` substrings of `s`, delimited by a newline, so as to comply with the following pattern:

(for `s` = "Hello")

```
H
He
Hel
Hell
Hello
Hell
Hel
He
H

```

---

# Input

A single string `s`. Input defaults of the community apply. You can assume that the input string will only contain printable ASCII characters.

---

# Output

Several lines separated by a newline, constituting an appropriate pattern as explained above. Output defaults of the community apply. Leading and trailing **blank (containing no characters or characters that cannot be seen, like a space)** lines in the output are permitted.

---

# Test Case

A multi-word test case:

```
Input => "Oh yeah yeah"

Output =>

O
Oh
Oh
Oh y
Oh ye
Oh yea
Oh yeah
Oh yeah
Oh yeah y
Oh yeah ye
Oh yeah yea
Oh yeah yeah
Oh yeah yea
Oh yeah ye
Oh yeah y
Oh yeah
Oh yeah
Oh yea
Oh ye
Oh y
Oh
Oh
O

```

Note that there are apparent distortions in the above test case's output's shape (for instance, line two and line three of the output appear the same). Those are because we can't see the trailing whitespaces. Your program need NOT to try to fix these distortions.

---

# Winning Criterion

This is , so the shortest code in bytes in each language wins!

# Answer
# brainfuck, 32 bytes

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

```

Try it online!

The same loop is used for both halves of the pattern.

### Explanation:

```
,             Take first input character as initial line
[             Until line to output is empty:
  [<]>        Move to beginning of line
  [.>]        Output all characters in line
  ++++++++++. Output newline
  ,           Input next character
  [>>]        Move two cells right if input character nonzero
  <[-]        Otherwise remove last character in line
  <           Move to new last character in line
]

```
> 120 votes

# Answer
# JavaScript (ES6), 36 bytes

```
f=([c,...r],s=`
`)=>c?s+f(r,s+c)+s:s

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
                  //   the input string split into:
  [c,             //     c   = next character (may be undefined if we've reached the end)
      ...r],      //     r[] = array of remaining characters
  s = `\n`        //   the output string s, initialized to a linefeed
) =>              //
  c ?             // if c is defined:
    s +           //   append s (top of the ASCII art)
    f(r, s + c) + //   append the result of a recursive call to f, using r[] and s + c
    s             //   append s again (bottom of the ASCII art)
  :               // else:
    s             //   append s just once (this is the final middle row) and stop recursion

```
> 55 votes

# Answer
# 05AB1E (legacy),  ~~4~~  3 bytes

*Crossed out ` 4 ` is no longer 4 :)*

```
η.∊

```

Try it online or verify all test cases.

**Explanation:**

```
η     # Get the prefixes of the (implicit) input-string
 .∊   # Vertically mirror everything with the last line overlapping
      # (which implicitly joins by newlines in the legacy version of 05AB1E)
      # (and output the result implicitly)

```

In the new version of 05AB1E, and explicit `»` is required after the `η`, which is why I use the legacy version of 05AB1E here to save a byte.

---

**3 bytes alternative provided by *@Grimy*:**

```
ηû»

```

This version works in both the legacy and new version of 05AB1E.

Try it online (legacy), try it online (new version) or verify all test cases (new version).

**Explanation:**

```
η     # Get all prefixed of the (implicit) input-string
 û    # Palindromize each string in this list
  »   # And then join the list of strings by newlines
      # (after which the result is output implicitly)

```
> 50 votes

# Answer
# x86-16 machine code, IBM PC DOS,  ~~44~~  ~~43~~ 39 bytes

```
00000000: d1ee ad8b d648 93b7 248a cbd0 e13a d975  .....H..$....:.|
00000010: 01fd ac86 3cb4 09cd 2186 3cb8 0d0e cd10  ....<...!.<.....
00000020: b00a cd10 e2e7 c3                        .......

```

Build and test `YT.COM` using `xxd -r` from above.

***Unassembled:***

```
D1 EE       SHR  SI, 1              ; point SI to DOS PSP at 80H (SI intialized at 100H)
AD          LODSW                   ; load input length into AL, SI = 82H
8B D6       MOV  DX, SI             ; save start of string pointer
48          DEC  AX                 ; remove leading space from string length
93          XCHG AX, BX             ; save string length in BL
B7 24       MOV  BH, '$'            ; put end-of-string marker in BH
8A CB       MOV  CL, BL             ; set up loop counter in CL
D0 E1       SHL  CL, 1              ; number of lines = 2 * string length - 1
    LINE_LOOP:
3A D9       CMP  BL, CL             ; does CL = string length?
75 01       JNZ  LINE_OUT           ; if not, go to output line
FD          STD                     ; otherwise flip DF to descend
    LINE_OUT:
AC          LODSB                   ; increment or decrement SI
86 3C       XCHG BH, [SI]           ; swap current string byte with end of string delimiter
B4 09       MOV  AH, 9              ; DOS API display string function
CD 21       INT  21H                ; write substring to console
86 3C       XCHG BH, [SI]           ; restore string byte
B8 0E0D     MOV  AX, 0E0DH          ; AH = 0EH (BIOS tty function), AL = CR char
CD 10       INT  10H                ; write CR to console
B0 0A       MOV  AL, 0AH            ; AL = LF char
CD 10       INT  10H                ; write LF to console
E2 E6       LOOP LINE_LOOP          ; move to next line
C3          RET                     ; return to DOS

```

***Explanation***

Loop `2 * input length - 1` for each row. The DOS API's string display function (`INT 21H,9`) writes a `$`-terminated string to the screen, so each time through the loop the character after the last to be displayed is swapped with the end-of-string terminator.

The loop counter is compared with the string length, and if it's greater (meaning the ascending part of the output) the string/swap position is incremented, otherwise it's decremented.

Standalone PC DOS executable program, takes input string from command line.

***Output***

* -1 byte use `SHR SI, 1` instead of `MOV` \- thanks to gastropner!
* -1 byte flipping loop comparison
* -1 byte write newline directly instead of as string
* -1 byte use `XCHG` instead of `MOV`
* -1 byte use `STD` / `LODSB` to ascend/descend SI pointer
> 25 votes

# Answer
# MATL, 8 bytes

```
nZv"G@:)

```

Try it online!

Please like this post for the smiley `:)` in the code it took me a lot of time to make.

```
n  % Length of the input string
Zv % Symmetric range ([1 2 ... n ... 1])
"  % For each k in above range
G  % Push input
@: % Push [1 2 ... k]
)  % Index

```
> 20 votes

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

```
f=lambda s,n=1:s[n:]and[s[:n]]+f(s,n+1)+[s[:n]]or[s]

```

Try it online!

# Python 3.8 (pre-release), 50 bytes

```
f=lambda s,n=1:s>(x:=s[:n])and[x,*f(s,n+1),x]or[s]

```

Try it online!
> 19 votes

# Answer
# , 11 bytes

Anonymous tacit prefix function. Returns a space-padded character matrix.

```
[:(}:,|.)]\

```

Try it online!

`]\` the list of prefixes

`[:(``)` apply the following function to that list

`|.` the reverse list

`,` prepended with

`}:` the curtailed (without last item) list
> 16 votes

# Answer
# Perl 6, 31 bytes

```
{[\~](@_)[0...@_-1...0]}o*.comb

```

Try it online!

Anonymous code block that takes a string and returns a list of lines.

### Explanation:

```
{                      }o*.comb   # Pass the list of characters into the codeblock
 [\~](@_)                 # Triangular reduce by concatenation
                          # e.g. The list [1,2,3,4] turns into [1,12,123,1234]
         [0...@_-1        # Return the elements from 0 to length of string minus 1
                  ...0]   # And back down to 0

```
> 13 votes

# Answer
# Japt -R, 4 bytes

```
å+ ê

```

Cumulative reduce on a string.

*-1 byte thanks to @Shaggy*

Try it online!
> 11 votes

# Answer
# Japt `-R`, ~~9~~ 7 bytes

-2 bytes thanks to Shaggy

```
Êõ@¯XÃê

```

Try it online!
> 10 votes

# Answer
# Perl 5 (`-p`), 26 bytes

```
s,.,$\=$`.$/.$\;"$`$&
",ge

```

TIO
> 10 votes

# Answer
# Haskell, ~~52~~ ~~50~~ 44 bytes

```
f x=unlines$init<>reverse$scanr(\_->init)x x

```

Try it online!
> 9 votes

# Answer
# , ~~79~~ ~~65~~ ~~62~~ 58 bytes

```
write(substring(s<-scan(,""),1,c(1:(r=nchar(s)),r-1:r)),1)

```

Try it online!

*-14 by Giuseppe's superior function knowledge*

*-3 with cleaner indexing*

*-4 thanks to Nick Kennedy and Giuseppe's move to `scan` and `write`*

Avoiding loops (and `substr`) is nice.
> 8 votes

# Answer
# Python 3.8 (pre-release), 48 bytes

```
lambda s,r='':(l:=[r:=r+c for c in s])+l[-2::-1]

```

Try it online!

Uses assignment expressions with `:=` to accumulate a list of prefixes and then again to save the result to concatenate its reverse (without the first char).

# Python 2, 51 bytes

```
f=lambda s,l=[]:s and f(s[:-1],[s]+l)or l+l[-2::-1]

```

Try it online!

We almost have the following nice 45-byte solution, but it has the original string twice and I don't see a short way to fix this.

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

```

Try it online!
> 6 votes

# Answer
# Jelly, ~~5~~ 4 bytes

*-1 byte thanks to @JonathanAllan!*

```
¹ƤŒḄ

```

Try it online! I think this is my second Jelly answer? ~~I don't know if this is optimal.~~ I am more convinced of it being optimal. Returns an array of lines.

## Explanation

```
¹ƤŒḄ     input: "Hi!"
¹Ƥ       prefixes of the input: [["H"], ["H", "i"], ["H", "i", "!"]]
  ŒḄ     bounce, using each array: [["H"], ["H", "i"], ["H", "i", "!"], ["H", "i"], ["H"]]

```

Another approach, proposed by @JonathanAllan, is `;\ŒḄ`, which cumulatively reduces (`\`) concatenation (`;`), which is another way to generate prefixes.
> 6 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~123~~ ~~109~~ ~~94~~ ~~84~~ 74 bytes

Assumes we can return a char array array (I believe we can, as a char array is a valid representation for a string and a string array is a valid representation for multiple lines)

```
a=>new int[a.Length*2-1].Select((b,i)=>a.SkipLast(Math.Abs(a.Length-i-1)))

```

Try it online!
> 5 votes

# Answer
# Charcoal, 5 bytes

```
Ｇ^Ｌθθ

```

Try it online! Link is to verbose version of code. Explanation:  draws a filled polygon, `^` specifies that the sides are down right and down left (the polygon then automatically closes itself), `Ｌθ` specifies the length of those sides as being the length of the original input and the final `θ` specifies the fill string.
> 5 votes

# Answer
# Attache, 15 bytes

```
Bounce@Prefixes

```

Try it online!

Pretty simple. `Bounce`s (appends reverse without center) the `Prefixes` of the input.

Alternatively, **21 bytes:** `Bounce@{_[0..0:~-#_]}`, re-implementing prefix.
> 5 votes

# Answer
# Brachylog (v2), 6 bytes

```
a₀ᶠ⊆.↔

```

Try it online!

Function submission, returning an array of lines. Loosely based on @Fatalize's answer.

## Explanation

```
a₀ᶠ⊆.↔
    .↔  Find a palindrome
   ⊆      that contains, in order,
  ᶠ       all
a₀        prefixes of {the input}

```

Tiebreak order here is set by the , which, when used with this flow pattern, prefers the shortest possible output, tiebroken by placing the given elements as early as possible. The shortest possible output is what we want here (due to it not being possible to have any duplicate prefixes), and placing the given elements (i.e. the prefixes) as early as possible will place them in the first half (rounded up) of the output. Given that we're also requiring them to be placed in the same order, we happen to get exactly the pattern we need even though the description we gave Brachylog is very general; the tiebreaks happen to work out exactly right, causing Brachylog to pick the output we want rather than some other output that obeys the description.
> 5 votes

# Answer
# APL (Dyalog Unicode), 9 bytesSBCS

Anonymous tacit prefix function. Returns list of strings.

```
(⊢,1↓⌽),\

```

Try it online!

`,\` the list of prefixes (lit, the cumulative concatenation)

`(``)` apply the following function to that list:

the reversed list

`1↓` drop the first item

`,` prepend

the unmodified list
> 4 votes

# Answer
# sed, 31 35 bytes

```
:x
h
s/.\n.*\|.$//
/^$/{x;q}
H
G
bx

```

Try it online!

# Explanation

At the beginning of each iteration of the loop, pattern space is some "central chunk" of the desired output, and each loop adds a shortened copy to the top and bottom.

```
:x
h                  Copy the current chunk to hold space
s/.\n.*\|.$//      Remove the last letter of the first line, and all other lines (if there are any)
/^$/{x;q}          If pattern space is empty we're done; output hold space
H                  Add the shortened line to the end of hold space
G                  and add the new hold space to pattern space.
bx

```
> 4 votes

# Answer
# PowerShell, 46 bytes

```
($l=$args|% t*y|%{($s+=$_);++$i})+$l[$i..0]|gu

```

Try it online!

---

# PowerShell, 42 bytes (YouTube special, dirty)

It is known that the maximum length of a comment on youtube is 10,000 characters. Ok, use this as the upper limit.

```
($l=$args|% t*y|%{($s+=$_)})+$l[1e4..0]|gu

```

Try it online!
> 4 votes

# Answer
# x86-16 machine code, IBM PC-DOS, 33 bytes

Hexdump:

```
00000000: bf 82 00 91 89 fa e8 0a 00 74 06 41 eb f8 e8 02  .........t.A....
00000010: 00 e2 fb b4 40 cd 21 b0 0d ae cd 29 b0 0a cd 29  ....@.!....)...)
00000020: c3                                               .

```

Commented assembly:

```
        [org 0x100]
start:
        ; DI <- first command line argument
        mov     di, 0x0082
        ; DOS startup state abuse 1: set CX to zero by swapping AX (0x0000)
        xchg    cx, ax
        ; DX <- DI
        mov     dx, di
.loop1:
        ; A multitasking loop.
        ; This both prints the string up to the full length and counts
        ; the chars by scanning for '\r'.

        ; Print DS:DX(CX)
        ; We test for the end of string when printing
        ; the newline by using SCASB.
        call    putsn
        ; If the SCASB returned true, break to the end of .loop2
        ; We don't go to the top because it would print the full
        ; length string twice.
        jz      .next
        ; Increment the length and character counter
        inc     cx
        ; Loop to loop1
        jmp     .loop1

.loop2: ; Shortening loop
        ; Print
        call    putsn
.next:
        ; while (--CX)
        loop    .loop2
        ; Fallthrough: prints an empty line (as CX is 0) and exits

        ; Prints CX chars from DX, followed by a newline.
putsn:
        ; DOS startup state abuse 2: BX is 0x0000.
        ; DOS lets you write to STDIN and it still prints to the screen.
        ; Why? I have no idea. It's very convenient though. Note that
        ; this behavior is consistent on DOS 6.22 and FreeDOS 1.3rc4.
        ;
        ; write(0, argv, CX)
        mov     ah, 0x40
        int     0x21
        ; Print \r\n with INT 29h
        mov     al, 13
        ; Since we have \r in AL, we can use SCASB to check
        ; for the end of the string when we return.
        ; Interrupts save the flags.
        ;
        ; Yes, this reads out of bounds on the second loop,
        ; but it is DOS, who cares?
        scasb
        int     0x29
        mov     al, 10
        int     0x29
        ret

```

To be even with 640KB, I also used the command line arguments, but I made some changes:

1. I use `write` (`21:40`) instead of `puts` (`21:09`). While it does require manually printing a newline, it lets me manually control the length just by changing CX.
2. I count the length of the command line arguments on the fly.
3. I did some other tricks.

This abuses the newline rule: it actually prints empty strings at the start and end.
> 4 votes

# Answer
# C (gcc), ~~68~~ ~~67~~ ~~64~~ 59 bytes

thanks @ceilingcat for -6 thanks @gastropner for -5

```
i,j;f(char*s){for(j=1;i+=j;puts(""))j-=2*!s[write(1,s,i)];}

```

Try it online!
> 3 votes

# Answer
# Ruby, ~~51~~ ~~42~~ 40 bytes

```
f=->s,i=1{s[i]?[t=s[0,i],*f[s,i+1],t]:s}

```

Try it online!

Thanks to Doorknob for -2 bytes.
> 3 votes

# Answer
# , 12 bytes

```
]\,[:}.@|.]\

```

Try it online!

Still 1 byte longer than Adám's

# K (oK), ~~12~~ 11 bytes

-1 byte thanks to ngn

```
{x,1_|x}@,\

```

Try it online!
> 3 votes

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

This can probably be golfed alot more, Arnauld already has a way shorter one but I had fun atleast!

```
s=>{a=[];for(c=s.length-1;c--;)a[c]=s.slice(0,c+1);return[...a,s,...a.reverse()].join`\n`}

```

Try it online!
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), 118 bytes

```
	N =INPUT
	L =1
1	X =LT(X,SIZE(N)) X + 1	:F(D)
O	N ARB . OUTPUT POS(X)	:($L)
D	X =GT(X) X - 1	:F(END)
	L ='D'	:(O)
END

```

Try it online!

There appears to be a bug in this implementation of SNOBOL; attempting to replace the label `D` with the label `2` causes an error, although the manual for Vanilla SNOBOL indicates that (emphasis added)

> If a label is present, it must begin with the first character of the line. Labels provide a name for the statement, and serve as the target for transfer of control from the GOTO field of any statement. **Labels must begin with a letter or digit, optionally followed by an arbitrary string of characters.** The label field is terminated by the character blank, tab, or semicolon. If the first character of a line is blank or tab, the label field is absent.

My supposition is that the CSNOBOL interpreter only supports a single label that begins with an integer.
> 3 votes

# Answer
# APL+WIN, 31 bytes

Prompts for input of string:

```
 ⊃((⍳n),1↓⌽⍳n)↑¨(¯1+2×n←⍴s)⍴⊂s←⎕

```

Explanation:

```
(¯1+2×n←⍴s)⍴⊂s create a nested vector of the string of length =1+2x length of string

((⍳n),1↓⌽⍳n)↑¨ progressively select elements from each element of the nested vector
              following the pattern 1  2 ...to n to n-1 ... 1

⊃ convert nested vector into a 2d array.

```
> 3 votes

# Answer
# F# (.NET Core), ~~67~~ 61 bytes

```
let l=s.Length
[1..l*2-1]|>Seq.map(fun i->s.[..l-abs(i-l)-1])

```

Try it online!

Input is a `string` and output is a `seq<string>`

Another solution could be `let f(s:string)=for i=1 to s.Length*2-1 do printfn"%s"s.[..s.Length-abs(i-s.Length)-1]` for 80ish bytes... I am not sure that it is worth looking into.
> 3 votes

# Answer
# Haskell, 36 bytes

```
foldr(\h l->(h:)<$>[]:l++min[[]]l)[]

```

Try it online!

Outputs a list of lines.

**Haskell, 37 bytes**

```
f[c]=[[c]]
f(h:t)=(h:)<$>"":f t++[""]

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~62~~ ~~60~~ 58 bytes

-2 bytes by using the `write()` approach of jaeyong-sung's answer.

```
i,d;f(char*s){for(d=1;write(1,s,i+=d-=!s[i]*2);puts(""));}

```

Try it online!
> 3 votes

# Answer
# PHP, 79 bytes

```
function y($s,$l=1){echo$t=substr($s,0,$l)."
",$l<strlen($s)?y($s,$l+1).$t:'';}

```

Try it online!

Recursive in PHP as a function. Ungolfed version:

```
function y( $s, $l=1 ) {
    echo $t = substr( $s, 0, $l ) . "\n";
    if ( $l < strlen( $s ) ) {
        y( $s, $l+1 );
        echo $t;
    }
}

```

Call as `y('String')` outputs:

```
S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S

```

Or **69 bytes** iterative with `php -nF` input as STDIN (basically a port of several other answers).

```
while(++$x<2*$l=strlen($s=$argn))echo substr($s,0,$l-abs($x-$l)),"
";

```

Try it online!
> 3 votes

# Answer
# \[Assembly (nasm, x64, Linux)\], 35 32 bytes

This is a function that takes a string (Pointer in RSI) and it's length (number in ebp), and outputs the required string to STDOUT.

EDI and EDX *MUST* be 0

```

ytc:
	;Actual setup
	inc ebp
	inc edi ;FD for STDOUT
	push rdi ;Value to add/subtract
	mov bl, 0Ah
.lp:
	add edx, [rsp] ;Str Length +- 1
	jz .end
	cmp edx, ebp
	jne .clp
	push -1
.clp:
	xchg [rsi+rdx-1], bl
	mov al, 1
	syscall
	xchg [rsi+rdx-1], bl
	jmp .lp
.end:
	ret

```

Try it online!
> 3 votes

# Answer
# BASH (+ GNU coreutils) 72 bytes

Takes input string from STDIN (one line)

```
read s;for i in `seq ${#s};seq $((${#s}-1)) -1 1`;do echo ${s:0:$i};done

```

example:

```
echo "Oh yeah yeah" | ./script.sh

```

output:

```
O
Oh
Oh
Oh y
Oh ye
Oh yea
Oh yeah
Oh yeah
Oh yeah y
Oh yeah ye
Oh yeah yea
Oh yeah yeah
Oh yeah yea
Oh yeah ye
Oh yeah y
Oh yeah
Oh yeah
Oh yea
Oh ye
Oh y
Oh
Oh
O

```

## Explanation:

```
# read string from STDIN into variable $s
read s

# `seq ${#s}` : sequence of numbers from 1 to length of string followed by
# `seq $((${#s}-1)) -1 1` : sequence of numbers from length-1 downto 1

# loop through sequence
for i in `seq ${#s};seq $((${#s}-1)) -1 1`;do

    # print substring of $s from position 0 to i
    echo ${s:0:$i}

# end of loop
done

```
> 3 votes

# Answer
## Julia, 40 bytes

```
s->(a=cumprod([s...]);[a;a[end-1:-1:1]])

```

Try it online!

Gets the first half by taking the cumulative product (`*` is string concatenation in Julia) of the array of characters, then adds this array to itself reversed minus the first element.

Thanks to @Kirill L. for 4 bytes.
> 2 votes

# Answer
# Octave, 58 bytes

```
for k=1:(n=nnz(s=input(''))*2)-1
disp(s(1:min(k,n-k)))
end

```

Try it online!
> 2 votes

# Answer
# Brachylog, 8 bytes

```
a₀ᶠ;Lc.↔

```

Try it online!

### Explanation

```
a₀ᶠ          Find all prefixes of the input
   ;Lc.      The output is that list of prefixes with something unknown appended at the end
      .↔     The output reversed is itself (i.e. it's a palindrome)

```
> 2 votes

# Answer
## MBASIC, 103 bytes

```
1 INPUT S$:N=1
2 PRINT LEFT$(S$,N):IF N<LEN(S$) THEN N=N+1:GOTO 2
3 N=N-1:PRINT LEFT$(S$,N):IF N>1 THEN 3

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~82~~ 81 bytes

```
x=>{for(int l=x.Length,i=0;i<l*2-1;)WriteLine(x.Substring(0,l-Math.Abs(++i-l)));}

```

Try it online!

String as input and output to std
> 2 votes

# Answer
# Pyke, 6 bytes

```
BE 27 4F 5F 2B 58

```

Try it here!

```
        - input() (implicit)
.>      - prefixes(^) (1 byte)
  'O_   - ^[:-1], reversed(^)
     +  - [^]
      X - "\n".join(reversed(^))

```
> 2 votes

# Answer
# MathGolf, 7 bytes

```
£rñ{l<n

```

Try it online!

## Explanation

```
£         length of array/string with pop
 r        range(0, n)
  ñ       pop(a), push palindromize(a) string/list/number
   {      start block or arbitrary length
    l     read string from input
     <    slice input string at index
      n   newline char

```
> 2 votes

# Answer
# \>\<\>,  ~~44~~  41 bytes

```
i:0(?^l&}21.>ao&~
:o}1&:1-&) ?^
l&21.>~{~

```

Try it online!
> 2 votes

# Answer
## VBA, ~~54~~ 51 Bytes

(-3 bytes now that leading & trailing 0-character lines are confirmed as permitted)

```
x=Len([A1]):For i=-x To x:?Left([A1],x-abs(i)):Next

```

Just a simple loop from -Length to Length, omitting that many Absolute characters from the end each time

Input is cell A1 of the ActiveSheet. Output and Code are in the Immediate window
> 2 votes

# Answer
# Kotlin, 62 bytes

```
{s->s.indices.map{s.take(it+1)}.let{it+it.reversed().drop(1)}}

```

Could probably be golfed more, but this is what I came up with.

Try it online!
> 2 votes

# Answer
# Husk, 6 bytes

```
S+o↔hḣ

```

Try it online!

Takes input as an argument.

```
S      Apply the first argument to the third argument and to the second argument applied to the third argument:
 +     concatenation,
 o     the composition of
  ↔    reversal
  h    with removal of the last element,
 ḣ     every prefix of
       the input.

```

...I may need to not try to explain combinators in plain English.
> 2 votes

# Answer
**C, 78 bytes**

```
#define f;printf("%.*s\n",i,d));
i;y(char*d){for(;i++<strlen(d)f for(i--;i--f}

```
> 2 votes

# Answer
# Pyth, 10 bytes

```
j+._zt_._z

```

Try it online!

```
j          # Join the final array with newlines and print
 +         # Join the two resulting arrays:
  ._z      #   1. All prefixes of the input (z)
     t     #   2. Remove the first element (full word)
      _    #      of the reverse
       ._z #      of all prefixes of the input (z)

```

Thanks to ASCII-only for helping get the bytes down!
> 2 votes

# Answer
# Python 3, ~~79~~ 72 bytes

*Thanks Jo King for helping me save 7 bytes*

I'm a bit late to this golf, but I was bored and didn't see a Python 3 one that gave a printable string and not a list. This isn't exactly very short but this is my first code golf post :)

```
lambda x:'\n'.join(x[:[i,len(x)-i][i>len(x)]]for i in range(1,len(x)*2))

```

Try it online!
> 2 votes

# Answer
# Scala, 41 bytes

```
s=>s.inits.toSeq.reverse++s.inits.drop(1)

```

Try it online!

# Scala, ~~61~~ 57 bytes

```
s=>1.to(2*s.size-1).map(x=>s.take(s.size-(s.size-x).abs))

```

Try it online!

* -4 thanks to user!
> 2 votes

# Answer
# Canvas, 3 bytes

```
［］─

```

Try it here!
> 2 votes

# Answer
# Branch, 32 bytes

```
,[[^]/[./]10.,]^[0^[^]/[./]10.^]

```

Try it on the online Branch interpreter!

## Explanation

```
,                 Read a character from STDIN
[            ]    While true (while input is not EOF)
 [^]              Keep going up until we hit 0; this is the parent of the first input node
    /             Go to the input node
     [./]         While true, output the node and descend; outputs all input at this point
         10.      Output 10 (newline)
            ,     Read the next character
^                 Go up one space (this puts us on the last input node)
[              ]  While true (while we haven't deleted all of the input yet)
 0^               Zero the current value and go up (delete the last character)
   [^]/           Go to the top again
       [./]       Output all of the input again (gradually gets deleted)
           10.    Output newline
              ^   Go up again; this is the new last input character

```

This can actually be ported quite easily.

# brainf\***, 56 bytes

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

```

Try it online!

Basically does the same thing as above. However, BF can't set the value of a cell like Branch can, so instead we can zero with `[-]` (which doesn't actually work well in Branch because `long long int` can take a long long time to zero if its initial value is `-1`) and then to get `10`, we can just do `+` 10 times after zeroing.
> 2 votes

# Answer
# Vyxal `j`, 3 bytes

```
¦øm

```

Try it Online!

-3 thanks to lyxal

```
¦   # Prefixes
 øm # Palindromised
    # Joined by newlines

```
> 2 votes

# Answer
# Knight, 41 bytes

```
;=aP;=nF;W<=n+1nLaO GaFn;OaW=aSa-LaT1""Oa

```

Nothing too fancy, we just print out the first half, then the middle, then the second.

```
; = a PROMPT # read stdin
; = n FALSE # will coerce to `0` within the `WHILE` condition, but saves us a space from `=n 0`

# until we're at the length of `a`, print the prefix [0..n] from `a`
; WHILE < (=n + 1 n) (LENGTH a)
    OUTPUT (GET a FALSE n)

# output the entire thing
; OUTPUT a

# continue removing pieces from the end of `a` until it's empty, and printing `a` in the process
WHILE (= a SUBS a (- LENGTH a TRUE) 1 "")
    OUPUT a

```
> 2 votes

# Answer
# Vyxal `j`, 2 bytes

```
¦∞

```

Try it Online!
> 2 votes

# Answer
# , 86 bytes

```
x=utf8ToInt(scan(,''))
for(i in c(y<-1:sum(x|1),rev(y)[-1]))cat(intToUtf8(x[1:i]),"
")

```

Try it online!

I'm learning more and more about better ways to manipulate strings in R, so I'm somewhat proud of this answer. The only part I don't like is the for loop portion, which I feel could definitely be golfed.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 76 bytes

```
x=>{for(int i=0,s=1;s+i>0;s=i<x.Length?s:-s)WriteLine(x.Substring(0,i+=s));}

```

Try it online!

Using an iterative approach, as opposed to LINQ.

I did not realize until after I posted, but my answer is pretty similar to aloisdg's answer. Although they are different enough, I might just leave mine too :)
> 1 votes

# Answer
# Python 2, ~~68~~ 63 bytes

```
i=input()
j=[i[:x]for x in range(1,len(i))]
print j+[i]+j[::-1]

```

Try it online!

-5 thanks to @pppery for spotting an unneeded variable declaration.

Longer than the other Python answers but just another way of doing it.
> 1 votes

# Answer
# Java (JDK), 86 bytes

```
s->{for(int i=0,l=s.length();++i<2*l;)System.out.println(s.substring(0,i<l?i:2*l-i));}

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~122~~ 90 bytes

A worse solution of @xnor's

```
u=lambda n,s,b:s[:b-abs(n-b)]+'\n'+u(n+1,s,b)if n<2*b else""
def c(w):print(u(0,w,len(w)))

```

Try it online!
> 1 votes

# Answer
# APL(NARS), 24 char, 48 bytes

```
{⊃{w[⍵]}¨k,1↓⌽k←⍳¨⍳≢w←⍵}

```

test and how to use it:

```
  h←{⊃{w[⍵]}¨k,1↓⌽k←⍳¨⍳≢w←⍵}
        h ,'1'
1
  h '12'
1
12
1
  h '123'
1
12
123
12
1

```

comment: it would build one array of ranges \[(1) (1 2) (1 2 3) ecc\] and the code pass each of them to the function {w\[⍵\]}
> 1 votes

# Answer
# Wolfram Language (Mathematica), 63 bytes

```
(L=2StringLength@#;Do[Print@StringTake[#,Min[n,L-n]],{n,L-1}])&

```

Try it online!
> 1 votes

# Answer
# Factor, 77 bytes

```
: f ( s -- ) dup length [1,b] dup reverse 1 tail append [ head ] with map . ;

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 100 bytes

```
StringJoin[#~Join~Reverse[#][[2;;]]&[Append[Take[#,i],"\n"]~Table~{i,1,Length[#]}&[Characters[#]]]]&

```

Try it online!
> 1 votes

# Answer
# Nim, ~~83~~ 76 bytes

```
let s=readline(stdin)
let l=len(s)
for a in 1..l*2-1:echo(s[0..<l-abs(a-l)])

```

Try it online!

My first time golfing in Nim. All inputs are welcome!

This is a port of my F# and C# answer.

* -7 bytes by using the `[a..<b]` instead of `substr()` (source)
> 1 votes

# Answer
# Röda, 37 bytes

```
f s{{seq 1,#s-1;seq#s,1}|[s[:_],"
"]}

```

Try it online!

Explanation:

```
f s{ /* Function f(s) */
 {
  seq 1,#s-1; /* Push numbers 1..#s-1 to the stream (#s = length of s) */
  seq #s,1    /*   --..--     #s..1    --..-- */
 }|
 [       /* Print the following things for each _ in the stream: */
  s[:_], /*  Substring of s from 0 to _ */
  "
"        /*  Newline */
 ]
}

```
> 1 votes

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

```
a=>{r=[];for(i=0;++i<a.length;)r.push(a.slice(0,i));return[...r,a,...r.reverse()].join`\n`}

```

Try it online!
> 1 votes

# Answer
# Gaia, 3 bytes

```
…ṫṣ

```

Try it online!

As simple as it gets.

```
…	| prefixes
 ṫ	| palindromize
  ṣ	| join with newlines

```
> 1 votes

# Answer
# Zsh, 60 bytes

```
for c (${(s::Oa)1})(($#a))&&a=($c $c$^a $c)||a=$c
<<<${(F)a}

```

Try it online!

```
for c (${(s::Oa)1})          # (s::) splits the first parameter, (Oa) reverses order
    (( $#a )) &&             # if $a is not empty, then
        a=($c $c$^a $c) ||   # ...set a to the current character, then the array with
                             # the current character prepended to each element, else
        a=$c                 # ...set a to the current character
<<< ${(F)a}                  # print a; (F) joins on newlines

```
> 1 votes

# Answer
# Python 2, 52 bytes

```
f=lambda s,i=1:s[i:]and[s[:i]]+f(s,i+1)+[s[:i]]or[s]

```

Try it online!

Returns a list of strings.
> 1 votes

# Answer
# CJam, ~~28~~ 29 bytes

```
l_,{_A)<oNo}fA_,{_A)~<oNo}fA;

```

My first CJam answer, so this can probably be golfed quite a lot

Edit: actually made it work correctly, at the cost of a byte

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
Print/@Table[#~StringDrop~-Abs@i,{i,l=-StringLength@#,-l}]&

```

Try it online!

---

Taking input as a list of characters, and returning a list of character lists, **39 bytes**:

```
Table[#~Drop~-Abs@i,{i,l=-Tr[1^#],-l}]&

```

Try it online!
> 1 votes

# Answer
# Brain-Flak, 254 bytes

```
<>(<()>)<>{({}(<()>))<>{({}<>)<>}{}((()()()()()){})(<()>)<>{({}(<()>))(({}<>)<{({}<>)<>}>{})(<()>)<>{({}<>)<>}{}}{}}<>{({}<>)(<()>)<>{({}<>)<>}{}((()()()()()){})(<()>)<>{({}(<()>))(({}<>)<{({}<>)<>}>{})(<()>)<>{({}<>)<>}{}}{}<>}<>{{}}<>{}{}{({}<>)<>}<>{}

```

Try it online!

Harder than expected (or maybe i'm just not very talented in Brain-Flak ^^)

**Explanation:**

```
<>(<()>)<>              push 0 on second stack

                        ### copy words with increasing letter count to second stack
{                       while letters on stack
  ({}(<()>))            push 0 after first letter
  <>{                   move letters up to next 0 from second to first stack
    ({}<>)<>
  }
  {}                    pop 0
  ((()()()()()){})      append newline
  (<()>)                push new 0
  <>
                        ### append word from first to second stack
  {                     While letters on stack
    ({}(<()>))          push 0 after first letter
    (                   move letter on "third" stack for later use
      ({}<>)            move letter to other stack
      <{                move letters up to next 0 from second to first stack
        ({}<>)<>
      }>
      {}                pop 0
    )                   save letter from "third" stack
    (<()>)              push new 0
    <>{                 move letters up to next 0 from second to first stack
      ({}<>)<>
    }
    {}                  pop 0
  }
  {}                    pop 0
}
<>

                        ### copy words with decreasing letter count to second stack
{                       while letters on second stack
  ({}<>)(<()>)<>        move letter and 0 on first stack
  {                     move letters up to next 0 from second to first stack
    ({}<>)<>
  }
  {}                    pop 0
  ((()()()()()){})      append newline
  (<()>)                push new 0
  <>
                        ### append word from first to second stack
  {                     While letters on stack
    ({}(<()>))          push 0 after first letter
    (                   move letter on "third" stack for later use
      ({}<>)            move letter to other stack
      <{                move letters up to next 0 from second to first stack
        ({}<>)<>
      }>
      {}                pop 0
    )                   save letter from "third" stack
    (<()>)              push new 0
    <>{                 move letters up to next 0 from second to first stack
      ({}<>)<>
    }
    {}                  pop 0
  }
  {}                    pop 0
  <>
}

                        ### Tidy up
<>
{{}}                    delete input
<>
{}{}                    pop 0 and newline
{({}<>)<>}              move everything from second to first stack
<>
{}                      pop newline

```
> 1 votes

# Answer
# Java (JDK), ~~107~~ 106 bytes

```
(s)->{int l=s.length(),i=0;var r=new String[2*l-1];for(;i<l;r[i]=r[2*l-i-2]=s.substring(0,++i));return r;}

```

Loops over the characters of the input string and fills the resulting array from both sides.

Try it online!

107 -\> 106: i=0 at initialisation so removed from for loop
> 1 votes

# Answer
# Ly, 43 bytes

```
0>&ir[sp<l&:rp[o]r(10)o>]<rpr[p&s&o(10)o&l]

```

Try it online!

The logic here is to go through each character (codepoint in Ly) of the input string, add it to a second stack, print the accumulated characters, then go back to the input. Once the input is exhausted, start with the "whole string" copy and do the reverse (remove a character, print, loop) until it's empty.

```
0>&ir[sp<l&:rp[o]r(10)o>]<rpr[p&s&o(10)o&l]  #
0                                            # Push 0 on the stack
 >                                           # Switch to stack on the right
  &i                                         # Read input onto the stack as codepoints
    r                                        # Reverse the stack
     [                  ]                    # Loop until stack is empty
      s                                      # Stash the current char
       p                                     # Delete it from the stack
        <                                    # Switch to stack on the left
         l                                   # Load the stashed character
          &:                                 # Duplicate stack on itself
            rp                               # Reverse stack, pop the top (0)
              [o]                            # Print stack until we hit a 0
                 r(10)o                      # Reverse the stack, print a LF
                       >                     # Switch to stack on the right
                         <                   # Time to shrink... Switch left
                          rpr                # Remove 0 at front of stack
                             [            ]  # While stack not empty
                              p              # Delete one character
                               &s            # Stash the whole stack
                                 &o          # Print the stack in order
                                   (10)o     # Print a LF
                                        &l   # Restore the stack

```
> 1 votes

# Answer
# Python 3.8 (pre-release), 96 bytes

```
def f(s):
    for i in (a:=range(len(s))):print(s[:i+1])
    for i in a[::-1][1:]:print(s[:i+1])

```

Try it online!
> 1 votes

# Answer
# Python 3, 65 63 bytes

Returns a list of lines.

```
lambda s:[s[:[i,2*len(s)-i][i>len(s)]]for i in range(len(s)*2)]

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 64 bytes

Here's another JS solution:

```
s=>(l=s.length,f=i=>i<l*2?s.slice(0,i>l?l-i:i)+`
`+f(i+1):"")(1)

```
> 1 votes

# Answer
# Red, 78 bytes

```
func[s][repeat n l: length? s[print copy/part s n]loop l[take/last s print s]]

```

Try it online!
> 0 votes

# Answer
# x86 machine code (Linux), 53 bytes

```
00000000: 89cf 31d2 4252 e814 0000 005a 803c 1100  ..1.BR.....Z.<..
00000010: 75f2 4a52 e806 0000 005a 09d2 75f4 c36a  u.JR.....Z..u..j
00000020: 015b 6a04 58cd 806a 0ab2 0189 e1b0 04cd  .[j.X..j........
00000030: 805e 89f9 c3                             .^...

```

Assembly:

```
section .text
	global func
func:				;Main function with args: char* ecx
					;Clear registers
	mov edi, ecx			;push pointer to original string
	xor edx, edx			;message length, start at 0
	loop_a:				;Increasing length loop:
		inc edx				;increment message length
		push edx			;save message length
		call print_text			;print string with newline
		pop edx				;get message length
		cmp byte [ecx + edx], 0		;If not at end of string:
		jne loop_a			;continue looping
	loop_b:				;Decreasing length loop:
		dec edx				;decrement message length
		push edx			;save message length
		call print_text			;print string with newline
		pop edx				;get message length
		or edx, edx			;If edx != 0:
		jne loop_b			;Continue loop
	ret

print_text:			;Function to print string (pointer in ecx) with newline:
	push 1
	pop ebx				;fd of stdout
	push 4
	pop eax				;syscall #4 (write)
	int 0x80			;run syscall (msg is in ecx)
	push 0xA			;push newline
	mov dl, 1			;set message length to 1
	mov ecx, esp			;set pointer for syscall to top of stack
	mov al, 4			;syscall #4 (write)
	int 0x80			;run syscall
	pop esi				;reset stack pointer
	mov ecx, edi			;get pointer to original string
	ret

```

Try it online!
> 0 votes

# Answer
# Java 8, ~~92~~ 91 bytes

```
s->{for(int i=0,l=s.length();i++<l*2-1;System.out.println(s.substring(0,i<l?i:l-(i-l))));};

```

Try it online!
-1 byte by using a for loop instead of a while
> 0 votes

# Answer
# SAP ABAP (Unicode), 143 bytes

```
FORM i USING s.DATA(w) = 2 * strlen( s ).WHILE w > 0.w = w - 1.IF w < strlen( s ).WRITE:/ s(w).ELSE.WRITE:/ s(sy-index).ENDIF.ENDWHILE.ENDFORM.

```

Pretty straightforward subroutine. I'm using ABAP's substring access `var+offset(length)` and the system variable `sy-index`, which represents the index of the current loop. Other than that it's probably pretty self-explanatory, even though it's ABAP.

---

# SAP ABAP (Non-Unicode), 141 bytes

```
FORM i USING s.DATA(w) = 2 * strlen( s ).WHILE w > 0.w = w - 1.IF w < strlen( s ).WRITE:/ s(w).ELSE.WRITE:/ s(sy(10)).ENDIF.ENDWHILE.ENDFORM.

```

Saving two bytes here by accessing the `index` component of `sy` like a substring, despite it being an integer value. In Unicode systems, characters are obviously multi-byte values, therefore using offsets is not allowed in mixed-type structures like `sy`. However, in a non-Unicode (ASCII-based) system, both digits of a number and characters are represented as one byte each, and offsets are allowed for structures like `sy`.

Conveniently `index` is the first 10-byte component of structure `sy`, so we don't need to use an offset. Otherwise we'd not be able to save *anything* here, as `sy+x(10)` is just as long as `sy-index` \- or even longer if the offset was \>= 10.

---

Output of both programs is obviously the same, screenshot below.
> 0 votes

# Answer
# T-SQL query, 119 bytes

```
SELECT left(@,n)FROM(SELECT*,number/2+1n,len(@)k,number%2-.5m
FROM spt_values)x
WHERE type='P'and n+m<k
ORDER BY(n-k)*m

```

**Try it online**
> 0 votes

# Answer
# PHP, 65 bytes

```
for(;($n=$argn)!=$s.=$n[$i++];$b="$s
$b")$a.="$s
";echo"$a$n
$b";

```

Try it online!

Tests: Try it online!

In a loop creates a word with one letter added to it towards input on each iteration until the word has one letter less than the input.

For example if the input is "Hello" the word in first iteration is "H" and on third iteration is "Hel" and on last iteration is "Hell".

This word is appended to `$a` and prepended to `$b` with a newline. At the end `$a`, input, a newline and `$b` are printed.
> 0 votes

# Answer
# C (clang), ~~56~~ 52 bytes

```
i;f(*s,l){for(i=0;write(1,s,++i<l?i:l--);puts(""));}

```

Try it online!

-4 thanks to @ceilingcat

Takes a string and its length as arguments.
> 0 votes

# Answer
# GolfScript, 27 bytes

```
.1/{0=1$?1$<}%n*.-1%@n+n\+\

```

Try it online!
> 0 votes

# Answer
# Fortran (GFortran), 79 bytes

```
character(99)a
read*,a
k=len_trim(a)
print('(a)'),(a(1:k-abs(i-k)),i=0,2*k)
end

```

Try it online!

Fortran. Always good for string manipulation
> 0 votes

# Answer
# Keg, 37 bytes

```
?1&((⑻|⑩")(⑻|')⑹
,)⑺⑺((⑻|⑩")(⑻|')⑺
,)

```

Try it online!

I decided to try an interesting string shifting approach.
> 0 votes

# Answer
# .+?, 28 bytes

```
((.+).(\n.+)*)
\2\n\1\n\2
$

```

Thanks to JoKing for giving the original regex, which I then golfed a bit.

# Explanation

```
((.+).(\n.+)*)  The full pattern
(            )  Makes group 1 the entire match, used in the replacement
 (.+).          Makes group 2 every character on the first line, except for the last character
      (\n.+)*   Makes it match the rest, so it all will get replaced

\2\n\1\n\2      Replacement
\2              Group 2 (first line except last character)
  \n            Newline
    \1          Group 1 (entire match)
      \n        Newline
        \2      Group 2 (first line except last character)

$               This match always fails. Makes the first pair repeat until it doesn't match, which happens when the first line has less than 2 characters.

```

Try it online! (The second command line argument is input)
> 0 votes

# Answer
# Factor \+ `grouping.extras`, 38 bytes

```
[ head-clump dup reverse rest append ]

```

Try it online!

```
            ! "Hello"
head-clump  ! { "H" "He" "Hel" "Hell" "Hello" }
dup         ! { "H" "He" "Hel" "Hell" "Hello" } { "H" "He" "Hel" "Hell" "Hello" }
reverse     ! { "H" "He" "Hel" "Hell" "Hello" } { "Hello" "Hell" "Hel" "He" "H" }
rest        ! { "H" "He" "Hel" "Hell" "Hello" } { "Hell" "Hel" "He" "H" }
append      ! { "H" "He" "Hel" "Hell" "Hello" "Hell" "Hel" "He" "H" }

```
> 0 votes

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Total Derangement (Difficulty Level: Hard)
**The problem:** Write a function which, given a cycle length `n` and a number of cycles `m`, where 'm' is within `[2, n-2]`, generates `m` random cycles, each of length `n`, and all of which are derangements of each other. Then `n=7`, for example, `m` could be `2, 3, 4, or 5`. All possible sets of `m` cycles of length `n` that fit the criteria should have equal probability of occurring.

**What is a cycle?** Imagine you're hopping around a list. Each element in the list is a number corresponding to another position on the list. Start out at the first element, and update your position to be whatever index is at that element:

```
CycleThrough(list)
{
    pos = 0;
    while(true) { pos = list[pos]; }
}

```

If you can visit every element in the list and get back to the start using this method, it's a cycle. If you can't, it's not. Here are a few examples of cycles:

```
(0)
(1, 0)
(1, 2, 0)
(2, 0, 1)
(1, 2, 3, 0)
(1, 3, 0, 2)
(2, 4, 1, 0, 3)

```

Take the last cycle. It goes `0 -> 2 -> 1 -> 4 -> 3 -> 0`. What isn't a cycle? Take `(4, 0, 3, 2, 1)`\- this isn't a cycle because it goes `0 -> 4 -> 1 -> 0`, and you won't hit `3` or `2`. Or take `(1, 1)` \- it goes `0 -> 1 -> 1 -> 1 -> 1...` and it never gets back to 0, so it's not a cycle.

**What does it mean for two cycles to be deranged?** Lets say you have two cycles, cycle `A` and cycle `B`. If `A[i]` never equals `B[i]`, they're derangements of each other. If you have more than two cycles, they're all derangements of each other if all pairs of cycles are derangements.

The fastest algorithm (in time complexity) wins.

Example outputs for n=5, m=3:

```
{{1, 4, 3, 0, 2}, {3, 0, 4, 2, 1}, {2, 3, 1, 4, 0}}
{{3, 0, 4, 2, 1}, {2, 4, 3, 1, 0}, {4, 3, 1, 0, 2}}
{{3, 0, 1, 4, 2}, {2, 4, 3, 1, 0}, {4, 3, 0, 2, 1}}
{{3, 4, 0, 1, 2}, {1, 2, 4, 0, 3}, {2, 3, 1, 4, 0}}
{{3, 4, 0, 1, 2}, {4, 0, 1, 2, 3}, {1, 2, 3, 4, 0}}
{{4, 2, 0, 1, 3}, {2, 3, 1, 4, 0}, {1, 4, 3, 0, 2}}
{{4, 3, 0, 2, 1}, {2, 4, 1, 0, 3}, {3, 2, 4, 1, 0}}
{{4, 0, 1, 2, 3}, {3, 2, 0, 4, 1}, {2, 4, 3, 1, 0}}
{{3, 0, 1, 4, 2}, {4, 2, 0, 1, 3}, {1, 3, 4, 2, 0}}
{{3, 2, 0, 4, 1}, {4, 0, 1, 2, 3}, {1, 4, 3, 0, 2}}

```

Example outputs for `n = 4...12, m = n-2`

```
{{2, 3, 1, 0}, {3, 2, 0, 1}}
{{4, 0, 1, 2, 3}, {1, 2, 3, 4, 0}, {2, 3, 4, 0, 1}}
{{4, 2, 5, 1, 3, 0}, {2, 5, 4, 0, 1, 3}, {3, 4, 1, 5, 0, 2}, {5, 3, 0, 4, 2, 1}}
{{6, 3, 5, 0, 1, 4, 2}, {1, 5, 4, 2, 6, 3, 0}, {5, 2, 3, 6, 0, 1, 4}, {4, 0, 6, 1, 5, 2, 3}, {3, 6, 1, 4, 2, 0, 5}}
{{7, 0, 3, 6, 1, 2, 4, 5}, {6, 2, 0, 7, 5, 1, 3, 4}, {1, 5, 4, 0, 7, 6, 2, 3}, {5, 3, 6, 4, 0, 7, 1, 2}, {4, 6, 7, 2, 3, 0, 5, 1}, {3, 7, 1, 5, 2, 4, 0, 6}}
{{2, 3, 6, 8, 0, 4, 1, 5, 7}, {8, 5, 0, 2, 1, 6, 7, 3, 4}, {3, 2, 4, 5, 7, 1, 8, 6, 0}, {4, 6, 5, 7, 8, 0, 3, 2, 1}, {1, 8, 7, 4, 6, 3, 2, 0, 5}, {7, 0, 3, 1, 5, 2, 4, 8, 6}, {5, 7, 1, 6, 3, 8, 0, 4, 2}}
{{1, 4, 5, 6, 2, 9, 8, 3, 0, 7}, {4, 2, 7, 1, 9, 3, 5, 0, 6, 8}, {9, 5, 0, 8, 3, 7, 1, 4, 2, 6}, {5, 7, 6, 0, 8, 2, 4, 9, 1, 3}, {7, 6, 8, 9, 5, 0, 3, 1, 4, 2}, {2, 8, 9, 7, 1, 6, 0, 5, 3, 4}, {8, 0, 3, 5, 6, 4, 9, 2, 7, 1}, {6, 3, 4, 2, 0, 1, 7, 8, 9, 5}}
{{3, 4, 1, 5, 8, 9, 0, 10, 6, 7, 2}, {1, 2, 6, 4, 10, 8, 5, 9, 7, 3, 0}, {10, 6, 3, 1, 9, 7, 8, 4, 0, 2, 5}, {8, 3, 0, 7, 2, 6, 10, 5, 9, 1, 4}, {9, 5, 7, 6, 0, 3, 2, 8, 4, 10, 1}, {2, 0, 9, 10, 7, 1, 4, 3, 5, 6, 8}, {6, 7, 5, 8, 3, 4, 1, 2, 10, 0, 9}, {4, 8, 10, 9, 6, 0, 7, 1, 2, 5, 3}, {5, 10, 4, 0, 1, 2, 9, 6, 3, 8, 7}}
{{6, 11, 4, 5, 3, 1, 8, 2, 9, 7, 0, 10}, {1, 4, 8, 9, 10, 11, 5, 3, 7, 6, 2, 0}, {7, 9, 10, 1, 11, 3, 2, 8, 6, 0, 4, 5}, {4, 2, 5, 0, 6, 7, 9, 11, 1, 10, 8, 3}, {10, 8, 7, 6, 5, 0, 4, 1, 3, 11, 9, 2}, {9, 3, 6, 8, 7, 10, 1, 0, 5, 2, 11, 4}, {8, 0, 9, 11, 1, 4, 7, 10, 2, 3, 5, 6}, {3, 6, 0, 10, 2, 9, 11, 5, 4, 8, 1, 7}, {2, 5, 11, 7, 8, 6, 10, 9, 0, 4, 3, 1}, {11, 7, 1, 2, 0, 8, 3, 4, 10, 5, 6, 9}}

```

# Answer
> 2 votes
# Python 3, \\$O((n - 1)!^{m - 1}nm)\\$ expected time

This is a reference answer using a very straightforward and slow rejection sampling algorithm, for the sake of having at least one valid answer. It picks \\$m\\$ random cycles, checks whether they form a valid solution, and repeats from scratch until they do.

Since there exists at least one valid solution, there must exist at least \\$(n - 1)!\\$ valid solutions (by relabeling it), so the probability that \\$m\\$ random cycles happen to be a valid solution is at least \\$\frac{(n - 1)!}{(n - 1)!^m}\\$. So we expect at most \\$(n - 1)^{m-1}\\$ iterations of the loop, with each iteration taking \\$O(nm)\\$ time. (This is a pessimistic analysis that could be improved with a better lower bound on the number of solutions.)

```
import random

def f(n, m):
    while True:
        cycles = []
        for i in range(m):
            order = list(range(1, n))
            random.shuffle(order)
            cycle = [None] * n
            for a, b in zip([0] + order, order + [0]):
                cycle[a] = b
            cycles.append(cycle)

        if all(len({cycle[j] for cycle in cycles}) == m for j in range(n)):
            return cycles

```

Try it online!

# Answer
> 1 votes
# Python3, ~O(n!):

```
import collections, copy, random
def cycles(n):
   q, q1 = collections.deque([([], [0 for _ in range(n)], 0, {}, {*range(n)}, collections.defaultdict(set))]), collections.deque()
   while q:
     result, a, s, d, ac, cache = q.popleft()
     if not ac:
        yield a, cache
        continue
     for i, x in enumerate(a):
       if (s or i) and (i not in d and s not in cache[i]):
          l, _cache = copy.deepcopy(a), copy.deepcopy(cache)
          _d = copy.deepcopy(d)
          l[i] = s
          _d[i] = s
          _cache[i].add(s)
          q.append((result, l, i, _d, ac - {s}, _cache))

def main(n, m):
   cycle, result, cache, seen = [*cycles(n)], [], {}, []
   while 1:
     if len(result) == m and result not in seen:
        yield result
        result, cache, seen = [], {}, seen + [result]
        continue
     c, _cache = random.choice(cycle)
     if all(not cache.get(j, set())&_cache[j] for j in _cache):
        result.append(c)
        cache = {j:cache.get(j, set())|_cache[j] for j in _cache}

```

Try it online!

---
Tags: combinatorics, permutations, fastest-algorithm
---


title: Generate this huge right triangle

text:
# Question
Title: Generate this huge right triangle
Your task is to print out this exact text:

```
-
||
-|-
|---
|-|--
-|-|--
-|-----
|-|-----
|---|-|--
-|-----|--
---|-|-----
|---|-|-----
|---|-----|--
-----|---|-|--
-|-|---|-------
------|---|-----
|-|---------|-|--
---|-----|---|----
-|-----|-|---------
|-|---|-|-----------
|-----------|---|-|--
-|-----|-|---------|--
---|-----|-----|-|-----
|---|-|---------|-------
------|---|-|---|--------
-----|-----|---------|-|--
-|-----|-------|-----|-----
|---|-----|-------|---|-----
--|---------|-|---------|-|--
---|---|-----|-------|---|-|--
-|-----------|-------|---|-----
--|---|-----|-----------|-|-----
------------|-----|---------|----
-|-----|-|-----|---------|-----|--
---|-|-----|-----|---|-|-----------
|---------|-|---|-----|-----|-|-----
------|---|-----|-------|---------|--
-----|---------|-------|-----|-----|--
-|-------|-----|---|-------|---|-------
------|---------|-----------|-|---------

```

It at first look seems meaningless repititions of `-` and `|`, but it has a nice hidden pattern inside it. I won't reveal it now.

Binary matrix or 2D lists are not accepted as output. Exactly this text is required. But output can have trailing whitespace.

You can use any non-number character in place of `-` and `|`

Shortest code wins.

# Answer
> 12 votes
# Python 2, 70 bytes

```
p=n=i=1
while i<41:s='';exec"s+='-|'[p%n];p*=n*n;n+=1;"*i;i+=1;print s

```

Try it online!

> *The `|`s mark the position of primes.*
> The idea here, as with many prime-related tasks in Python, is to use Wilson's theorem. Essentially, \\$ (n - 1)!^2 \bmod n \\$ will equal 1 if \\$ n \\$ is prime, and 0 if it is not. @xnor gives a more in-depth explanation here if you're interested.

# Answer
> 10 votes
# , 29 26 25 bytes

```
({&'-|'/.1 p:#\)@(#~i.41)

```

Try it online!

-3 thanks to an idea from Lynn!

-1 thanks to xash!

# Answer
> 7 votes
# Jelly, 11 bytes

```
40RRȷR¤ṁẒỌY

```

Try It Online!

> The `|`s are at prime indexes

I figured out the pattern by smash-printing the rows into one flat string and realizing that the distribution looked familiar :P I had another idea to use base conversion but I decided to flatten the string first and then noticed.

Leaky Nun has two tricks in their answer \- firstly, that you can take the range up to `1000` (which is shorter) since `mold` will discard extras, and secondly, I didn't notice other characters were allowed, so the digraph nilad `ØA` is shorter. Jonathan Allan also noticed that we can just use `chr` and output the unprintables 0x00 and 0x01, so thanks to both of them for the byte saves. Please go upvote Leaky Nun's answer as well.

```
40RRȷR¤ṁẒỌY  Main Link (Niladic)
40           Start at 40
  R          Range; [1, 2, ..., 40]
   R         Range; [[1], [1, 2], [1, 2, 3], ...]
       ṁ     Mold; to the shape of [[1], [1, 2], [1, 2, 3], ...], reshape
    ȷR¤      Range of 1000 ([1, 2, 3, ..., 1000]) - extra elements are discarded
        Ẓ    x => isprime(x)
         Ọ   chr
          Y  Join on newlines

```

There are a couple of ways to go about this idea - you can swap which list you generate first, you can index into a multitude of other strings, you can prime-check before or after molding since it vectorizes and thus doesn't really care what shape it is, etc.

# Answer
> 6 votes
# Jelly, 13 bytes

```
ȷRẒṁ40RR¤ịØAY

```

Try it online!

Uses `Z` and `A` instead of `-` and `|`.

This is basically the same answer as @hyper-neutrino's answer, which was published 3 minutes before mine, but our answers arose independently.

# Answer
> 5 votes
# 05AB1E, 14 bytes

```
A820ÅTüŸ€¦pèJ»

```

Try it online!

-1 byte thanks to ovs

```
A820ÅT>üŸ€¦pèJ»  Full Program
A                Push "abc...xyz"
 820             Push 820
    ÅT           Pop 820; Push [0, 1, 3, 6, 10, ...] (triangular numbers)
      üŸ         Pairwise range; get [[0, 1], [1, 2, 3], [3, 4, 5, 6], ...]
        €¦       For each sublist, remove the first element
          p      Primality; get the 2D list of 1s and 0s
           è     Index into "abc...xyz"
            J    Join each row into a string
              »  Join the result into a multiline string

```

# Answer
> 5 votes
# Jelly, 8 bytes

```
ØYxJĠẒỌY

```

Try it online!

```
ØY         The string "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"
  xJ       Repeat "B" once, "C" twice, "D" thrice... "z" 40 times.
    Ġ      Group indices by values: [[1], [2,3], [4,5,6], …, […820]]
                                     ↑B   ↑C     ↑D          ↑z
     Ẓ     Is prime?
      Ọ    Translate 0,1 into "\x00","\x01"
       Y   Join lines

```

# Answer
> 5 votes
# Excel, 110 bytes

```
=LET(a,SEQUENCE(820),CONCAT(IF(MMULT((MOD(a,TRANSPOSE(a))=0)*1,a^0)=2,"|","-")&IF(MOD(SQRT(8*a+1),1),"","
")))

```

Link to Spreadsheet

```
=LET(a,SEQUENCE(820),                               a = (1..820)
CONCAT(                                             concatenate the following
IF(MMULT((MOD(a,TRANSPOSE(a))=0)*1,a^0)=2,"|","-")& if a is prime (has 2 factors) then "|" else "-"
IF(MOD(SQRT(8*a+1),1),"","                          if a is triangular (8a+1 is a perfect square) then add a line feed
")))

```

# Answer
> 4 votes
# Vyxal `j`, 16 bytes

```
40ɾƛʁƛkA¥›:£æi;ṅ

```

Try it Online!

-1 byte thanks to @hyper-neutrino

> Replace all those characters with numbers from 1, 2 and so on. The |'s are at prime indices. So then it's easy.

> (pxeger spoiled it, though I came to it independently)

# Answer
> 4 votes
# Pyth, 19 bytes

```
jmsm@GP_hkrZ=+ZdS40

```

Try it online!

Uses `a` and `b` instead of `-` and `|`.

# Answer
> 4 votes
# brainfuck, 1249 bytes

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

```

Try it online!

Kind of boring; just a hardcoded solution. I'm trying to create a solution that computes it with the prime relation, but I'm not that experienced in brainfuck and also I'll need to find an interpreter that goes up to 820 if I don't want excessive pain and suffering.

# Answer
> 4 votes
# APL (Dyalog Extended), ~~23~~ 19 bytes

‒1 thanks to Razetime.

Full program.

```
↑⎕UCS{1⍭⍳≢⍵}⍢∊,\⍳40

```

Try it online!

`⍳40`**i**ndices 1 through 40

`,\` prefixes of that; `[1,[1,2],[1,2,3],``,39,40]]`

`{``}⍢∊` apply the following anonymous lambda to the **e**nlisted (flattened) data:

the argument; `[1,1,2,1,2,3,``,39,40]`

the length of that; `820`

> `1⍭` indicate which elements are prime; `[0,1,1,0,1,0,``,0,0]`

`⎕UCS` convert to characters in the **U**niversal **C**haracter **S**et; `[\x00,\x01,\x01,\x00,\x01,\x00,``,\x00,\x00]`

mix the list of strings into a matrix, padding with spaces as necessary to make it rectangular; `["\x00` `","\x01\x01` `",``\x00\x00\x00\x00\x00\x00``\x00\x00"]`

# Answer
> 4 votes
# brainfuck, 223 bytes

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

```

Try it online!

Uses trial division up to 86 to determine every prime up to 820. Outputs `T` for `-` and `V` for `|`.

```
Populate list of 820 numbers not yet considered composite
-[>-<-----]>[>++++[<[[->>>+<<<]>]<+>>>-]<-]

tape is 1 0 0 1 0 0 1 etc 1 0 0 1 0 (0)

Create 85 to test visibility by up to N=86 (which is high enough and short to create)
>>-[--->+<]>

working tape will be 1 0 0 1 0 0 1 etc 1 1 0 1 1 0 (0 or 1) x y 0 0
with x plus y = 85 in first iteration

For all numbers from 85 down to 1: (N is this number plus one)
[

  For all numbers to sieve:
  <<<<<[

    Mark number seen
    >+

    Decrement x and increment y if x is nonzero
    [[>]>]>>[->+>]

    Otherwise, the last number was divisible by N
    >[

      Move y back to x
      [-<+>]

      If this isn't the first time we've seen a multiple of N:
      <<[

        Mark number composite
        -<<<[[<]<]>>[-]-[[>]>]>

      Mark that we've seen a multiple of N
      ]+>>>>

    ]

    Go to next number (for loop termination condition)
    <<<<<<<[[<]<]<

  Repeat until all 820 numbers checked
  ]

  Remove all "seen" markings and "seen multiple of N"
  >+[->>>]

  Copy whatever was left of y back to x and decrement
  <[-<+>]<-
]

Now all numbers have been checked and marked composite if applicable
We are 5 cells right of first number (1) now

Set up counters for triangle shape (x=1 for first row; and y=1 so y is always nonzero)
<<<+<+

Mark 1 as nonprime
<--

For each number
[

  While x is nonzero
  >[

    Move x and y left three cells
    [[-<<<+>>>]>]

    Add 85 to primality indicator to output ASCII
    <<-[---<+>]

    Output and remove number
    <.[-]

    Increment y and decrement x
    <+<-

  ]

  Output newline
  ++++++++++.[-]

  Copy y to x (now one more than it was; restore y=1)
  >[-<+>]+

<<]

```

# Answer
> 3 votes
# Python 3.8 (pre-release), 98 bytes

```
r=range
for _ in r(n:=1,41):s="";exec("s+='-|'[all(n%y for y in r(2,n))and n>1];n+=1;"*_);print(s)

```

Try it online!

-6 bytes thanks to @hyper-neutrino and @pxeger

# Answer
> 3 votes
# Python 3, 105 bytes

```
r=range
for i in r(1,41):
	for j in r(i):n=i*~-i//2-~j;print(end="-|"[all(n%y for y in r(2,n))])
	print()

```

Try it online!

One byte longer than wasif's, but no `exec` trick used here.

# Answer
> 3 votes
# Japt `-R`, ~~13~~ 11 bytes

Uses `f` for composites and `t` for primes.

```
#(õ_ç Ëî°Tj

```

Test it

```
#(õ_ç Ëî°Tj
#(              :40
  õ             :Range [1,40]
   _            :Map each Z
    ç           :  Z spaces (could be any character)
      Ë         :  Map each character
       î        :    Slice the following to length (always 1)
        °T      :      Prefix increment T (initially 0)
          j     :      Is prime? (Returns a Boolean which gets coerced to a string by î)
                :Implicit output joined with newlines

```

# Japt `-R`, 13 bytes

Preserving this version as I quite liked the `ú` trick. Uses `q` for qomposites(!) and `p` for primes.

```
40õ_ç¬Ëú²g°Tj

```

Test it

```
40õ_ç¬Ëú²g°Tj
40õ_              :Map each Z in the range [1,40]
    ç             :  Repeat to that length
     ¬            :    "q"
      Ë           :  Map each character
       ú          :    Left pad
        ²         :    With "p" to length 2
         g        :    Get the character at index
          °Tj     :      As above, with the Boolean this time coerced to 0 or 1
                  :Implicit output joined with newlines

```

# Answer
> 2 votes
# JavaScript (ES7), 78 bytes

A recursive function going from \\$k=820\\$ to \\$k=1\\$ and testing whether \\$\sqrt{8k+1}\\$ is an integer to detect triangular numbers and figure out where line-feeds have to be inserted.

```
f=(k=820)=>k?f(k-1)+'-|'[(g=n=>n%--d?g(n):+!~-d)(d=k)]+[`
`[(1+8*k)**.5%1]]:''

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~101~~ \\$\cdots\\$ ~~98~~ 97 bytes

```
p;r;d;f(n){for(n=r=0;++r<41;puts(""))for(;r*-~r>2*n;printf(L"-|"+p))for(p=d=n++;d>1;p=n%d--&&p);}

```

Try it online!

Saved a byte (and got below \\$100\\$!) thanks to ceilingcat!!!
Saved another byte thanks to Shaggy!!!
Saved yet another byte from Juan Ignacio Díaz!!!

# Answer
> 2 votes
# Vyxal `j`, ~~11~~ 14 bytes

```
40ƛɽ÷Ṡnɾ+æ₁+Cṅ

```

Try it Online!

~~I'm posting this because it's significantly shorter than the other one.~~ I didn't realise the *non-number* rule, but still fairly short.

```
40ƛ            # Map 1...40 to...
   ɽ÷Ṡ         # Sum of 1...n-1
      nɾ+      # Added to each of 1...n, this produces the correct indices
         æ     # Is prime (vectorised)
          ₁+C  # Add 100 and get the corresponding character (d or e)
             ṅ # Joined
               # (j flag) join by newlines

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
∞40L£pçJ»

```

Uses unprintables `\0` and `\1` instead of `-` and `|`.

Try it online.

**Explanation:**

```
∞         # Push an infinite positive list: [1,2,3,...]
 40L      # Push list [1,2,3,...,38,39,40]
    £     # Split the first list into parts with the lengths of the second list
          # (removes any unused trailing items): [[1],[2,3],[4,5,6],...]
     p    # Check for each integer whether it's a prime (1 if it's a prime; 0 otherwise)
      ç   # Convert it to a character with this codepoint: \0 and \1
       J  # Join each inner list together to a single string
        » # And join those strings by newlines
          # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Factor, 75 bytes

```
820 [1,b] [ prime? 43 45 ? ] ""map-as 40 [1,b] [ cut swap print ] each drop

```

Try it online!

* `820 [1,b]` Create a range from 1 to 820 inclusive. 820 is the number of elements in the triangle sans newlines.
* `[ prime? 43 45 ? ] ""map-as` Create a flat version of the triangle as a string, where `43` is the code point for `+` and `45` is the code point for `-`. `|`'s code point has 3 digits so I changed this (as it is allowed by the rules).
* `40 [1,b] [ cut swap print ] each drop` Cut the sequence in two at ever-increasing indices, printing each line after it is cut off from the main sequence.

# Answer
> 1 votes
# Retina 0.8.2, 60 bytes

```

820$*|
.(?<=^\1+(..+))
-
^.
-¶
+`(.)+¶(?=.+$)(?<-1>.)+.
$&¶

```

Try it online! Explanation:

```

820$*|

```

Insert 820 `|`s. (820 = 40 × 41 ÷ 2)

```
.(?<=^\1+(..+))
-

```

Change most of them to `-`s appropriately.

```
^.
-¶

```

Change the first one too, and start building the triangle.

```
+`(.)+¶(?=.+$)(?<-1>.)+.
$&¶

```

Build up each row of the triangle to be one character longer than the previous.

# Answer
> 1 votes
# Charcoal, 25 bytes

```
Ｇ↓→⁴⁰ψ¤⭆⁸²⁰§-|﹪ΠＥ⊕ι∨λ±¹⊕ι

```

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

```
Ｇ↓→⁴⁰ψ

```

Draw an empty triangle of side 40. (Unfortunately Charcoal doesn't have a 1-byte shortcut for a triangle in this orientation.) The `y` variable is the null byte, which has a special meaning for the `Fill` function, in that it counts as a fillable area.

```
¤⭆⁸²⁰§-|﹪ΠＥ⊕ι∨λ±¹⊕ι

```

Calculate the first 820 factorials, negate them, reduce them modulo the incremented index, and index the results into the string `-|`. Use this to fill the triangle drawn above. (Charcoal's `Fill` works by painting the string across the region to be filled, rather than repeating it horizontally and vertically. See @ASCII-only's answer to Bake a slice of Pi for another example of how it works.)

# Answer
> 1 votes
# Perl 5, 73 bytes

```
say join($/,map$"x$_,1..40)=~s/./!$n++|(grep$n%$_==0,2..$n-1)?"-":"|"/ger

```

Try it online!

```
say                         # print triangle string, say adds a \n at the end
join($/,map$"x$_,1..40) =~  # make multi-line triangle
                            # of $" (spaces) and $/ (newlines)
s/ /                        # replace spaces
  !$p++                     # count position, ! prevent first from becoming "|"
  |                         # bit-or instead of || or 'or'
  (grep $p%$_==0, 2..$p-1)  # check if $p position is a prime
  ? "-"                     # replace non-prime $p with -
  : "|"                     # replace prime $p with |
/ger                        # g=replace all, e=eval, r=return triangle to say

```

# Answer
> 1 votes
# Julia 1.0, 76 bytes

```
f(y=1)=1:40 .|>i->print.(y:(y+=i).|>j->"
-|"[j==y||2+(2==sum(j.%(1:j).<1))])

```

Try it online!

# Answer
> 1 votes
# Husk, 10 bytes

```
Cḣ40mȯc¬ṗN

```

Try it online! (but you won't be able to easily view the output of non-printable characters) or Try this online instead to see the output switched to `0` and `1` characters.

Derived independently to Kevin Cruijssen's 05AB1E answer, but it turns-out to use almost exactly the same approach... Unfortunately Husk's prime-checker  returns the index in the list of primes, rather than `1` or `0`, costing one extra byte.

```
    mȯ       # map over
         N   # the infinite list of integers:
      c      # character corresponding to
       ¬     # logical NOT of
        ṗ    # index in list of primes;
C            # now cut into substrings
 ḣ40         # with lengths of 1..40

```

# Answer
> 0 votes
# BBC BASIC, 147 bytes

```
L=820
T=1
C=0
F.N=1TOL
IFFNF(N-1)^2MODN=0TH.P."-";:EL.P."|";:ENDIF
C+=1
IFC=T TH.
T+=1
C=0
P.';
ENDIF
N.N
END
DEF FNF(A)IFA=1ORA=0TH.=1
=A*FNF(A-1)

```

I won't lie, this is definitely not the best algorithm, but I did at least golf it down as much as I could.

# Answer
> 0 votes
# Haskell, 134 bytes

```
[]#n=[]
a#n=take n a:drop n a#(n+1)
main=putStrLn$foldl(\a b->a++'\n':b)"-"$["|-"!!fromEnum(0`elem`map(x`mod`)[2..x-1])|x<-[2..820]]#2
```

Attempt This Online!

---
Tags: code-golf, string, kolmogorov-complexity
---


# Question
Title: Write a program that always outputs "2012" - even if it's modified!
This idea is not mine, though I don't know where it originated. I once met it in a programming contest very long ago (1998, if I remember correctly). The task is to write a program in your favorite language that outputs `2012` **and only** `2012`. The catch is that the program must still output `2012` after any **one** of its characters is modified. The modification can be either insertion, deletion or replacement. Of course, the modification will be such that the program is still syntactically valid.

Since I don't know all the programming languages, I have to ask the audience to help me and test the answers submitted.

**Added:** Many have commented that my definition of acceptable modifications is too vague. Here's my second attempt: **The allowed modifications will leave your program syntactically valid and will not cause it to crash.** There, I think that should cover all the compile-time, link-time and run-time errors. Though I'm sure that there will be some odd edge case in some language anyway, so when that comes up we'll look at it individually.

# Answer
# C, 53 characters

```
main(){register*a="2012";(puts("2012"==a?a:"2012"));}

```

A bit longer than the scripting language answers, and follows the same basic principle. Relies on the fact that due to the constraints of C's syntax, the only letters that would be possible to change without making the program invalid are within the strings!

**Edit:** Shaved off 4 characters.

**Reedit:** Robustness increased, shaved off one character.

**Re-redit:** Longer, but more robust. Just try your `&` now! (Correctly this time).

**Update:** Shortened a bit; defeats most approaches seen so far.

~~**Update:** Changed int to void; should defeat the last possible approach to break it I can think of.~~

~~**Update:** I thunk of another approach; replacing the last `a` (may it rot) with `0`; using two-letter names should deal with that problem.~~

**Update:** Last update revoked; assuming changes causing runtime errors are disallowed; `a` will work just fine.

**Update:** Backtracking some more; attempting to dereference `*a` will also segfault; so using `void` to tease a compile error out of it should not be necessary.

**Update:** And a final shortening; that relies on the string `"2012"` being placed at but one address (which is common); and that literal strings are read-only (also common).

**Update:** It cost me two characters, but I defeated your puny semi-colon!
> 70 votes

# Answer
## Haskell, 19

```
(\xx@2012->xx)$2012

```

or, as a full program,

## 29

```
main=print$(\xx@2012->xx)2012

```

---

For a bit more fun:
```
(\l@(_:_:t:[])->t:l)['0'..'2']

```

---

To get one that can't be modified in such a way that yields merely a runtime error, we can encode the information in the lengths of lists which can't be modified using just one-character-changes, i.e.
```
map(head.show.length)[[(),()],[],[()],[(),()]]

```

To make it more modifiable (safely), we can also use the number itself as list element – just need to make it strings to prevent exchanging commas for plus':

```
map(head.show.length)[["2012","2012"],[],["2012"],["2012","2012"]]

```

As this string is just the result of the expression, we can also again substitute it with that – not a problem thanks to Haskell's lazyness

## ~~64~~ 72

```
a=map(head.show.length.init)[[a,a,a],[a],[a,a],[a,a,a]]
main=putStrLn a

```

The `init` acts as "minus one, but non-negative" here.

---

We can also include the type system in the redundancy scheme and then write the number in a way that *could* be modified with one-character changes...
```
u :: Enum a => (a,[b])->(a,b)
u(a,[b]) = (succ a , b)
p :: (a,b)->(a,[b])
p(a,b) = (a,[b])

ι :: (Int,())           -- Integral type to make sure you can't make it 0/0
ι = (\n -> (n-n,()))0

twothousandandtwelve = map(head.show.fst) [ u.p.u.p$ι , ι , u.p$ι , u.p.u.p$ι ]

```

(`GHCi> twothousandandtwelve` ≡\> `"2012"`)

You could now change any one `u` to `p` vice versa, but that would always mess up the deepness of list stackings in the second tuple element and thereby trigger a compile-time error.

This idea could be expanded further in such a way that whole texts could be encoded compactly, easy to read and edit, and still safe from modifing single characters.

---

And yet another one...
```
main = print N2012
data Counter = Τv |Πy |Υj |Cε |Ho |Φϑ |Ωm |Sg |Πl |Pt |Yϑ |Γσ |Km |Φz |Εα |Av |Ζρ |Ηρ |Εv |Κs |Rζ |Γϑ |Οc |Dι |Rυ |Λd |Bγ |Wt |Xε |Ωη |Ιa |Hζ |Ed |Qj |Wπ |Κw |Qu |Γο |Oι |Mσ |Ωκ |Yg |Kυ |Aj |Du |Λζ |Nζ |Θτ |Pε |Yf |Βa |Τγ |Qx |Jη |Pδ |Iq |Ωn |Fv |Kl |Ψη |Δj |Θσ |Hd |Θq |Υs |Ht |Fρ |Jh |Lζ |Hμ |Υι |Ρζ |Ρv |Dυ |Wo |Iχ |Iζ |Γy |Kr |Sσ |Iμ |Μο |Xw |Εμ |Cσ |Yξ |Aq |Jf |Hσ |Oq |Hq |Nυ |Lo |Jκ |Ρz |Οk |Θi |Θα |Αη |Gh |Lξ |Jm |Ων |Zu |Μc |Qη |Κγ |Αψ |Χζ |Hρ |Γρ |Uϑ |Rj |Χγ |Rw |Mω |Πζ |Θρ |Ωd |Υh |Nt |Tη |Qψ |Θω |Εχ |Iw |Σx |Ηn |Mτ |Xt |Yx |Φε |Hh |Wη |Mf |Ψχ |Νγ |Βξ |Aϑ |Qp |Τϑ |Φm |Uy |Gy |Cd |Bχ |Λl |Οτ |Εa |Df |Li |Aι |Yi |Νκ |Vc |Γx |Φρ |Φp |Nξ |Kf |Tw |Λξ |Φn |Λa |Oψ |Υχ |Fψ |Xω |Τq |Οσ |Σj |Θψ |Το |Νr |Ιπ |Τi |Dτ |Φf |Μn |Χm |Ηε |Wa |Αχ |Uδ |Λf |Ρu |Qk |Wα |Uρ |Τζ |Lg |Qy |Τν |Jϑ |Βδ |Mε |Μι |Πβ |Bη |Eκ |Κz |Ηh |Fδ |Σp |Εγ |Qφ |Μτ |Νχ |Ψν |Pw |Χz |Εϑ |We |Nπ |Tυ |Wg |Bh |Tρ |Ζν |Λm |Ag |Dσ |Πι
                |Oη |Nν |Χl |Χp |Sξ |Πt |Οϑ |Wο |Yη |Cp |Tm |Ξs |Εβ |Ιb |Ρρ |Fs |Um |Ep |Jλ |Rρ |Ρξ |Ua |Οq |Γξ |Zη |Nη |Qτ |Nc |Ez |Xσ |Yφ |Ρy |Yε |Ετ |Φκ |Λω |Ωα |Μκ |Φw |Mt |Tk |Sf |Ηξ |Οb |Νπ |Κε |Mι |Kz |Vi |Ξx |Ψs |Αο |Qδ |Kt |Aσ |Οm |Ψδ |Λγ |Ακ |Hα |Wϑ |Τμ |Γγ |Jδ |Ικ |Ηϑ |Μp |Zo |Κn |Qz |Δe |Pe |Jο |Qι |Tu |Jν |Ξμ |Πω |Αm |Θw |Nε |Dy |Zξ |Υα |Dβ |Hο |Χv |Gr |Ωl |Jb |Σl |Vζ |Ξ  |Nx |Qs |Βh |Qg |Νx |Co |Rσ |Νυ |Χg |Ρt |Wy |Ηκ |Οa |Yμ |Uj |Uξ |Op |Μr |Ζα |Ξw |Mυ |Ar |Ργ |Zζ |Sv |Vy |Βo |Κι |Vϑ |Ξι |Uζ |Fμ |Su |Ιξ |Fϑ |Hi |Hw |Mv |Χχ |Θg |Sν |Pp |Mπ |Pk |Bκ |Lυ |Ρλ |Ιr |Uλ |Νo |Κο |Nh |Lε |Sw |Ξλ |Zυ |Mr |Bv |Κπ |Aγ |Dv |Pd |Ξσ |Μg |Oπ |Χξ |Nj |Kψ |Ξπ |Mκ |Gn |Ωe |Gγ |Pν |Yz |Nl |Οο |Ic |Pz |Ξf |Νω |Υμ |Ηq |Nw |Θm |Μx |Jε |Φy |Οz |Ξz |Ti |Οψ |Φγ |Tψ |Oγ |Zϑ |Ιk |Σw |Rf |Υi |Ωp |Vr |Υτ |Xl |Οβ |Πb |Δν |Οu |Jα |Ττ |Κl |Pf |Iκ |Gk |Πe |Σu |Δβ |Ωh |Nλ |Ξt |My |Πs |Βr |Mγ |Δω |Le |Zρ |Θv |Σs |Ηd |
               Bn |Κu |Δξ |Pτ |Ηα |Δu |Πμ |Ρh |Bω |Τλ |Gt |Αρ |Sh |Aο |Θδ |Δπ |Wq |Tφ |Γo |Γf |Λβ |Xυ |Mη |Δw |Qυ |Vν |Βτ |Γα |Μm |Μπ |Κζ |Θd |Fε |Ρτ |Οn |Αs |Wu |Ξh |Μz |Αν |Aε |Yq |Τε |Cz |Ωu |Ec |Ds |Wρ |Θϑ |Κp |Τδ |Mδ |Ηy |Go |Sb |Rξ |Σϑ |Yο |Jg |Vh |Kσ |Nδ |Ηψ |Γh |Rk |Eο |Μk |Ζk |Ψο |Ψμ |Zσ |Pβ |Ρd |Us |Hυ |Βi |Mχ |Σr |Βι |Sχ |Zγ |Δα |Sτ |Γp |Ns |Sn |Νn |Pξ |Νa |Sω |Σi |Τφ |Xο |Eδ |Ba |To |Vj |Sl |Κκ |Δh |Τχ |Gυ |Ρϑ |Bs |Dh |Μσ |Vd |Iϑ |Kg |Νμ |Dμ |Σγ |Πg |Γg |Εt |Fa |Ψn |Ρx |Αj |Mβ |Kλ |Ξψ |Fω |Qζ |Θj |Kπ |Gf |Oe |Yυ |Κk |Wω |Bδ |Lο |Cβ |Nf |Ol |Σo |Fn |Τβ |Βω |Dn |Ha |Πλ |Ss |Σy |Kϑ |Lp |Dδ |Dψ |Ωo |Xγ |Χk |Ωσ |Δa |Sκ |Jμ |Κt |Rc |Ηc |Lχ |Oε |Μλ |Cs |Il |Tι |Ra |Zα |Ωr |Ob |Wβ |Ον |Γν |St |Xλ |Kv |No |Rε |Kd |Mν |Np |Ωc |Δζ |Nβ |Zπ |Ok |Vι |Tδ |Vδ |Γz |Χα |Μs |Βυ |Xc |Xo |Vp |Γχ |Υf |Θπ |Πj |Pi |Γj |By |Φk |Υq |Ny |Rο |Γd |Ωj |Αy |Εo |Κy |Uc |Rm |Ph |Αδ |Ιl |Ιx |Δτ |Zt |Nq |Ct |Φi |Uv |Eπ
                |Κm |Rλ |Vu |Χσ |Τn |Μe |Φη |Ξβ |Εz |Σω |Bb |Ψε |Sε |Ρm |Δο |Vξ |Φo |Ωε |Zb |Σc |Dζ |Ξp |Rη |Ιψ |Δσ |Χη |Kj |Eμ |Qν |Ri |Ip |La |Νξ |Αγ |As |Nr |Δi |Oν |Ζx |Xκ |Pr |Ελ |Λb |Ψk |Ωβ |Pl |Ιy |Cμ |Ζc |Αg |Σρ |Dw |Ρq |Ιη |Pζ |Σa |Uq |Ρμ |Lω |Fh |Ζδ |Αd |Cψ |Κσ |It |Qκ |Fν |Αb |Ηg |Ιν |Ls |Jr |Ow |Je |Zx |Ld |Jl |Ζd |Μo |Χτ |Kα |Μβ |Mo |Σλ |Xρ |Μq |Ψb |Νd |Ρβ |Wδ |Μf |Κρ |Ηb |Ξτ |Qα |Λv |Zψ |Φt |Sδ |Εh |Rκ |Rμ |Χι |Κυ |Ηj |Pχ |Pη |Jσ |Ρσ |Ιχ |Kζ |Εδ |Nω |Iψ |Γμ |Vσ |Ψρ |Χυ |Αw |Kn |Al |Gj |Zj |Αc |Aζ |Ζi |Bz |Vπ |Πw |Αu |Qf |Bf |Ξo |Ρε |Λy |En |Ey |Wi |Σχ |Τc |Dχ |Fg |Ρo |Zm |Ψω |Fq |Μa |Ηt |Wc |Kε |Κτ |Χψ |Κβ |Λφ |Κq |Υm |Πx |Pj |Mi |Δy |Κχ |Lϑ |Wτ |Lη |Nd |Ωk |Iπ |Tα |Bο |Uε |Lc |Rp |Θx |Ρη |Lu |Μζ |Εd |Gρ |Χμ |Vγ |Ιζ |Πυ |El |Uk |Hc |Ξξ |Λx |Ιο |Μy |Ζm |Jw |Iε |Σφ |Αk |Σf |Ac |Ab |Αq |Δf |Θκ |Υa |Ζτ |Jc |Xμ |Sι |Κv |Ζj |Ει |Oω |Ηδ |Φv |Dα |Fτ |Ko |Et |Ψζ |Jx |Mk |Th |Βλ |Λχ |Οo |Υπ |
               Cζ |Θy |Λk |Γδ |Iυ |Σξ |Υϑ |Cι |Cχ |Εσ |Βψ |Iα |Τη |Eυ |Lφ |Lδ |Υw |Ξο |Uσ |Δb |Nϑ |Ζγ |Δz |Cο |Mb |Ξy |Γυ |Εk |Αζ |Vα |Τυ |Ιω |Wυ |Cτ |Ιγ |Yω |Ωy |Ηp |Ψψ |Ah |Dq |Βv |Ιw |Ox |Ξv |Οζ |Tχ |Πψ |Qb |Rδ |Aψ |Zμ |Ζg |Ψφ |Nφ |Δρ |Χe |Vχ |Ηυ |Ml |Σσ |Ζμ |Sz |Πκ |Sγ |Kq |Dη |Υk |Dt |Ξe |Sc |Νs |Μv |Ev |Ji |Rχ |Xπ |Αo |Lμ |Gδ |Fσ |Λϑ |Λe |Σb |Id |Hb |Γι |Βz |Sβ |Tg |Ζο |Δk |Dl |Λσ |Κϑ |Aw |Uγ |Lx |Uψ |Hs |Ωχ |Δφ |Wσ |Π  |Εe |Ro |Λο |Ud |Fχ |Δψ |Νh |Θμ |Zd |Kb |Οδ |Ex |Να |Φσ |Φω |Pm |Λυ |Xq |Si |Σδ |Gα |Bu |Βw |Eχ |Ρι |Gβ |Vο |Yh |Σε |Χq |Hι |Re |Zχ |Ζp |Eρ |Ωγ |Bξ |Hδ |Oξ |Γc |Μγ |Wφ |Πη |Wj |Ιq |Γs |Πο |Κj |Un |Rι |Dφ |Τl |Ωz |Pμ |Wr |Gω |Gi |Εu |Σq |Ρl |Iν |Zy |Rb |Νk |Ky |Uκ |Ησ |Hy |Ir |Tp |Εc |Bw |Εο |Cm |Εw |Ψf |Yχ |Ιρ |Hβ |Ιz |Vλ |Εj |Oδ |Qρ |Θν |Aρ |Ov |Zω |Gψ |Ij |Ξη |Ps |Φh |Οg |Dp |Ta |Ty |Οe |Uο |Rγ |Οr |Θp |Hλ |Νι |Vk |Νz |Tl |Ψi |Λs |Hη |Ζκ |Rz |Hx |Fξ |Ξn |Φe |Sπ |Ηw |Dκ |Ζω
                |Sr |Vψ |Ντ |Vω |Lv |Νg |Fκ |Jψ |Ζs |Oβ |Υζ |Δg |Fυ |Yκ |Χd |Zf |Φμ |Lt |Ξd |Oφ |Τp |Κh |Ψx |Vυ |Qπ |Θφ |Nψ |Ρχ |Rx |Υz |Ξκ |Ξχ |Qn |Pu |Υψ |Az |Xj |Σd |Φξ |Ws |Xα |Βm |Βf |Lh |Hv |Aω |Hν |Kχ |Ρψ |Aδ |Χx |Sη |Φx |Cκ |Jz |Dr |Xu |Ηζ |Ξζ |Gτ |Ca |Af |Aν |Bι |Mc |Ψg |Ωv |Ωs |Qω |Mψ |Lλ |Μα |Kμ |Vl |Yσ |Οι |Ve |Dν |Eg |Ιυ |Xι |Zν |Xϑ |Νζ |Ni |Sφ |Se |Ζa |Xδ |Νv |Wι |Jv |Jt |Ιh |Υv |Cη |Τd |Ψι |Τu |Ge |Πc |Bυ |Mϑ |Χλ |Δλ |Σψ |Μϑ |Απ |Vg |Κα |Sψ |Ζz |Λδ |Aκ |Λκ |Ga |Κb |Db |Jo |Τa |Fw |Τs |Βϑ |Eτ |Wk |Ξu |Ψl |Αι |Νψ |Δι |Qμ |Υn |Bτ |Ηs |Yw |Ye |Iο |Dο |Γe |Rβ |Qv |Xs |Ηη |Yo |Χj |Dω |Οπ |Uβ |Mλ |Qh |Fο |Βd |Ζr |Οv |Zφ |Αi |Dλ |Pb |Οx |Rv |Uz |Εν |Ψτ |Na |Aη |Βu |Ιd |Ηm |Υd |Wn |Qσ |Οp |Αr |Ηλ |Σι |Br |Cu |Ωζ |Θγ |Qo |Bρ |Bψ |Zβ |Πφ |Ρκ |Qϑ |Bj |Vε |Zz |Ζϑ |Za |Θt |Τψ |Ρο |Jq |Πf |Jφ |Τα |Xχ |Χn |Vo |Αt |Bg |Gs |Bi |Rϑ |Nι |Ρa |Υr |Υν |Λo |Γφ |Δo |Yρ |Χc |Ξα |Gq |Γm |Ωμ |Ζυ |Wζ |At |Mw |
               Cf |Επ |Fo |Οh |Tσ |Ηv |Sα |Ζq |Dk |Jπ |Ιm |Mj |Oi |Ψa |Qγ |Rn |Dξ |De |Γk |Ψm |Lα |Cl |Θο |Γq |Λc |Tx |Nm |Ki |Υο |Χr |Φs |Κi |Φλ |Vq |Αω |Ch |Tμ |Xb |Ζπ |Ym |Ζn |Eω |Ξj |Υκ |Τg |Uo |Ai |Sy |Τe |Ητ |Tτ |Λg |Bp |Δq |Χo |Pπ |Dγ |Δγ |Yπ |Ys |Ωδ |Ψσ |Sζ |Πξ |Rφ |Hj |Uf |Td |Ξk |Xψ |Οj |Cx |Φπ |Gλ |Φδ |Ej |Yψ |Ae |Φφ |Jγ |Qχ |Ξγ |Δp |Σg |Is |Eσ |Λπ |Cδ |Ιe |Cυ |Oh |Hm |Tb |Qi |Οl |Bε |Eψ |Hn |Ja |Σν |Γr |Ηu |Ζξ |Ζb |Nu |Θξ |Κd |Qο |Lq |Λw |Ηf |Kξ |Ευ |Rr |Τm |Εξ |Ψp |Χh |Ξi |Fπ |Μφ |Fu |Cξ |Aα |Pγ |Sk |Cω |Ηr |Αp |Ββ |Bx |Fp |Tζ |Pω |Λp |Lm |Jp |Bl |Φc |Vf |Τz |Εy |Λμ |Rd |Νf |Πρ |Ηx |Μψ |Γη |Bα |Συ |Iσ |Γt |Κξ |Io |Ζφ |Γl |Θf |Γλ |Υγ |Ψh |Xg |Tn |Iu |Bφ |Πχ |Λq |Χπ |Bϑ |Εm |Κφ |Λt |Ιu |Ρs |Ιβ |Ωg |Yν |Lσ |Ζι |Eι |Aτ |Φa |Pα |Θz |Ψκ |Θs |Θη |Ηl |Φζ |Bt |Ρυ |On |Ξε |Tf |Gp |Mα |Μi |Kβ |Σο |Ωξ |Νl |Iz |Fk |Dj |Bπ |Nz |Xr |Mp |Χω |Sϑ |Hu |Αμ |Js |Βn |If |Τw |Ηz |Σz |Po |Yj |Ημ |Yβ |Σm |Do
                |Ηχ |Κg |Θo |Ζh |Ψj |Ψu |Ωφ |Δμ |Γa |Bν |Ιε |Oz |Νq |Υp |Qλ |Υc |Υy |Kc |Kh |Ew |Wγ |Νβ |Ωλ |Οξ |Zι |Yr |Sυ |Γπ |Bm |Μj |Pa |Os |Χδ |Κδ |Εx |Iγ |Eη |Fλ |Tγ |Yλ |Hξ |Φq |Τξ |Ql |Δn |Zn |Ot |Sa |Φψ |Nμ |Ξr |Ξc |Φj |Gl |Oλ |Rπ |Am |Mο |Gx |Fd |Cg |Χu |Lι |Wv |Ζt |Jυ |Pσ |Σκ |Wκ |Pv |Ιg |Ωι |Δx |Φl |Eb |Δυ |Cr |Nχ |Ογ |Νφ |Gu |Ασ |Λi |Rτ |Eh |Xη |Md |Wm |Tt |Πα |Υe |Βk |Ju |Dρ |Χβ |Οs |Γi |Kι |Κe |Mm |Χf |Oκ |Vb |Γβ |Οy |Vv |Νϑ |Hl |Λα |Wξ |Om |Βφ |Ρp |Φβ |Βb |Αυ |Υδ |Χφ |Pλ |Νρ |Υλ |Ul |Kγ |Qc |Νm |Πz |Hφ |Es |Ψπ |Xm |Xξ |Tν |Eλ |Ao |Ak |Ka |Ζη |Xk |Γψ |Βπ |Fβ |Βρ |Xx |Βζ |Iτ |Pϑ |Εb |Ψγ |Τk |Gm |Yn |Xν |Νu |Hϑ |Εr |Τπ |Uw |Mh |Og |Μυ |Tj |Λν |Qm |Xn |Ην |Νi |Kη |Zv |Ιι |Ση |Yk |Dx |Aχ |Ou |Fy |Cα |Θl |Γκ |Ax |Vκ |Cn |Cλ |Ξϑ |Wε |Υl |Ψt |Ωa |Θe |Ξω |Ηo |Ll |Bζ |Kw |Αβ |Δc |Oυ |Βj |Jβ |Νε |Eϑ |Ξg |Tz |Cc |Ry |Sρ |Ψz |Yα |Pq |Υg |Jn |Vμ |Σk |Ck |Ωt |Zg |Pι |Hω |Λλ |Aμ |Wλ |Ιλ |Βc |Ξa |
               Jk |Πϑ |Ιt |Εψ |Hε |Ωϑ |Εη |Ie |Κω |Yc |Iβ |Ου |Hg |Θr |Nn |Uμ |Ζv |Ζχ |Jρ |Pο |Ng |Be |Δv |Fζ |Ρe |Qe |Cq |Κf |Θλ |Tϑ |Ξq |Me |Βq |Oα |Θc |Qr |Δt |Dm |Yu |Ru |Σh |Λr |Yy |Εε |Μχ |Mφ |Δδ |Kφ |Cγ |Ζσ |Iω |Au |Wb |Κc |Πq |Ωω |Pυ |Γn |Nγ |Cv |Βχ |Φg |Gο |Ug |Kο |Βκ |Wμ |Hτ |Hχ |Ue |Οw |Sμ |Sm |Υω |Yb |Χa |Ιi |Κν |Πu |Κψ |Uτ |Lβ |Fj |Pn |Εf |Τσ |Qε |Ψo |Λρ |Oϑ |Πν |Ts |Ηο |Μρ |Ff |Ψβ |Ne |Nκ |Bλ |Bσ |Mx |Πp |Υσ |Ιn |Αz |Fz |Ηa |Uν |Mζ |Δϑ |Yι |Ζe |Ψα |Tο |Βg |Lπ |Ζf |Αλ |Em |Θh |Gπ |Γω |Kω |Tξ |Σn |So |Im |Φυ |Ξb |Ii |Λι |Xz |Kδ |Μω |Uυ |Wf |Χb |Sλ |Lγ |Οη |Ιs |Xβ |Pκ |Bc |Ιp |Od |Αn |Va |Tω |Ζw |Ιτ |Θε |Ρi |Gι |Τh |Υx |Nτ |Δη |Εφ |Kx |Xa |Gν |Ft |Yt |Qd |Gσ |Ξυ |Εs |Nσ |Νc |Λj |Υu |Ρc |Ψξ |Δm |Qβ |Μu |Υb |Nk |Ωτ |Κr |Δd |Iλ |Πa |Ωρ |Χν |Μh |Jξ |Μμ |Fc |Iφ |Zr |Ux |Φb |Πo |Gd |Eζ |Αα |Νν |Λz |Vη |Pψ |Ωf |Lρ |Cb |Ν |Α |Χ |Ω |Zτ |Τκ |Αε |Bβ |Uι |Fi |Ui |Βx |Ωq |Βp |Λh |Uu |Ωw |Xp |Ζβ |Λτ
 | N2012 deriving(Enum); instance Show Counter where show = show . fromEnum

```
> 38 votes

# Answer
## JavaScript

I believe this is runtime error proof, any single change should either result in a compile error or a single alert saying 2012.

Edit: Code would make a runtime error on something like `if("alert(2012 "==r)`, I moved the try section to deal with it.

Edit: Nice one Vilx-, but fixable :-) Now there is a bracket mismatch for inserting that semicolon.

Edit: But then a comma could do the same thing as the semicolon, that is a host of options, I think I have fixed it, but there is an awful lot of code now.

Edit: Simplified a bit.

Edit: One more in an infinite series of bugfixes.

Edit: This kinda feels more long and complicated than bulletproof, but it should at least take care of `~eval` and `!eval`.

```
var q="alert(2012 "
var p=1
try{
    if("alert(2012 "==q){
        if(eval(((p=5,q+")")||alert(2012)))){
            if(p!==5){
                alert(2012)
            }
        }
    }
    else{
        alert(2012)
    }
}
catch(e){
    alert(2012)
}

```
> 14 votes

# Answer
## Perl, 49 chars

```
  do{
use strict;$_=2012;;2012==$_&&0-print||die}

```

Based on J B's answer, but this one **actually satisfies the spec**. An exhaustive check indicates that every one-character deletion, insertion or replacement either leaves the output unchanged or causes the program to crash when run (as indicated by a non-zero return value and output to stderr), at least as long as insertions and replacements are restricted to printable ASCII characters.

(Without the restriction, the task is impossible in Perl: a little-known feature of the Perl parser is that it stops when it encounters a Ctrl-D or a Ctrl-Z character, so inserting either of those in front of any file turns it into a valid Perl program that does nothing.)

**Edit:** Shaved off one more char by replacing `1==print` with `0-print`.
> 14 votes

# Answer
## Brainfuck

I am trying to convince myself that this is possible, and I am fairly certain I may have stretched it a bit too far. I have made a few assumptions about my environment:

1. An infinite loop is considered a 'crash'. A similar condition could possibly be achieved by decrementing past zero or to the left of memory location zero in certain interpreters. Many interpreters are difficult to crash at runtime. I avoid the halting problem by using only the simplest, most obvious infinite loop.
2. Unmatched square braces are considered a compile error.
3. This will only work in an environment where the program's output is piped back to it's own input. I use that to verify that it did indeed output '2012'. This is the only way I could get around simply deleting one of the output characters.

Unfortunately, if you get any stricter I fear this will be impossible. Here is my solution:

```
++++++++++++++++++++++++++++++++++++++++++++++++++
.--.+.+.
,--------------------------------------------------[]
,------------------------------------------------[]
,-------------------------------------------------[]
,--------------------------------------------------[]
,[]EOF = 0

```

Basically, you can change the output code, or the verification code, but not both. One of them is guaranteed to work. If one of them doesn't it will 'crash'.
> 14 votes

# Answer
## Python2

```
import sys;xx='2012';(
1/(sys.stdout.write(xx=='2012' and xx or 2012)==None))

```

I had to change Ray's test script slightly to test this as the stdout redirect was breaking it. Passing empty dicts to exec avoids polluting the namespace

```
exec(prog, {}, {})

```
> 7 votes

# Answer
# Brain-Flak, 44 + 3 = 47 bytes \[Non-Competing\]

This uses Brain-Flak's `-A` flag and outputs the characters `2012` to STDOUT

```
((((((((()()()){}){}){}()){})[()])[()])()())

```

Try it online!

# Alternative, 50 bytes

```
(((((()()()()){}){}){}){})({({}[()])}{}[()()()()])

```

Try it online!

## Explanation

Any single character modification to either of the codes above will cause the program to error.
> 6 votes

# Answer
# Sisi, non-competing

Finally I think I found one of my languages that works. It's horrendously long, and the language is newer than the question, but it still feels like an accomplishment.

```
1 set xx 2012
2 set y xx=2012
3 jumpif y 55
4 set xx 2012
828 set x xx
829 set ax xx
830 set xa xx
831 set axx xx
832 set xax xx
833 set xxa xx
834 set bx xx
835 set xb xx
836 set bxx xx
837 set xbx xx
838 set xxb xx
839 set cx xx
840 set xc xx
841 set cxx xx
842 set xcx xx
843 set xxc xx
844 set dx xx
845 set xd xx
846 set dxx xx
847 set xdx xx
848 set xxd xx
849 set ex xx
850 set xe xx
851 set exx xx
852 set xex xx
853 set xxe xx
854 set fx xx
855 set xf xx
856 set fxx xx
857 set xfx xx
858 set xxf xx
859 set gx xx
860 set xg xx
861 set gxx xx
862 set xgx xx
863 set xxg xx
864 set hx xx
865 set xh xx
866 set hxx xx
867 set xhx xx
868 set xxh xx
869 set ix xx
870 set xi xx
871 set ixx xx
872 set xix xx
873 set xxi xx
874 set jx xx
875 set xj xx
876 set jxx xx
877 set xjx xx
878 set xxj xx
879 set kx xx
880 set xk xx
881 set kxx xx
882 set xkx xx
883 set xxk xx
884 set lx xx
885 set xl xx
886 set lxx xx
887 set xlx xx
888 set xxl xx
889 set mx xx
890 set xm xx
891 set mxx xx
892 set xmx xx
893 set xxm xx
894 set nx xx
895 set xn xx
896 set nxx xx
897 set xnx xx
898 set xxn xx
899 set ox xx
900 set xo xx
901 set oxx xx
902 set xox xx
903 set xxo xx
904 set px xx
905 set xp xx
906 set pxx xx
907 set xpx xx
908 set xxp xx
909 set qx xx
910 set xq xx
911 set qxx xx
912 set xqx xx
913 set xxq xx
914 set rx xx
915 set xr xx
916 set rxx xx
917 set xrx xx
918 set xxr xx
919 set sx xx
920 set xs xx
921 set sxx xx
922 set xsx xx
923 set xxs xx
924 set tx xx
925 set xt xx
926 set txx xx
927 set xtx xx
928 set xxt xx
929 set ux xx
930 set xu xx
931 set uxx xx
932 set xux xx
933 set xxu xx
934 set vx xx
935 set xv xx
936 set vxx xx
937 set xvx xx
938 set xxv xx
939 set wx xx
940 set xw xx
941 set wxx xx
942 set xwx xx
943 set xxw xx
944 set yx xx
945 set xy xx
946 set yxx xx
947 set xyx xx
948 set xxy xx
949 set zx xx
950 set xz xx
951 set zxx xx
952 set xzx xx
953 set xxz xx
954 set xxx xx
955 print xx

```

### About Sisi

Sisi is a toy language inspired by assembly and QBasic. It is good for this challenge because its syntax is extremely limited.

* It has only four commands: `set`, `print`, `jump`, and `jumpif`.
* All commands have fixed arity.
* All lines must have line numbers, which are strictly increasing.
* Expressions are only allowed in `set` statements. They can only contain (at most) one operation, which must be binary. In particular: changing `print xx` to `print -xx` is a syntax error.
* Variable names must be composed of lowercase letters.
* Most importantly: there is *no comment syntax*!

### The program

The core of the program is this part:

```
1 set xx 2012
2 set y xx=2012
3 jumpif y 55
4 set xx 2012
955 print xx

```

We store `2012` in `xx`, then test whether that was successful and store the test result in `y`. If `y` is truthy, jump to line 55. (Jumps to nonexistent line numbers simply fast-forward to the next line.)

### Radiation hardening

* If the assignment in line 1 is modified, then `y` is falsey, the jump doesn't happen, and line 4 sets `xx` to 2012.
* If the assignment in line 2 or the jump condition in line 3 is modified, we don't care: `xx` will get set to 2012 whether we take the jump or not.
* The jump target in line 3 can be changed to as small as 5 or as large as 955. Any possible modification gets it to the `print` on line 955 sooner or later. It isn't possible with one modification to jump backwards (creating a loop) or past the end of the program.
* If the assignment in line 4 is modified, we don't care: line 1's assignment will be correct and we will jump past line 4.
* If line 955 is modified, we may have a problem. The one unfortunate thing about Sisi is that uninitialized variables default to `0`, so a modification like `print ax` isn't an error. The ugly but effective solution is lines 828-954, which assign 2012 to every possible variable with an edit distance of 1 from `xx`. This ensures that any modification to the final `print xx` will still print 2012.
* If a line number is modified, either: 1) it will be out of order and be a syntax error, or 2) it won't affect the program flow. The main modification we might be worried about--changing line 4 to 94, thereby inserting it after the jump to 55--doesn't matter because all it does is assign 2012 to `xx` again.
> 6 votes

# Answer
# T-SQL 2012, 55

```
DECLARE @n CHAR(4)='2012'PRINT IIF(@n='2012',@n,'2012')

```
> 3 votes

# Answer
## **Ruby 1.9** \- 43 chars

```
qq=[:p,2012]
b if qq!=[:p,2012]
send(
*qq)

```

Not tested, so break away.
> 2 votes

# Answer
**Excel, 14 characters** (cheating slightly):

```
{=2012} (in a 2x1 array with one cell hidden)

```

Any valid change to the array will affect the contents of both cells, and attempting to change just one cell triggers an error message.

Of course, this breaks down if you take the view that it's really only one formula, as opposed to 2 formulas that are constrained to be identical.
> 2 votes

# Answer
# Java 7

```
class M{
  static String c(){
    String a = "2012",
           b = "2012";
    return a.equals(b)           // 1
            ? a                  // 2
            : a.equals("2012")   // 3
               ? a               // 4
               : b;              // 5
  }

  public static void main(String[]a){
    System.out.print(c());
  }
}

```

**Explanation:**

1. Without changing anything it will take the following path: 1 → 2 (and it will return `a`'s value of `2012`).
2. If the content of String `a` is modified in any way it will take the following path: 1 → 3 → 5 (and it will return `b`'s unchanged value of `2012`).
3. If the content of String `b` is modified in any way it will take the following path: 1 → 3 → 4 (and it will return `a`'s unchanged value of `2012`).
4. If `a.equals(b)` on @1 is modified to `a.equals(a)`, `b.equals(b)`, or `!a.equals(b)` it will still take the same following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`).
5. If `a` on @2 is changed to `b` it will still take the following path: 1 → 2 (and it will return `b`'s unchanged value of `2012`).
6. If either `a` or `b` is changed to the opposite on the lines 3, 4 or 5 it will still take the following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`)
7. If the content of the String on @3 is modified in any way it will still take the following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`)
8. Changing `M` in `class M` or `a` in `main(String[]a)` to another valid character can be done without any changes to the functionality of the code.
9. Any other change will result in a Compile-error (excluding some of the enters/whitespaces, which can be removed/added).

Try all these modifications here, to verify they all still print 2012.

If you can find any way to break it following OP's rules I'd love to know, so I can think of something to fix it.
Unlike most similar questions where a single char is modified, this question allows the basic structure of the programming language in question to be intact, so Java can finally ~~compete in one~~ enter one (let's face it, Java will -almost- never win anything on this SE xD).
> 2 votes

# Answer
# Taxi, 396 bytes

```
2012 is waiting at Starchild Numerology.2012 is waiting at Starchild Numerology.Go to Starchild Numerology: w 1 r 3 l 2 l 3 l 2 r.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner: w 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery: n 3 r 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office: n 1 l 1 r.

```

Formatted for humans, that's:

```
2012 is waiting at Starchild Numerology.
2012 is waiting at Starchild Numerology.
Go to Starchild Numerology: w 1 r 3 l 2 l 3 l 2 r.
Pickup a passenger going to Equal's Corner.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: w 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: n 3 r 1 r 1 r.
Pickup a passenger going to Post Office.
Go to Post Office: n 1 l 1 r.

```

From reading other answers, the solution seems to be to pick a fragile language, set the value, check the value, print the value.
> 2 votes

# Answer
## Tcl, 55 chars.

```
if {$a=={puts 2012}} [set a {puts 2012}] {
puts 2012
#}

```

Check if the code is unmodified, then execute it, or print `2012`.
I consider accessing a undefined variable as syntax error.

~~## Tcl, 138 Characters
```
set a {set a {$a};if {\$a=={$a}} {puts 2012}};if {[info ex a]&&$a=={set a {$a};if {\$a=={$a}} {puts 2012}}} [subst -noc $a] {
puts 2012
#}

```
Ok, this is a quine variant: either the code is unmodified, then execute it, or simply print `2012`<br>~~

~~The last line is a little bit special: It is a comment, but the `}` closes the brace.~~
> 1 votes

# Answer
## Mathematica 24

this is a simple fix to @Dr.belisarius answer *(unfortunately, I can't add comments yet*)

```
2012//.Except@2012->2012

```

Changing Replace (`/.`) to RepeatedReplace (`//.`) fixes the problem @Dillon found, since `///` is a syntax error.
> 1 votes

# Answer
# SmileBASIC

```
OPTION STRICT
VAR A$=@2012
GOTO A$@2012
IF SHIFT(A$)THEN VAR B
?A$VAR C
B=C

```

First, we enable strict mode. This forces you to declare all variables before using them, and prevents things like changing ?A$ to ?B$.

Next, a string variable called "A$" is created, and the value is set to "@2012". To make sure the value of A$ hasn't been messed with, the program will try to jump to a label, and the only label in the program is @2012.

Now, A$ is definitely "@2012", but before printing it, the @ needs to be removed. SHIFT() removes the first item in a string or array (just like pop(), but from the other end). To discard the value returned by SHIFT, it is passed to an IF/THEN block, which does nothing. Just in case someone tries to comment out that line, we declare a variable "B", which is used later. If the VAR is commented out, the last line will throw an Undefined variable error.

Now, A$ is printed, and there's another VAR to prevent comments. The final line just makes sure the variables B and C have both been declared.
> 1 votes

# Answer
# Sinclair ZX81/Timex TS1000/1500 BASIC, 54 tokenized BASIC bytes used

```
 1 LET A$="2012"
 2 PRINT "2012" AND A$="2012";"2012" AND A$<>"2012"

```

Regardless of the value in `A$` 2012 is still shown on the screen. I have used string literals because it's faster for writing to the screen (in BASIC at least) and also saves BASIC bytes. So `A$` can contain any string value possible on the ZX81 tokenized "one-touch" entry system.
> 1 votes

# Answer
# Rust, 105 bytes

```
fn main(){use std::io::{Write,stdout};stdout().write_all({let a=b"2012";if a==b"2012"{a}else{b"2012"}});}

```

Try it online

Most of the length comes from writing directly to stdout vs using the `print!` macro. Unfortunately, the format string in `print!("{}", x);` can be easily modified and is checked at compile time so you can't pass in the value as a string directly.
> 1 votes

# Answer
# Lenguage, 176848577745260300319721504 bytes

Not really fun though.

No modification/edit a byte: `----------[+>+++++<]>.--.+.+.+`

Add a byte: `----------[+>+++++<]>.--.+.+.-`

Remove a byte: `----------[+>+++++<]>.--.+.+<]`

# JavaScript, 48 bytes

```
q="e=alert(2012)"
q=="e=alert(2012)"?eval(q)+e:w

```

Try it online!
> 1 votes

# Answer
## Haskell, 65

```
import Data.List
nub$filter(\x->x==2012||x==2012)([2012]++[2012])

```

## Perl, 84

```
use strict;use English;$ARG=
2032;s/.*/2012/unless$ARG eq 2012;$SUBSEP=2012;print;

```

Failed approach :

```
use strict;use English;"2012 2012"=~
/2012|2012|2012/;print$MATCH||$MATCH;

```
> 0 votes

# Answer
# C# .NET, 83 bytes

```
class P{static void Main(){var q="2012";System.Console.Write(q=="2012"?q:"2012");}}

```

Try Online
> 0 votes

---
Tags: popularity-contest, source-layout, radiation-hardening
---