title: Make the Mexican Wave

text:
# Question
Title: Make the Mexican Wave
In as few bytes as possible, write a program or function that outputs the following:

```
Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwxyZ
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
Abcdefghijklmnopqrstuvwxyz

```

A trailing newline is permitted. You can find a reference ungolfed Python implementation here.

# Answer
# Pyth, 12 bytes

```
V+Gt_GXGNrN1

```

Demonstration.

In Pyth, `G` is the lowercase alphabet. `+Gt_G` is `abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba`, the character that needs to be uppercased in each row.

`V` sets up a for loop over this string, with `N` as the loop variable.

In the body, `XGNrN1` is a string translation function. `X` translates `G`, the alphabet, replacing `N` with `rN1`, the uppercase version of `N`. `r ... 1` is the uppercase function. This gives the desired output.
> 64 votes

# Answer
# C,73

Sometimes the simplest approach is best: print every character one by one. this beats a lot of languages it really shouldn't.

```
i;f(){for(i=1377;i--;)putchar(i%27?123-i%27-32*!(i/702?i%28-4:i%26):10);}

```

explanation

```
i;f(){
   for(i=1377;i--;)
   putchar(i%27?                 //if I not divisible by 27
     123-i%27-                   //  print lowercase letter from ASCII 122 downards
       32*!(i/702?i%28-4:i%26)   //  subtract 32 to make it uppercase where necessary: above i=702, use i%28-4, below it use i%26
     :10);                       //if I divisible by 27 print a newline (10)
}

```
> 34 votes

# Answer
# Python 2, 69 bytes

```
i=25
exec"L=range(97,123);L[~abs(i)]^=32;i-=1;print bytearray(L);"*51

```

Nice and simple, I think.
> 26 votes

# Answer
# Brainfuck (8bit), 231 bytes

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

```

Ok, so it's never going to be the shortest, but it's the taking part that counts... right?!

Try it here (ensure to tick 'Dynamic memory')
> 21 votes

# Answer
# MS-DOS Binary, 61

This code does not have to be compiled, it will run in MS-DOS if you write it into a file called wave.com . The code in hex:

```
ba3d0189d7b91a00b061aa404975fbb00aaab00daab024aa31f6e8130046
83fe1a75f7be1800e807004e75fae80100c389d3802820b409cd21800020
c3

```

Or, if you prefer something more readable, here is how to produce it using debug.exe (the empty line after the code is important):

```
debug.exe wave.com
a
mov dx,13d
mov di,dx
mov cx,1a
mov al,61
stosb
inc ax
dec cx
jnz 10a
mov al,a
stosb
mov al,d
stosb
mov al,24
stosb
xor si,si
call 130
inc si
cmp si,1a
jnz 11a
mov si,18
call 130
dec si
jnz 126
call 130
ret
mov bx,dx
sub byte ptr [si+bx],20
mov ah,9
int 21
add byte ptr [si+bx],20
ret

rcx
3e
w
q

```
> 13 votes

# Answer
# Ruby: ~~71~~ ~~68~~ ~~65~~ 63 characters

```
puts f=(e=*?a..?z).map{|c|(e*"").tr c,c.upcase},f[0,25].reverse

```

Sample run:

```
bash-4.3$ ruby -e 'puts f=(e=*?a..?z).map{|c|(e*"").tr c,c.upcase},f[0,25].reverse' | head
Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz

```
> 11 votes

# Answer
## Matlab, ~~60~~ ~~58~~ 54 bytes

```
I=32*eye(26);[ones(51,1)*(97:122) '']-[I;I(25:-1:1,:)])

```

With thanks to Dennis Jaheruddin for saving me 4 bytes.
> 10 votes

# Answer
# Scala ~~110~~ 109 characters

```
val a=('a'to'z').map(c⇒('a'to'z').map(v⇒if(v==c)c.toUpper else v).mkString)
a++a.init.reverse foreach println

```
> 8 votes

# Answer
# SWI-Prolog, 136 bytes

```
a:-(R=0;R=1),between(1,26,I),(I=1,R=0;I\=1,nl),between(1,26,J),(R=0,L=I;R=1,L is 27-I),(J=L,K is J+64,put(K);J\=L,K is J+96,put(K)),\+!.

```

Abusing backtracking to loop...
> 8 votes

# Answer
# Haskell ~~100~~ ~~89~~ 88 bytes

```
putStr$map toEnum.(\(h,c:t)->h++c-32:t++[10]).(`splitAt`[97..122]).(25-).abs=<<[-25..25]

```

The lambda helper function `\(h,c:t)` takes a pair of lists of ascii values and concatenates both, but with the first value of the second list capitalized. The main function splits the lowercase alphabet (given in ascii, `97..122`) at every position `0,..,24,25,24,..,0` and calls the lambda in every step. Before printing each value is turned into the corresponding character.
> 8 votes

# Answer
# Haskell, 70 bytes

```
mapM putStrLn[[toEnum$x+sum[32|x+abs y/=90]|x<-[65..90]]|y<-[-25..25]]

```

I revisited this problem 6 years later and saved a bunch of bytes. Character growth!

Try it online!

# Haskell, 81 bytes

Counting bytes the way @nimi did; `f` is an IO action that prints the desired output.

```
x!y|x==min(50-y)y=65|0<1=97
f=mapM putStrLn[[toEnum$x+x!y|x<-[0..25]]|y<-[0..50]]

```
> 8 votes

# Answer
# SQL (postgreSQL), ~~107~~ 101

Generate are series from -25 to 25 and use the absolute value to replace characters with their uppercase version. Thanks to manatwork for the tip about the @ operator.

```
select replace('abcdefghijklmnopqrstuvwxyz',chr(122- @i),chr(90- @i))from generate_series(-25,25)a(i)

```
> 7 votes

# Answer
# Pyth - 18 17 bytes

First pass, probably can be made much shorter. Uses `X` to substitute and `r1` to capitalize.

```
V+KU26t_KXGNr@GN1

```

Try it online here.
> 6 votes

# Answer
# J, ~~31~~ 23 bytes

```
u:|:(97+i.26)-32*=|i:25

```

8 bytes saved thanks to @Mauris.

Try it online here.
> 6 votes

# Answer
# MATLAB - 58 bytes

```
char(bsxfun(@minus,97:122,32*[eye(25,26);rot90(eye(26))]))

```

Similar to Luis Mendo's solution, but using the broadcasting abilities of `bsxfun`.

Taking advantage that in ASCII, the difference between a capital and lower case character is exactly 32 values away from each other, we first generate lower case letters from ASCII codes 97 to 122 which are the ASCII codes from lowercase a to lowercase z respectfully, then create a 51 row matrix that contains the 26 ASCII codes from 97 to 122. Therefore, each row of this matrix contains a numerical sequence of values from 97 to 122. Next, we create another matrix where each ith row of this matrix contains a 32 in the ith column. The first 26 rows of this matrix has this pattern, which is essentially the identity matrix multiplied by 32. The function `eye` creates an identity matrix for you. The last 25 rows of this matrix is the scaled identity matrix rotated 90 degrees.

By taking this custom weighted identity matrix and subtracting this with the first matrix, then converting the resulting ASCII codes into characters, the desired "Mexican Hat" sequence is produced.

# Example Run

```
>> char(bsxfun(@minus,97:122,32*[eye(25,26);rot90(eye(26))]))

ans =

Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwxyZ
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
Abcdefghijklmnopqrstuvwxyz

```

You can also run this example using IDEone's online Octave environment. Octave is essentially MATLAB but free: http://ideone.com/PknMe0
> 6 votes

# Answer
# PHP, ~~87~~ ~~71~~ 69 bytes

Not the shortest one, but it works as intended.
Thanks to @manatwork for a few tips to reduce it's size by a lot.
And thanks to @Blackhole, the size was reduced by 2 bytes.

```
for(;$L=range(a,z),$L[25-abs($i++-25)]^=' ',$i<52;)echo join($L).'
';

```

Not exactly pretty, but works.
> 5 votes

# Answer
# Perl, 51 bytes

50 bytes code + 1 byte command line parameter

```
@a=a..z,@a[-1-abs]=uc@a[-1-abs],print@a for-25..25

```

Can be used as follows:

```
perl -le '@a=a..z,@a[-1-abs]=uc@a[-1-abs],print@a for-25..25'

```

Or online here (note I had to add `,"\n"` to this as I couldn't add the -l arg).

---

**Much longer method** Before the shortened version above, I tried a different method which ended up being pretty chunky. I've left it below anyway for reference.

86 bytes code + 1 byte command line arg

```
$_=join"",0,a..z,1;print s/1//r while s/(([A-Z])|0)(\D)|(.)((?2))(1)/\L\2\U\3\4\6\L\5/

```

First Perl I've ever golfed properly so I imagine there's a lot that can be done with it - please do suggest improvements!

Can be used as followed:

```
perl -le '$_=join"",0,a..z,1;print s/1//r while s/(([A-Z])|0)(\D)|(.)((?2))(1)/\L\2\U\3\4\6\L\5/'

```

Or online here (note I had to add ."\n" to this as I couldn't add the -l arg).

### Explanation

General approach is to use regex substitution to do all the hard work. We start off with:

```
0abcdefghijklmnopqrstuvwxyz1

```

This matches `(([A-Z])|0)(\D)` and gets replaced with `\U\3` (\U changes to uppercase) to give:

```
Abcdefghijklmnopqrstuvwxyz1

```

From this point onwards, we continue to match the same regex and replace with `\L\2\U\3`:

```
aBcdefghijklmnopqrstuvwxyz1
abCdefghijklmnopqrstuvwxyz1
...
abcdefghijklmnopqrstuvwxyZ1

```

Now the second alternation of the regex matches, `(.)((?2))(1)` (which is the same as `(.)([A-Z])(1)`). We replace with `\U\4\6\L\5` to give:

```
abcdefghijklmnopqrstuvwxY1z

```

This continues to match and replace until we reach:

```
A1bcdefghijklmnopqrstuvwxyz

```

and there are no more regex matches.

At each point in the loop we strip off the '1' and print.
> 5 votes

# Answer
## PowerShell 3.0, 82 bytes

```
$(0..25)+$(24..0)|%{$i=$_;[string](@(97..122)|%{[char]@($_,($_-32))[$_-eq$i+97]})}

```
> 5 votes

# Answer
# TIS Node Type T21 Architecture - ~~216~~ 215 bytes

Watch it in action here! There's a `DOWN` in that video that I later golfed to `ANY`, but it's functionally identical.

This language has no concept of strings or characters, so I should point out that I'm using ASCII values, i.e. output begins `97, 66, 67`...`88, 89, 90, 10, 65, 98`...

Here's the code in the format of TIS-100's save data, for the purposes of scoring:

```
@5
ADD 25
L:MOV 27 ANY
SUB 1
JGZ L
MOV 25 ANY
JRO -1
@6
JRO 2
S:MOV 10 ANY
ADD 65
MOV ACC ANY
SUB 90
JEZ S
ADD 26
@9
MOV 32 ANY
ADD UP
L:MOV 0 ANY
SUB 1
JGZ L
@10
MOV UP ACC
ADD ANY
SUB 42
D:JEZ D
ADD 42
MOV ACC ANY

```

**Explanation**
> 5 votes

# Answer
# CJam, 23 bytes

```
51{25-z~'{,97>'[2$+tN}/

```

Try it online in the CJam interpreter.

### How it works

```
51{                  }/ e# For I from 0 to 50:
   25-                  e#   Compute J := I - 25.
                        e#   This maps [0 ... 50] to [-25 ... 25].
      z                 e#   Compute K := abs(J).
                        e#   This maps [-25 ... 25] to [25 ... 0 ... 25].
       ~                e#   Compute L := ~K = -(K + 1).
                        e#   This maps [25 ... 0 ... 25] to [-26 ... -1 ... -26].
        '{,             e#   Push ['\0' ... 'z'].
           97>          e#   Discard the first 97. Pushes ['a' ... 'z'].
              '[2$+     e#   Add L to '['. Pushes 'A' for -26, 'Z' for -1.
                   t    e#   Set ['a' ... 'z'][L] to '[' + L.
                    N   e#   Push a linefeed.

```
> 4 votes

# Answer
# JavaScript ES6, 121 bytes

```
_=>Array(51).fill('abcdefghijklmnopqrstuvwxyz').map((e,i)=>e.replace(/./g,(f,j)=>j==i|i+j==50?f.toUpperCase():f)).join`
`

```

This is really long because it makes more sense to hardcode the alphabet than to use the absurdly long `String.fromCharCode` to generate the characters. Test it out below with the Stack snippet, which uses better-supported ES5 and below.

```
f=function(){
  return Array(51).fill('abcdefghijklmnopqrstuvwxyz').map(function(e,i){
    return e.replace(/./g,function(f,j){
      return j==i|i+j==50?f.toUpperCase():f
    })
  }).join('\n')
}

// Polyfill for ES6-only fill()
Array.prototype.fill = Array.prototype.fill || function(val){
  for(i=0;i<this.length;i++){
    this[i] = val
  }
  return this
}

document.getElementById('p').innerText=f()
```

```
<pre id="p"></pre>
```
> 4 votes

# Answer
# R, ~~78~~ 70

```
M=replicate(26,c(letters,"\n"));diag(M)=LETTERS;cat(M,M[,25:1],sep="")

```

Improved by @MickyT
> 4 votes

# Answer
# C#, 140 139 135 132

```
void f(){int d=1,i=0;var s="abcdefghijklmnopqrstuvwxyz\n";for(;i>=0;i+=d=i==25?-1:d)Console.Write(s.Replace(s[i],(char)(s[i]-32)));}

```

Expanded

```
void f()
{
    int d = 1, i =0;
    var s = "abcdefghijklmnopqrstuvwxyz\n";
    for (; i >= 0; i += d = i == 25 ? -1 : d)
        Console.Write(s.Replace(s[i], (char)(s[i] - 32)));
}

```

Saved 1 byte thanks to @Gunther34567 using a ternary instead of `if`

Saved 4 bytes then nesting that ternary inside the loop and moving the alphabet to the outside of the loop

Saved 3 bytes combining integer declarations thanks to @eatonphil
> 4 votes

# Answer
# Bash: ~~76~~ 66 characters

```
printf -va %s {a..z}
for c in {a..z} {y..a};{ echo ${a/$c/${c^}};}

```

Sample run:

```
bash-4.3$ printf -va %s {a..z};for c in {a..z} {y..a};{ echo ${a/$c/${c^}};} | head
Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz

```
> 4 votes

# Answer
# Linux Assembly, 289

Unfortunately not competitive with high level languages and probably far from optimal, but pretty straightforward. Run it using `nasm -f elf64 -o a.o wave.S; ld -s -o a a.o; ./a` (the resulting binary is just 568 bytes big):

```
section .data
s:db 'abcdefghijklmnopqrstuvwxyz',10
section .text
global _start
_start:
mov esi,0
a:call c
inc esi
cmp esi,26
jne a
mov esi,24
b:call c
dec esi
jnz b
call c
mov eax,1
call d
c:mov ecx,s
sub byte [ecx+esi],32
mov eax,4
mov edx,27
d:mov ebx,1
int 80h
add byte [ecx+esi],32
ret

```
> 4 votes

# Answer
# x86 assembly for DOS, 41 Bytes compiled

Binary:

```
00000000  b9 e6 ff b3 61 b8 61 02  50 38 d8 75 02 24 df 88
00000010  c2 cd 21 58 40 3c 7b 75  ef b2 0a cd 21 41 79 02
00000020  43 43 4b 80 f9 19 75 dd  c3

```

Source code, save as "wave.asm", compile with "nasm -f bin -o wave.com wave.asm" and run with "dosbox wave.com"

```
org 100h
section .text
start:
mov cx,-26
mov bl,'a'
next_line:
mov ax, 0261h
next_char:
push ax
cmp al,bl
jnz lower_case
and al,255-32
lower_case:
mov dl,al
int 21h
pop ax
inc ax
cmp al,'z'+1
jnz next_char
mov dl,0ah
int 21h
inc cx
jns move_left
inc bx
inc bx
move_left:
dec bx
cmp cl,25
jnz next_line
ret

```
> 4 votes

# Answer
# Perl - ~~95~~ 64 bytes

Takes advantage of the fact `\u` makes the next character printed an uppercase in Perl.

```
for$c(0..50){$n=1;print map{++$n==27-abs$c-25?"\u$_":$_}a..z,$/}

```

Thanks to manatwork for saving 31 bytes and fixing it (my previous code did not work.)
> 3 votes

# Answer
# Javascript (ES6), 113 bytes

```
c=-1;while(c++<50){console.log('abcdefghijklmnopqrstuvwxyz'.replace(/./g,(x,i)=>i==c|i+c==50?x.toUpperCase():x))}

```

# 110 bytes

```
for(c=-1;c++<50;)console.log('abcdefghijklmnopqrstuvwxyz'.replace(/./g,(x,i)=>i==c|i+c==50?x.toUpperCase():x))

```

# 102 bytes

Old school is unbeatable unless we'll have range operator/function/generator/whatever in js

```
for(c=-1;c++<50;){for(s='',i=-1;i++<25;)s+=String.fromCharCode(i+(i==c|i+c==50?65:97));console.log(s)}

```

# 100 bytes

Unluckily Math.abs is too long

```
for(c=51;c--;){for(s='',i=26;i--;)s+=String.fromCharCode(c+i==25|c-i==25?90-i:122-i);console.log(s)}

```

# ~~96~~ 94 bytes

Though I've beeing downvoted without explanation I continue my struggle

```
for(c=-26;c++<25;){for(s='',i=26;i--;)s+=String.fromCharCode(c*c-i*i?122-i:90-i);console.log(s)}

```

We can shave off a couple of bytes by rearranging loop instructions:

```
for(c=-26;c++<25;console.log(s))for(s='',i=26;i--;s+=String.fromCharCode(c*c-i*i?122-i:90-i));

```
> 3 votes

# Answer
# awk, 91 bytes

```
awk 'BEGIN{for(i=0;i<51;i++)for(j=0;j<27;j++)printf("%c",j>25?10:i==j||j==50-i?j+65:j+97)}'

```
> 3 votes

# Answer
# Sed: ~~135~~ ~~119~~ ~~116~~ 111 characters

(109 character code + 1 character command line option + 1 character input.)

```
s/.*/abcdefghijklmnopqrstuvwxyz/
h;H;G;H;G;H;g;G
s/.{,28}/\u&/gp
s/$/\t/
:;s/(\w+\n?)\t(.*)/\t\2\1/;t
s/.*Z//

```

Sample run:

```
bash-4.3$ sed -rf mexican.sed <<< '' | head
Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz

```
> 3 votes

# Answer
# Jelly, 12 bytes

```
ØaFŒu⁹¦¥ⱮJŒḄ

```

Try it online!

```
ØaFŒu⁹¦¥ⱮJŒḄ
Øa             Lower case alphabet
       ¥       Combine the last two links into a dyad:
  F              Flatten   (1st link)
      ¦          At index... (2nd link)
     ⁹             right argument to the dyad defined by ¥...
   Œu              Make upper case.
        Ɱ      Do the dyad defined by ¥ at each element of the right argument:
         J     [1...26] (len of the alphabet)
               This gives ["Abc..", "aBc...",... ,"...xyZ"]
          ŒḄ   Bounce. i.e. take the list above, remove the last element, reverse
               and append to the original argument.
               This leaves a list of lines which can be printed properly with Y.

```
> 3 votes

# Answer
# jq `-nr`, ~~77~~ ~~72~~ 70 bytes

The first part up to `min` is taken from manatwork's answer

```
range(51)|[.,50-.]|min|[. as$i|range(26)|.+(.-$i|.?/.*97//65)]|implode

```

Try it online!

**Some comments:**

`range(51)|[.,50-.]|min` generates a sequence of the indices of uppercase letters

`|[ ... ]` maps the inner part for each index and collects the results in one array for each index:
`. as$x` store current uppercase index in `$x`
`range(26)` range from 0 to 25
`.+(.-$i|try./.*97//65)` get the codepoint for that alphabet index, uppercase if it matches `$x`, lowercase if not. `try./.*97` returns `empty` for 0/0, which gets replaced with 65 by `//65` (I think that's how that works)

`|implode` converts each array of codepoints into a string
> 3 votes

# Answer
# jq `-nr`, 58 bytes

```
range(51)-25|fabs as$a|[range(26)+97]|.[25-$a]-=32|implode

```

Try it online with `.*.|sqrt` instead of `fabs`, or try it on https://jqplay.org/ with input `""` and *Raw output*.
> 3 votes

# Answer
# Python 2, 121 bytes

```
f=[];x=0
for i in[map(chr,range(97,123))]*26:l=i[:];l[x]=l[x].upper();f+=[''.join(l)];x+=1
print'\n'.join(f[:-1]+f[::-1])

```

This was weird one because of the need to make a **copy** of `i`.

For reference, here's the output *without* making a copy of `i`:

```
Abcdefghijklmnopqrstuvwxyz
ABcdefghijklmnopqrstuvwxyz
ABCdefghijklmnopqrstuvwxyz
ABCDefghijklmnopqrstuvwxyz
ABCDEfghijklmnopqrstuvwxyz
ABCDEFghijklmnopqrstuvwxyz
ABCDEFGhijklmnopqrstuvwxyz
ABCDEFGHijklmnopqrstuvwxyz
ABCDEFGHIjklmnopqrstuvwxyz
ABCDEFGHIJklmnopqrstuvwxyz
ABCDEFGHIJKlmnopqrstuvwxyz
ABCDEFGHIJKLmnopqrstuvwxyz
ABCDEFGHIJKLMnopqrstuvwxyz
ABCDEFGHIJKLMNopqrstuvwxyz
ABCDEFGHIJKLMNOpqrstuvwxyz
ABCDEFGHIJKLMNOPqrstuvwxyz
ABCDEFGHIJKLMNOPQrstuvwxyz
ABCDEFGHIJKLMNOPQRstuvwxyz
ABCDEFGHIJKLMNOPQRStuvwxyz
ABCDEFGHIJKLMNOPQRSTuvwxyz
ABCDEFGHIJKLMNOPQRSTUvwxyz
ABCDEFGHIJKLMNOPQRSTUVwxyz
ABCDEFGHIJKLMNOPQRSTUVWxyz
ABCDEFGHIJKLMNOPQRSTUVWXyz
ABCDEFGHIJKLMNOPQRSTUVWXYz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYz
ABCDEFGHIJKLMNOPQRSTUVWXyz
ABCDEFGHIJKLMNOPQRSTUVWxyz
ABCDEFGHIJKLMNOPQRSTUVwxyz
ABCDEFGHIJKLMNOPQRSTUvwxyz
ABCDEFGHIJKLMNOPQRSTuvwxyz
ABCDEFGHIJKLMNOPQRStuvwxyz
ABCDEFGHIJKLMNOPQRstuvwxyz
ABCDEFGHIJKLMNOPQrstuvwxyz
ABCDEFGHIJKLMNOPqrstuvwxyz
ABCDEFGHIJKLMNOpqrstuvwxyz
ABCDEFGHIJKLMNopqrstuvwxyz
ABCDEFGHIJKLMnopqrstuvwxyz
ABCDEFGHIJKLmnopqrstuvwxyz
ABCDEFGHIJKlmnopqrstuvwxyz
ABCDEFGHIJklmnopqrstuvwxyz
ABCDEFGHIjklmnopqrstuvwxyz
ABCDEFGHijklmnopqrstuvwxyz
ABCDEFGhijklmnopqrstuvwxyz
ABCDEFghijklmnopqrstuvwxyz
ABCDEfghijklmnopqrstuvwxyz
ABCDefghijklmnopqrstuvwxyz
ABCdefghijklmnopqrstuvwxyz
ABcdefghijklmnopqrstuvwxyz
Abcdefghijklmnopqrstuvwxyz

```
> 2 votes

# Answer
# q (37 characters)

A first cut

```
@[.Q.a;;upper]'[(raze(|:\)til 26)_26]

```
> 2 votes

# Answer
# K5, 47 bytes

```
(`0:)'{`c$(97+!x),(x+65),97+1_x_l}'l,1_|(l:!26)

```

More golfing to come shortly.
> 2 votes

# Answer
## Batch - 284 bytes

```
@!! 2>nul||cmd/q/v/c%0&&exit/b
set a=&for /l %%a in (65,1,90)do (set/aa+=1,b=0&cmd/cexit %%a&set c=!=exitCodeAscii!&for /L %%b in (97,1,122)do set/ab+=1&cmd/cexit %%b&if !a!==!b! (set %%a=!%%a!!c!)else set %%a=!%%a!!=exitCodeAscii!
echo !%%a!)
for /l %%a in (89,-1,65)do echo !%%a!

```

Ungolfed:

```
@echo off
setLocal enableDelayedExpansion
set a=0
for /l %%a in (65,1,90) do (
    set /a a+=1,b=0
    cmd /c exit %%a
    set c=!=exitCodeAscii!
    for /L %%b in (97,1,122) do (
        set /a b+=1
        cmd /c exit %%b
        if !a!==!b! (
            set %%a=!%%a!!c!
        ) else set %%a=!%%a!!=exitCodeAscii!
    )
    echo !%%a!
)
for /l %%a in (89,-1,65) do echo !%%a!

```

To get the alphabets, this uses the `!=exitCodeAscii!` variable generated from new CMD instances (knowing that 65 to 90 is A to Z, and 97 to 122 is a to z). Just hard-coding the alphabets could very well be shorter, but this is much cuter.
> 2 votes

# Answer
# Python 3, 103

```
a,l='abcdefghijklmnopqrstuvwxyz',list(range(26))
for i in l+l[24::-1]:print(a[:i]+a[i].upper()+a[i+1:])

```

or, without hardcoding alphabet:

```
l,a=list(range(26)),''.join(chr(i+97)for i in l)
for i in l+l[24::-1]:print(a[:i]+a[i].upper()+a[i+1:])

```
> 2 votes

# Answer
# jq: 99 characters

(96 characters code + 3 characters command line option.)

```
"abcdefghijklmnopqrstuvwxyz"as$a|range(51)|[.,50-.]|min|$a[:.]+($a[.:.+1]|ascii_upcase)+$a[.+1:]

```

Sample run:

```
bash-4.3$ jq -n -r '"abcdefghijklmnopqrstuvwxyz"as$a|range(51)|[.,50-.]|min|$a[:.]+($a[.:.+1]|ascii_upcase)+$a[.+1:]' | head
Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)
> 2 votes

# Answer
## Groovy, ~~99~~ ~~88~~ ~~78~~ 77 bytes

```
((a='a'..'z')+('y'..'a')).each{println a.join().replace(it,it.toUpperCase())}

```

*Thanks to **manatwork** for helping me trim off ~~11~~ 21 bytes.*
> 2 votes

# Answer
**C (208 characters)**

(my first try at Code Golf)

```
#include<stdio.h>
#define P printf
#define A(i) {for(l='a',p=0;l<='z';++l,++p){if(p==i)P("%c",l-32);else P("%c",l);}P("\n");}
int main(){int i,p;char l;for(i=0;i<26;++i)A(i);for(i=24;i>=0;--i)A(i);return 0;}

```
> 2 votes

# Answer
## **\>\<\>, 48 bytes**

Just playing around with the `.` operator more than anything else.

```
"a"&"a"::&:&=84**-o1+:"{"=6$.
=?;&30.~ao&1+:"{"

```
> 2 votes

# Answer
**C - 110 bytes**

***Golfed***

```
void f(){int i,n=0,c=0;for(;n<51;n++){for(i=0;i<26;i++)putchar((i==c)?i+65:i+97);c+=(n>24?-1:1);putchar(10);}}

```

***Ungolfed***

```
void f()
{
    int i,n,c=0;
    for(n=0;n<51;n++)
    {
        for(i=0;i<26;i++)
            putchar((i==c)?i+'A':i+'a');
        c+=(n>24?-1:1);
        putchar(10);
    }
}

```
> 2 votes

# Answer
# R 72

Since there are no R answers:

```
a=function(i){l=letters;l[i]=toupper(l[i]);l};for(i in c(1:26,25:1))cat(a(i),'\n',sep='')

```
> 2 votes

# Answer
**Scala - 103**

```
(0.to(25)++24.to(0,-1))map{i⇒val a=(97+i)toChar;println('a'to('z')mkString("")replace(a,a.toUpper))}

```

Some fun postfix operator abuse.
> 2 votes

# Answer
## R, 60 59

```
cat(intToUtf8(c(x<-rbind(97:122-diag(26)*32,10),x[,25:1])))

```

Improvement based on the comment by @JayCe.

---

Former version:

```
x=rbind(97:122-diag(26)*32,10)
cat(intToUtf8(c(x,x[,25:1])))

```

This is based on ASCII codes that are transformed to characters.
> 2 votes

# Answer
# Canvas, 9 bytes

```
Ｚ＼──ｌｚ＊；ｎ

```

Try it here!

This also works in the latest version, but didn't before this commit (..yes it was used), so the link is to an older version of Canvas.

Explanation:

```
Z\--lz*;n
Z          push the uppercase alphabet
 \         create a diagonal out of that
  --       palindromize vertically with 1 overlap
    l      get the height of that
     z*    and repeat the lowercase alphabet vertically that many times
       ;n  overlap the diagonals over the lowercase block of alphabet

```

unfortunately `Ｚ＼─ｌｚ＊；ｎ` doesn't work as Canvas is too smart and replaces the `V` in the upside down version with a `^`..
> 2 votes

# Answer
# Charcoal, ~~24~~ ~~12~~ 9 bytes

```
Ｅββ↑↗α‖Ｏ↑

```

-12 bytes thanks to *@ASCII-only*.
-3 bytes thanks to *@Neil*.

Try it online (verbose) or try it online (pure).

**Explanation:**

Print the lowercase alphabet with newline delimiter 26 times:

```
Print(Map(b, b));
Ｅββ

```

Move up once:

```
Move(:Up);
↑

```

Print the uppercase alphabet in an up-right direction:

```
Print(:UpRight, a);
↗α

```

Reflect everything upwards horizontally with one line overlap:

```
ReflectOverlap(:Up);
‖Ｏ↑

```
> 2 votes

# Answer
**VIM, ~~37~~ 35 bytes**

↵ is the enter key

```
:h<_↵jjYZZ51P25@='vUlj'↵26@='vUjh'↵

```
> 2 votes

# Answer
# PowerShell, 53 bytes

```
0..25+24..0|%{($s=[char[]](97..122))[$_]-=32;-join$s}

```

Try it online!

Each iteration makes a fresh array of a-z, capitalizes the correct one by shifting its ASCII value, then joins it into a proper line
> 2 votes

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

```
int i,j;for(;i<1376;j=++i%27)Write((char)(j>25?10:j+(i/27==j|i/27==50-j?65:97)));

```

Try it online!

My answer uses a similar strategy to this C answer, but I came up with it independently.

For the heck of it, here is a solution that decrements the loop variable, (like the C solution), but it is not quite as short as the solution that increments.

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

```
for(int i=1377,j;i-->0;)Write((char)((j=i%27)<1?10:(i/27==j+24|i/27==26-j?91:123)-j));

```

Try it online!
> 2 votes

# Answer
# Vimscript - 41 bytes/keystrokes

```
ia<Esc>qqylp<C-a>q24@qY51pk^qw~jq25@whqs~hjhq25@s

```

Make sure that alphabet increment is enabled:

```
set nrformats+=alpha

```

## Explanation:

`ia<Esc>qqylp<C-a>q24@q` writes down the alphabets from 'a' to 'z'.

`Y50p` copies the line and paste it 50 times.

`k^` moves cursor to letter 'a' on the first line.

`qw~jq` starts recording, changes the 'a' to uppercase moves the cursor down and stops recording

`25@w` replays the record 25 times

`hqs~hjhq` starts recording, moves the cursor to 'y', changes 'y' to uppercase moves the cursor down left and stops recording

`25@s` replays the record 25 times
> 2 votes

# Answer
# Vyxal `j`, 11 bytes

```
kaømƛ:⇧ka∇V

```

Try it Online!

```
ka          # Lowercase alphabet
  øm        # Palindromised
    ƛ       # Map...
     :   ∇V # Replace that character
      ⇧     # With its uppercase
       ka   # In the lowercase alphabet

```
> 2 votes

# Answer
# jq `-nr`, ~~93~~ 89 bytes

```
[range(26)+97]|. as$a|range(51)|[.,50-.]|min|$a[:.]+($a[.:.+1]|[.[]-32])+$a[.+1:]|implode

```

Try it online!

porting manatwork's idea.

-4 bytes from ovs.

# jq `-nr`, 95 bytes

```
[range(26)+97]|implode|. as$i|./""|[.[]as$j|$i|sub($j;$j|ascii_upcase)]|.+reverse[1:]|join("
")

```

Try it online!

removing the variables might increase the size. Having explicit references is useful sometimes.

`-n` is for no input.

`-r` is to output the string raw. Otherwise it is printed with `\n` instead of actual newlines.
> 2 votes

# Answer
# CJam, 26 bytes

```
26,:L_W<W%+{L'af+\_'A+tN}/

```

Try it online

Explanation:

```
26,     Create sequence [0 .. 25].
:L      Store it in variable for later reuse.
_       Copy.
W<      Slice off last element to get [0 .. 24]
W%      Reverse it to get [24 .. 0]
+       Concatenate to get [0 .. 25 .. 0]
{       Loop over position list.
  L'af+   Build [a .. z] by adding 'a to previously saved [0 .. 25]
  \_      Pop position to top, and copy it.
  'A+     Calculate upper case letter by adding 'A to position.
  t       Store upper case letter in sequence.
  N       Add a newline.
}/      End loop over position list.

```
> 1 votes

# Answer
# Mathematica, 104 bytes

```
FromCharacterCode[#~Join~Rest@Reverse@#]<>""&[{##,10}&@@@(97~Range~122~Table~{26}-32IdentityMatrix@26)]

```
> 1 votes

# Answer
## F# - 141

This is my first try in F#. I would love some feedback :)

```
[97..122]@List.rev [97..121]|>Seq.iter(fun x->[97..122]|>Seq.map(fun y->(char(y-if x=y then 32 else 0)))|>System.String.Concat|>printfn "%s")

```
> 1 votes

# Answer
# Clojure, 125 (ugh)

```
(map println(map #(apply str(replace{(char(+ %(int\a)))(char(+ %(int\A)))}%2))(range 26)(repeat 26(map char(range 97 123)))))

```
> 1 votes

# Answer
# F#: 114 characters

Simple, and a little naïve -- can't really think of any other way to shorten the technique I used here. I'm sure there's a different approach that would be shorter.

```
Seq.map(fun i->(for c in 97..122 do printf"%c"(char(if c=i then c-32 else c)));printfn"")<|[97..122]@[122..-1..97]

```

Explanation: iterate the alphabet twice (forward then backwards) with `Seq.map ... [97..122]@[122..-1..97]`, the printing the alphabet each time but with the current character capitalized.
> 1 votes

# Answer
## C++, 151 146 142

Golfed:

```
#include <iostream>
int main(){int a=1,b=0,j;while(b>-1){for(j=0;j<27;j++){std::cout<<(char)(j>25?'\n'j:j==b?'A'+j:'a'+j);}b+=a;b>24?a=-1:a;}}

```

Ungolfed:

```
int main(){
    int a=1,b=0,j;
    while(b>-1) {
        for(j=0;j<27;j++){
            std::cout << (char)(j>25?'\n':j==b?'A'+j:'a'+j);
        }
        b+=a;
        b>24?a=-1:a;
    }
}

```
> 1 votes

# Answer
# Java, 159 158 bytes

```
class A{public static void main(String[]a){for(int b=0;b++<51;)for(int c=70;c++<96;)System.out.print((char)(c+(96-Math.abs(b-26)==c?-6:26))+(c>95?"\n":""));}}

```

## Online demo

Try it online

## Explanation

```
class A {
    public static void main(String[] a) {
        // loop the alphabet two times (2 x 26)
        for (int b = 0; b++ < 51;) {
            // loop from lower character ASCII codes a (97) to z (122)
            // c will be from [71 to 96] (because of condition "c++" before the first iteration)
            for (int c = 70; c++ < 96;) {
                System.out.print(
                    // print character by ASCII code
                    (char)(c + (
                        // if character position matches the wave
                        96 - Math.abs(b - 26) == c
                        // substract 6, because 71 - 6 = 65 = 'A'
                        ? -6
                        // otherwise add 26, because 71 + 26 = 97 = 'a'
                        : 26)
                    ) +
                    // if current character is greater then the 'y' (ASCII 95), also print a new line
                    (c > 95 ? "\n" : "")
                );
            }
        }
    }
}

```

Perhaps there's too much math in this. Someone who can shorten this?
> 1 votes

# Answer
# Kotlin, 121 bytes

```
Array(26){"abcdefghijklmnopqrstuvwxyz"}.mapIndexed{i,s->s.replace(s[i],s[i]-32)}.let{it+it.reversed()}.forEach(::println)

```

Try it online!

Generates array of alphabet string with alphabet size, and then replacing characters to uppercase characters, after concacts resulting list and its reversed version.
> 1 votes

# Answer
# K (ngn/k), ~~27~~ 26 bytes

-1 byte from using @ngn's approach

```
x,1_|x:`c$97++(!26)-32*=26

```

Try it online!

* `=26` build a 26-by-26 unit matrix (with 1's on the main diagonal)
* `+(!26)-32*` convert to matrix of offsets from "a" (e.g. -32 =\> "A", 1 =\> "b", etc.)
* ``c$97+` convert offsets to actual characters
* `x,1_|x:` "mirror" the result vertically
> 1 votes

# Answer
# Python - 272 bytes

```
a=range(97,123)
d=False
i=0
while True:
    if d and i>24:
        i-=1
        continue
    for (x,l) in enumerate(a):
        print(chr(l) if x!=i else chr(l-32),end='')
    i-=1 if d else -1
    if i<0:
        break
    if i>26:
        i=25
        d=True
    print()

```

Try it online!
My first attempt at codegolf, so it definitely could be smaller.
> 1 votes

# Answer
# Zsh, 48 bytes

```
b=({a..z})
for n ($b {y..a})<<<${(j::)b/$n/$n:u}

```

Try it online! Similar to the bash solution but using zsh substitutions.
> 1 votes

# Answer
# Vim, 33 bytes

```
:h<_
jjYZZ51Pqr~jq25@rqlh~hjq24@l

```

Try it online!

### Explanation

More or less combines the approaches of the two existing Vim answers, saving a couple of bytes along the way.

```
:h<_
jjYZZ

```

Yank the lowercase alphabet from the help file.

```
51P

```

Paste it 51 times, leaving the buffer's original empty line at the end.

```
qr~jq

```

Record macro `r`: swap case of the current letter and move right (`~`), then move down one row (`j`).

```
25@r

```

Run macro `r` 25 more times.

```
qlh~hjq

```

Record macro `l`: move left (`h`), swap case of the current letter and move right (`~`), move left again (`h`), and move down one row (`j`).

```
24@l

```

Run macro `l` 24 more times.
> 1 votes

# Answer
# Vyxal `jr`, 8 bytes

```
kA∞ƛ⇩kaV

```

Try it Online!
> 1 votes

# Answer
# Dyalog APL, 23 bytes

```
↑{1⎕C@⍵⎕C⎕A}¨(⍳26),⌽⍳25

```

Attempt This Online!

```
                    ⍳25  integers from 1 to 25
                   ⌽     reverse
                  ,      join with
             (⍳26)       integers from 1 to 26
 {         }¨            for each integer n
         ⎕A               uppercase alphabet
       ⎕C                 casefold
  1⎕C                     convert to uppercase
     @                    at
      ⍵                   index n
↑                        convert nested vector to simple matrix

```
> 1 votes

# Answer
# Java: 918 characters

```
public class Sample{

    public static int i;

    public static int j;

    public static int z;

    public static String[] k={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

public static void main(String args[]){
        for (i=0; i<k.length;i++){
            for(j=0 ;j<k.length;j++){
                if (i==j){
                System.out.print(k[j].toUpperCase());
                }
                else
                System.out.print(k[j].toLowerCase());
            }
            System.out.println();
            }
        for (i=1; i<k.length;i++){
            for(j=0 ;j<k.length;j++){
                if (i==(k.length-(j+1))){
                System.out.print(k[j].toUpperCase());
                }
                else
                System.out.print(k[j].toLowerCase());
            }
            System.out.println();
        }
        }
}

```
> 0 votes

# Answer
# ECMAScript 6 - 114 110 characters

(112 108 + 2 linebreaks)

```
b=(c,d)=>c<26?String.fromCharCode(c==d?c+65:c+97)+b(c+1,d):""
a=i=>b(0,i)+(i?"\n"+a(i-1)+"\n"+b(0,i):"")
a(25)

```

Two recursive functions `a` and `b`:

* `b` creates an alphabet string with the letter at index `d` capitalized. Doesn't take very much advantage of recursion, but fat arrows make this function just a tiny bit shorter than a loop.
* `a` creates line by line anagrams (sort of) of the strings generated by `b`

**EDIT:** Woops! The capitalization is backwards ('z' is capitalized on the first and last line, 'a' in the middle)
> 0 votes

# Answer
# Haskell 128 Bytes

```
import Data.Char
a c=take 701(cycle(toUpper:replicate c id))
f=zipWith($)(a 27++drop 27(a 25))$cycle(['a'..'z']++"\n")
g=f++"z"

```

Not as short as the others but a very different approach. Defines the constant `g` as the string. save to a file and open interactively using `ghci <filename>`. Then enter `g` to the repl.
> 0 votes

# Answer
# Haskell, 78 bytes

```
mapM_ putStrLn[['a'..toEnum(x-2)]++toEnum(x-33):[toEnum(x)..'z']|x<-[98..123]]

```

This code takes for all 'numbers, x from 'a'(+1) to 'z'(+1):

* the letters from a to the letter corresponding to x-2
* the letter x-33 (x-1 uppercased)
* the letters from the letter corresponding to x It concatenes them. We have the list of the strings. We print it.
> 0 votes

# Answer
# Python 3, 103 characters

```
a="abcdefghijklmnopqrstuvwxyz"
for i in range(51):
 x=25-abs(25-i)
 print(a.replace(a[x],a[x].upper()))

```
> 0 votes

# Answer
# Japt v1.4.5 `-R`, 12 bytes

```
;C¬ê £CrX,_u

```

Try it online!

Somehow tied with top Pyth submission.

### Unpacked & How it works

```
;Cq ê mX{CrX,Z{Zu
;                  Use alternative set of initial variables
 C                 "abc...z"
  q ê              Split into chars and palindromify [a,b,...,z,...,b,a]
      mX{          Map...
         CrX,Z{Zu    Replace the char X in C into uppercase

-R                 Join with newline

```
> 0 votes

# Answer
# Python 2, 107 bytes

```
a='abcdefghijklmnopqrstuvwxyz'
for c in range(51):
i=25-abs(25-c)
print a[:i]+a[i].upper()+a[i+1:]

```
> 0 votes

# Answer
# MS-SQL, 135 bytes

```
WITH t AS(SELECT-25n UNION ALL SELECT n+1FROM t WHERE n<25)SELECT
STUFF('abcdefghijklmnopqrstuvwxyz',26-ABS(n),1,CHAR(90-ABS(n)))FROM t

```

Inspired largely by MickyT's postgreSQL solution, but since we can't use `generate_series`, we use a CTE to create a number table, and use `STUFF` to replace each character.
> 0 votes

# Answer
# Yabasic, 93 bytes

An anonymous function that takes no input and outputs to the console.

```
For i=-25To 25
For j=-25To 0
s$=Chr$(122+j)
If j=-abs(i)Then s$=Upper$(s$)Fi
?s$;
Next
?
Next

```

Try it online!

---

### Alternate Solution, 93 bytes

```
For i=-25To 25
For j=-25To 0
s$=Chr$(122+j)
If j+abs(i)Then?s$;Else?Upper$(s$);Fi
Next
?
Next

```

Try it online!
> 0 votes

# Answer
# dc, 83 bytes

```
97sj1sxBDsy[32-]sU[liddlj=UP1+dsiBD>I]sI[97silIxAPljlx+dsjly!=J]dsJx_1sx96syBBsjlJx

```

Try it online!

Bit chunkier than I would have liked. Ultimately we're going to use two macros, `I` and `J`, and they're going to use some counters, `i` and `j`. The counters are decimal values converted to ASCII for printing. Macro `I` (`[liddlj=UP1+dsiBD>I]sI`)handles printing one line of the alphabet, letter at a time, checking each letter to see if it matches and running macro `U` (`[32-]sU`) to uppercase if need be. It runs until it hits 123, just past the letter 'z'. Macro `J` (`[97silIxAPljlx+dsjly!=J]dsJx`) resets `i` to the beginning of the alphabet, runs `I`, prints a linebreak (`AP`), adds the value of `x` to `j`, and keeps running as long as it doesn't match the value of `y`. The first time we run it, `x` is positive 1 and `y` is 123, so we increment until we're past the letter 'z'. After doing that, we put `j` back down to 121 (after `...xyZ` we're supposed to print `...xYz` and not a second `...xyZ`), and set `x` to negative 1 and `y` to 96, running `J` with a decrement and lower bound just below the letter 'a'.
> 0 votes

# Answer
# Python 3, 88 bytes

```
a=list(range(26));[print(''.join([chr([97+x,65+x][x==i])for x in a]))for i in a+a[::-1]]

```

Try it online!
> 0 votes

# Answer
# VBA, 80 bytes

A script that takes no input and outputs to the console.

```
For i=-25To 25:For j=-25To 0:s=Chr(122+j):?IIf(j+Abs(i),s,UCase(s));:Next:?:Next

```
> 0 votes

# Answer
# Lua, 96 bytes

```
for j=1,51 do for i=1,26 do io.write(string.char(i+((j+i==52or i==j)and 64or 96)))end print()end

```

Try it online!

---

```
for j=1, 51 do -- a to z (26) + y to a (25), because the Z doesn't repeat
  for i=1, 26 do -- for each letter
     io.write(string.char(i+((j==52-i or j==i) and 64 or 96))) -- ↴
     io.write(string.char(i+(                               )) -- writes the character represented by the value i+(...) on the ASCII table
                             (j==52-i or j==i)                 -- if the uppercase letter is equal to i or to 52-i
                                               and 64 or 96    -- then sum 64 else sum 96 (because 'A' is 65 and 'a' is 97)
  end
  print() -- jumps to the next line
end

```

If you have any questions, feel free to ask!
> 0 votes

# Answer
# Excel, 101 bytes

Using Immediate Window and Output in Cell`A1:A51`

```
[A1:A51]="=SUBSTITUTE(""abcdefghijklmnopqrstuvwxyz"",CHAR(122-ABS(ROW()-26)),CHAR(90-ABS(ROW()-26)))"

```
> 0 votes

# Answer
# 05AB1E, ~~12~~ 9 bytes

```
AûvAyDu:,

```

The existing 05AB1E answer got deleted for some reason, so I decided to post a new one.

-3 bytes thanks to *@dzaima*.

Try it online.

**Explanation:**

```
A           # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
 û          # Palindromize it: "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"
  v         # Loop over each of its characters `y`
   A        #  Push the lowercase alphabet
    y  :    #  Replace the current lowercase letter `y`,
     Du     #  with it's uppercase variant
        ,   #  Print the modified alphabet with trailing newline

```
> 0 votes

# Answer
# Japt `-R`, 11 bytes

```
;C¬£ChYXuÃê

```

Test it
> 0 votes

# Answer
# ARM Thumb-2 (with libc), 54 bytes

`f7ff fffe` is a 4 byte linker placeholder for `puts`.

Machine code:

```
b5fe 466f 241a 3c01 f104 0161 5539 d1fa
76bc 0038 0025 2d1a d009 bf88 f1c5 0533
5d46 f006 025f 5542 f7ff fffe 557e 3401
2c34 d3ee bdfe

```

Commented assembly:

```
        .thumb
        .arch armv6t2
        .globl main
        .thumb_func
main:
        // Create a 27 byte buffer on the stack by doing a massive push
        // 27 is for the buffer, 1 is padding, and the last is the link register
        // to return from main.
        push    {r1, r2, r3, r4, r5, r6, r7, lr}
        // Create a frame pointer in r7, since sp lacks narrow register offset
        // addressing.
        mov     r7, sp
        // Fill the stack buffer with "abcdefgh....\0"
        movs    r4, #26
.Lfill_loop:
        subs    r4, #1
        add.w   r1, r4, #'a' // wide
        strb    r1, [r7, r4]
        bne     .Lfill_loop
.Lfill_loop_end:
        // r4 is zero now. Serves as both a null terminator and a loop counter.
        // Null terminate the string.
        strb    r4, [r7, #26]
        // The print loop
.Lprint_loop:
        // Load buffer into r0 for puts
        movs    r0, r7
        // Make a copy of r4 into r5
        movs    r5, r4
        // Compare to 26.
        cmp     r5, #26
        // If equal, skip to prevent printing Z twice
        beq     .Lskip_double_Z
        // If r5 is > 26 change it to 51 - r5 to reverse the order.
        it      hi
        rsbhi   r5, #51 // wide
        // Load the byte from the stack
        ldrb    r6, [r0, r5]
        // toupper(r6) -> r6 & 0x5f
        and.w   r2, r6, #0x5f // wide
        strb    r2, [r0, r5]
        // Call puts on our modified buffer
        bl      puts
        // Reset the char we modified.
        strb    r6, [r7, r5]
.Lskip_double_Z:
        // Loop 52 times.
        adds    r4, #1
        cmp     r4, #52
        blo     .Lprint_loop
.Lloop_end:
        // restore stack (clobbering all registers but bionic libc seems to be
        // fine with this) and return by popping the link register into pc.
        pop     {r1, r2, r3, r4, r5, r6, r7, pc}

```
> 0 votes

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


title: Build a code minifier

text:
# Question
Title: Build a code minifier
Pick a programming language.

In that language, write a function or program that takes as input a string of working code (in the same language).

It should return/output a minified version of the input code. The output should be functionally equivalent to the input.

Answers should contain both

1. The code that does the minifying (should be readable/non-golfed)
2. The resulting output after passing your code (that is, the code that does the minifying) in to itself

The shortest **output** wins.

*Edit:* notes explaining the minification methods you used are appreciated.

*Edit:* obviously, minification methods could vary from language to language, but a good-faith attempt at writing a minifier for this challenge would most likely perform actions such as

* Removing unnecessary whitespace
* Removing unnecessary newlines
* Removing comments
* Shortening variable names

# Answer
# Brainfuck

I always had in mind to do this, so here we go:

```
>>>,
[
[->+>+<<]             copy input

<<<+++++++++++++      fill cell with 13 for subtraction
[->+>+>+<<<]          and duplicate some times

>>>[->---<]           sub 39
>----                 43

[                     plus
-
[                     comma
-
[                     minus
-
[                     dot

<<[->>-<<]>>-         60

[                     less than
--
[                     greater than

<<<[->>>--<<<]>>>     86
---                   91

[                     open square bracket
--
[                     closing square bracket

>[-]                  remove copy

]]]]]]]]

>[.[-]>]              the copy has not been removed; print

<<[-]<<<[-]>[-]>      clean up

,]

```

Compresses itself to (144 characters):

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

```

The size of the compressing could probably still reduced a bit. The compression alogorithm itself is near perfect, it's hard to do any more than removing non-`+-[]<>,.`.
> 14 votes

# Answer
## Python 2.6

I tried to implement a basic Python minifier which does the following things:

1. Removing unnecessary whitespace
2. Removing unnecessary newlines
3. Removing comments
4. Shortening variable names

As others stated, the winning criteria (shortest output when run through itself) does not make a whole lot of sense for a minifier if you want to start with a non-golfed solution.

## Original (2591 characters)

```
# imports
import keyword, tokenize, sys, token, itertools

# vars
line = ""
out = [] ; block = []
idx = 0 ; previdx = 0 ; prevdirection = 0
varnames = set() ; imports = set()
t = tokenize.generate_tokens(sys.stdin.readline)
newline = '\n'

# settings
replace_varnames = True

while 1:
    try:
        toknum, tokval, _, _, _ = t.next()
        iskwd = tokval in keyword.kwlist

        if toknum == 1:
            if ''.join(line).lstrip().startswith("import "):
                imports.add(tokval)
            else:
                if not (iskwd or line[-1]=="." or tokval in __builtins__.__dict__.keys() or tokval.startswith("_") or len(tokval) <=2 or tokval in imports):
                    varnames.add(tokval)

        if toknum == 53:
            continue

        if toknum == 4:
            block.append(' '.join(x for x in ("".join(l for l in line if l)).strip().split()))
            line = []

        if toknum == 5 or toknum == 6:
            if out and out[-1] != newline:
                out.append(newline)

            previdx = idx
            idx += (-1,1)[toknum==5]

            indenting = previdx < idx
            dedenting = previdx > idx
            prefix = " " * previdx
            base = ";".join(l for l in block)
            if dedenting and prevdirection == 1:
                out.pop()
                out.append(base)
            else:
                if len(block) > 1:
                    if indenting:
                        out.append(prefix + ";".join(l for l in block[:-1]))
                        out.append(newline)
                        out.append("".join(prefix + l for l in block[-1:]))
                    else:
                        out.append(prefix + base)
                elif len(block) == 1:
                    out.append(prefix + base)

            block = []
            prevdirection = [-1,1][indenting]
        space_if_needed = [""," "][iskwd and tokval not in ("else","try")]
        line += space_if_needed + tokval + space_if_needed
    except StopIteration:
        out.append(" " * idx + ";".join(l for l in block))
        break

total_out=''.join(out)+newline
if replace_varnames:
    wrappers = [";"," ", ":", "=", "(", "[", ")", "]", ".",",","*","+","-","/","<",">","!","\n"]
    wrl = list(itertools.permutations(wrappers,2)) + zip(wrappers, wrappers)

    for i, e in enumerate(varnames):
        # print i, e, "v"+str(i)
        for p, a in wrl:
            total_out = total_out.replace(p+e+a,p+"v"+str(i)+a)

print total_out[0:-1]

```

## Minified (by itself), 1388 characters (a 46 % reduction)

```
import keyword,tokenize,sys,token,itertools;v16="";v20=[];v19=[];v4=0;v15=0;v17=0;v10=set();v6=set();t=tokenize.generate_tokens(sys.stdin.readline);v8='\n';v13=True
while 1:
 try:
  v18,v9,_,_,_=t.next();v2=v9 in keyword.kwlist
  if v18==1:
   if ''.join(v16).lstrip().startswith("import "):v6.add(v9)
   else:
    if not (v2 or v16[-1]=="." or v9 in __builtins__.__dict__.keys() or v9.startswith("_") or len(v9)<=2 or v9 in v6):v10.add(v9)
  if v18==53:continue
  if v18==4:v19.append(' '.join(x for x in ("".join(l for l in v16 if l)).strip().split()));v16=[]
  if v18==5 or v18==6:
   if v20 and v20[-1]!=v8:v20.append(v8)
   v15=v4;v4+=(-1,1)[v18==5];v5=v15<v4;v12=v15>v4;v11=" "*v15;v14=";".join(l for l in v19)
   if v12 and v17==1:v20.pop();v20.append(v14)
   else:
    if len(v19)>1:
     if v5:v20.append(v11+";".join(l for l in v19[:-1]));v20.append(v8);v20.append("".join(v11+l for l in v19[-1:]))
     else:v20.append(v11+v14)
    elif len(v19)==1:v20.append(v11+v14)
   v19=[];v17=[-1,1][v5]
  v3=[""," "][v2 and v9 not in ("else","try")];v16+=v3+v9+v3
 except StopIteration:v20.append(" "*v4+";".join(l for l in v19));break
v1=''.join(v20)+v8
if v13:
 v0=[";"," ",":","=","(","[",")","]",".",",","*","+","-","/","<",">","!","\n"];v7=list(itertools.permutations(v0,2))+zip(v0,v0)
 for i,e in enumerate(v10):
  for p,a in v7:v1=v1.replace(p+e+a,p+"v"+str(i)+a)
print v1[0:-1]

```

## Known limitations:

1. Keyword arguments are problematic when variable name shortening is on.
2. The code is ugly and can probably break some of the more dynamic Python constructs. It does work fine for itself (and other simple scripts) though.
> 6 votes

# Answer
## JavaScript, 562 → 334 bytes

40% reduction, but it's pretty compact to begin with.

Uses the Google Closure Compiler API in advanced optimization mode, which might rename certain variables but it is still functionally equivalent.

```
function minify(input) {
    // Closure Compiler API url:
    var url = 'http://closure-compiler.appspot.com/compile';

    // Create and initialize the Ajax request:
    var rq = new XMLHttpRequest();
    rq.open('POST', url, false);
    rq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // Send the request:
    rq.send('js_code=' + encodeURIComponent(input) +
        '&compilation_level=ADVANCED_OPTIMIZATIONS&output_format=text&output_info=compiled_code');

    // Return the result and just assume the code succeeded (hey, it's Google):
    return rq.responseText;
}

```

Here's a sample jsFiddle, and here's the code run on itself when compiled without a run:

```
window.a=function(c){var b=new XMLHttpRequest;b.open("POST","http://closure-compiler.appspot.com/compile",!1);b.setRequestHeader("Content-Type","application/x-www-form-urlencoded");b.send("js_code="+encodeURIComponent(c)+"&compilation_level=ADVANCED_OPTIMIZATIONS&output_format=text&output_info=compiled_code");return b.responseText};

```
> 4 votes

# Answer
## APL, 76 character output

```
{(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞   ⍝ This takes a line of APL as input and removes comments and unnecessary spaces!

```

This isn't really a serious attempt at golfing, but it was interesting to implement.. I think? It removes comments (⍝) and spaces. This works on Dyalog APL. (Note that it preserves spaces and ⍝ characters found in quoted strings.)

Example (first line is the code, second is the input, third is the output):

```
      {(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞   ⍝ This takes a line of APL as input and removes comments and unnecessary whitespace!
{(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞   ⍝ This takes a line of APL as input and removes comments and unnecessary whitespace!
{(~(n↓b)∧' '⍷d)/d←(n←-+/∨\('⍝'⍷⍵)∧b←~a∨≠\a←((''''⍷⍵)∧{⍵∧¯1⌽⍵}~''''''⍷⍵))↓⍵}⍞

```
> 2 votes

# Answer
# APL (Dyalog APL), 2145 → 763 bytes (−64%)

```
 Minify←{
     ⍝ Minifies source code ⍵ — see examples at end
     ns←⎕NS ⍬  ⍝ namespace to keep names created by side-effects

     src←ns.(61 ⎕ATX ⎕FX) '_',⊆⍵  ⍝ get normalised source
     ⍝ make large magnitude numbers use exponential format:
     src←'\d+\.\d+' '\d00+'⎕R{⍵.PatternNum: (⊃,'E',∘⍕¯1+≢)⍵.Match ⋄ ⍵.Match} src

     (from to)←⍬ ⍬
     (from to),∘⊂←'''[^'']+''|\d+ [eEjJ]'       '&'      ⍝ preserve strings and space before e/j
     (from to),∘⊂←' ?⍬ ?'                       '⍬'      ⍝ remove spaces around ⍬
     (from to),∘⊂←'([^#]) # ([^#])'             '\1#\2'  ⍝ remove spaces around #
     (from to),∘⊂←'# ([^#])'                    '#\1'    ⍝ remove space after #
     (from to),∘⊂←'([^#]) #'                    '\1#'    ⍝ remove space before #
     (from to),∘⊂←' ([⎕:])'                     '\1'     ⍝ remove space before ⎕ and :
     (from to),∘⊂←' *⍝.*|^ +'                   ''       ⍝ remove comments and leading spaces
     (from to),∘⊂←'(\pL) 0\.'                   '\1.'    ⍝ make X 0.5 into X.5
     (from to),∘⊂←'(\d) (\pL)'                  '\1\2'   ⍝ make 1 X into 1X
     (from to),∘⊂←' ?(⋄ ?)+'                    '⋄'      ⍝ make 1 X into 1X
     (from to),∘⊂←'(:End)([DFHPRTW]|If|Sel)\w+' '\1'     ⍝ make :EndXYZ into :End where permitted
     (from to),∘⊂←':Return|:GoTo '              '→'      ⍝ Replace keywords with "→"

     src←from ⎕R to ⊢ src  ⍝ do it!

     ⍝ make small magnitude numbers use exponential format:
     src←'\b0\.00+(\d+)'⎕R{lead←-/⍵.Lengths ⋄ mantissa,'E',⍕10⍟⍵.Match÷⍥⍎mantissa←lead↓⍵.Match} src

     src←'\b0\.'⎕R'.' ⊢ src  ⍝ make 0.5 into .5

     _←'adic' ns.⎕CY 'dfns'  ⍝ import adic from dfns.dws
     from←' '(2⌽'\b\b',~)¨⍨' '~¨⍨↓ns.(⎕REFS ⎕FX)'\.[∆⍙\w]+'⎕R' '⍠'UCP' 1 ⊢ src  ⍝ get non-dotted names
     from{⍵,⍺,⍵}¨←⊂'\b'                ⍝ names have to be in isolation
     to←('_',⎕A,⎕C ⎕A)∘ns.adic¨⍳≢from  ⍝ generate short names
     (from to),⍨∘⊂←'''[^'']+''' '&'    ⍝ preserve strings
     from ⎕R to ⊢ 1↓src~⊂''            ⍝ minify names and remove blank lines

     More examples:
         Refs: ⎕SE # ## ⎕DMX #
         Numbers: 100000 0.000001 16 E3 16 F3
 }
```

Run it on its own source to get:

```
B←{
K←⎕NS⍬L←K.(61⎕ATX⎕FX)'_',⊆⍵
L←'\d+\.\d+' '\d00+'⎕R{⍵.PatternNum:(⊃,'E',∘⍕¯1+≢)⍵.Match⋄⍵.Match}L
(H M)←⍬⍬
(H M),∘⊂←'''[^'']+''|\d+ [eEjJ]' '&'
(H M),∘⊂←' ?⍬ ?' '⍬'
(H M),∘⊂←'([^#]) # ([^#])' '\1#\2'
(H M),∘⊂←'# ([^#])' '#\1'
(H M),∘⊂←'([^#]) #' '\1#'
(H M),∘⊂←' ([⎕:])' '\1'
(H M),∘⊂←' *⍝.*|^ +' ''
(H M),∘⊂←'(\pL) 0\.' '\1.'
(H M),∘⊂←'(\d) (\pL)' '\1\2'
(H M),∘⊂←' ?(⋄ ?)+' '⋄'
(H M),∘⊂←'(:End)([DFHPRTW]|If|Sel)\w+' '\1'
(H M),∘⊂←':Return|:GoTo ' '→'
L←H⎕R M⊢L
L←'\b0\.00+(\d+)'⎕R{I←-/⍵.Lengths⋄J,'E',⍕10⍟⍵.Match÷⍥⍎J←I↓⍵.Match}L
L←'\b0\.'⎕R'.'⊢L
F←'adic'K.⎕CY'dfns'
H←' '(2⌽'\b\b',~)¨⍨' '~¨⍨↓K.(⎕REFS⎕FX)'\.[∆⍙\w]+'⎕R' '⍠'UCP' 1⊢L
H{⍵,⍺,⍵}¨←⊂'\b'
M←('_',⎕A,⎕C⎕A)∘K.adic¨⍳≢H
(H M),⍨∘⊂←'''[^'']+''' '&'
H⎕R M⊢1↓L~⊂''
C G:
E:⎕SE# ##⎕DMX#
D:1E5 1E¯6 16 _ 16F3
}
```

Run *this* on itself to get something very similar (only names differ).

**Removes:**

* All redundant spaces
* Comments
* Empty lines
* Leading and trailing zeros in numbers

**Abbreviates:**

* Numbers into exponential form (only when it actually saves characters)
* Control structure keywords to their shorter alternate forms
* All used names into `_`, `A`, `B`, `C`,… `Z`, `a`,… `z`, `__`, `_A`, `_B`,…

**Fails on:**

* Evaluated strings
* Global and to-be-imported names (abbreviates them)
> 1 votes

# Answer
## Bash, 17 characters output

They say my Python solution below isn't a minimizer. So here's one that does minimize, and it's even shorter:

```
 sed -e '1 s/^ //'

```

It reduces its own size from 18 to 17 characters.

## Python, 38 character output

I misunderstood the question a bit, so my 0 character attempt was incorrect.
So I have a new and improved solution. I'd start a new answer, but since it's in the same spirit, I prefer to edit.
I'm sure it can be much improved, especially if you switch the language. But as it is, I'm still way ahead of the competition:

```
import sys
for l in sys.stdin:print l,

```

When given itself as input, you get a 100% equivalent program, 38 characters long.

---

## Python, 0 character output (but not when run on itself, so it doesn't count).

```
import sys
program = [ l for l in sys.stdin ]
if len(program)>1 or program[0]!="x=12345\n":
    print "".join(program),

```

Sample input (also Python):

```
x=12345

```

I admit, it isn't very effective on most programs.
However, it reduces my example to 0 chars, still keeping it equivalent.

"The shortest **output** wins" - I don't think anyone can top this.
> -1 votes

---
Tags: code-challenge, code-generation, self-scoring
---


# Question
Title: Can the number reach 1 by repeatedly subtracting the largest prime less than it?
## Challenge:

Given a number, take the largest prime strictly less than it, subtract it from this number, do this again to this new number with the biggest prime less than it, and continue doing this until it's less than 3. If it reaches 1, your program should output a truthy value, else, the program should output a falsey value.

## Examples:

All of these should give a truthy value:

```
3
4
6
8
10
11
12
14
16
17
18
20
22
23
24
26
27
29
30
32
34
35
37
38
40
41
42
44
46
47
48
50

```

All of these should give falsey values:

```
5
7
9
13
15
19
21
25
28
31
33
36
39
43
45
49

```

## Rules:

* You can either write a program or function.
* You can assume that the input is bigger than 2.
* Standard loopholes apply
* This is so the shortest answer wins!

# Answer
# Jelly, ~~9~~ 8 bytes

```
’ÆRṪạµ¡Ḃ

```

Try it online! or verify all test cases.

### How it works

```
’ÆRṪạµ¡Ḃ  Main link. Argument: n

     µ    Combine all atoms to the left into a chain.
’           Decrement; yield n - 1.
 ÆR         Prime range; yield all primes in [2, ..., n -1].
   Ṫ        Tail; yield p, the last prime in the range.
            If the range is empty, this yields p = 0.
    ạ       Compute the absolute difference of p and n.
      ¡   Call the chain to the left n times.
          This suffices since each iteration decreases n, until one of the fixed
          points (1 or 2) is reached.
       Ḃ  Bit; return the parity of the fixed point.

```
> 10 votes

# Answer
# Retina, 31 bytes

```
.+
$*
+`1(?!(11+)\1+$)11+
1
^1$

```

Prints `0` (falsy) or `1` (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

```
.+
$*

```

Convert input to unary by turning input `N` into `N` copies of `1`.

```
+`1(?!(11+)\1+$)11+
1

```

Repeatedly remove the largest prime less than the input. This is based on the standard primality test with regex.

```
^1$

```

Check whether the result is a single `1`.
> 11 votes

# Answer
# Regex (ECMAScript or better), ~~33~~ 32 bytes

```
^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$

```

Takes its input in unary, as a string of `x` characters whose length represents the number.

Try it online! \- ECMAScript
Try it online! \- Java
Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- .NET

I finally found a use for the positive lookahead primality test I came up with on 2018-12-07! This is 2 bytes longer than the "standard" negative lookahead primality test, but it allows the full regex to be 1 byte shorter:

```
^                           # tail = input number
(                           # Loop the following:
    (?=                     # Atomic lookahead - finds the first match, and once
                            # finished, its result won't be changed by backtracking
        .+?                 # tail = largest number that is less than the current tail,
                            #        for which the following matches:
        (?=(xx+?)\2*$)\2$   # Assert tail is prime; \2 = tail
    )
    \2                      # tail -= \2
)*                          # Iterate the above loop zero or more times
x$                          # Assert tail==1

```

A neat thing about this regex is that it can be logically negated for all inputs other than zero simply by adding one byte, because after the repeated subtraction, all \\$n\>0\\$ end up at either \\$1\\$ or \\$2\\$:

```
^((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$

```

Try it online! \- ECMAScript
Try it online! \- Java
Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- .NET

---

Here is the regex implemented in some languages that have golf-efficient regex calls, where it either beats the other submitted solution(s) or is the only one in that language:

### \\$\large\textit{Anonymous functions}\\$

# Julia v0.4+, 58 bytes

```
n->split("x"^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$")[1]==""

```

Try it online!

The above returns truthy for an input of `0`. If returning falsey for `0` were needed, it'd be **60 bytes**:

```
n->match(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$","x"^n)!=nothing

```

Try it online!

or **59 bytes** in Julia v0.7 and earlier with `!=Void()`: Try it online!

Of course as far as Julia v0.4 goes, Glen O's answer outgolfs this at 32 bytes, but for v0.5 and later, this and the below may be optimal golf.

# Julia v0.7+, 54 bytes

```
n->occursin(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$",'x'^n)

```

Try it online!

# Julia v1.2+, 53 bytes

```
n->endswith('x'^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x")

```

Attempt This Online!

# PowerShell, ~~52~~ 51 bytes

```
'x'*"$args"-match'^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$'

```

Try it online!

*-1 bytes thanks to Julian*

# Python, ~~70~~ 69 bytes

```
lambda n:re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n);import re

```

Try it online!

# Python, 73 bytes

```
lambda n:__import__('re').match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n)

```

Try it online!

(If it must be a pure lambda.)

# JavaScript (ES6), ~~58~~ 54 bytes

```
n=>/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/.test(Array(n+1))

```

Try it online!

*-4 bytes thanks to a technique used by RK. and CubeyTheCube*

# Perl, ~~49~~ 47 bytes

*-2 bytes thanks to dingledooper*

```
sub{1x pop~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/}

```

Try it online!

This beats a port of Ton Hospel's **41 byte** answer (**57 bytes**):

```
sub{my$x=1x pop;$x=$`while$x=~/\B(?!(11+)\1+$|$)|11$/;$x}

```

Try it online!

Even if it's allowed to modified the global variable `$_` (**51 bytes**):

```
sub{$_=1x pop;$_=$`while/\B(?!(11+)\1+$|$)|11$/;$_}

```

Try it online!

# Ruby, ~~48~~ 45 bytes

```
->n{?x*n=~/^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$/}

```

Try it online!

*-2 bytes by switching the truthy value from "string of `x` characters whose length is the input number" to "the integer value `0`", while keeping the same falsey value of `nil`*
*-1 byte by using `?x` instead of `"x"`*

# PHP, ~~89~~ ~~75~~ 71 bytes

```
fn($n)=>preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$n))

```

Try it online!

*-4 bytes by switching from `x` to  as the repeated character*

# , ~~73~~ ~~72~~ ~~68~~ 63 bytes

```
\(n)grepl('^((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.$',strrep(1,n),,1)

```

Attempt This Online! / Try it online!

```
\(n)grepl('^((?=.+?(?!(..+)\\2+$)(..+))\\3)*.$',strrep(1,n),,1)

```

Attempt This Online! / Try it online!

*-1 byte thanks to Giuseppe*
*-4 bytes by using `grepl()` instead of `sum(grep())` or `any(grep())`*
*-5 bytes by using a new anonymous function syntax introduced in R v4.1.0*

Since TIO uses R v3.5.2, the TIO links have the old **68 byte** versions of the function.

# Java 8, ~~92~~ ~~89~~ ~~88~~ 71 bytes

```
n->new String(new char[n]).matches("((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.")

```

Try it online!

```
n->new String(new char[n]).matches("((?=.+?(?!(..+)\\2+$)(..+))\\3)*.")

```

Try it online!

*-17 bytes by just matching the regex straight against a string of NUL characters instead of replacing the NULs with `x`*

# Java 11, 61 bytes

```
n->"x".repeat(n).matches("((?=.+?(?=(xx+?)\\2*$)\\2$)\\2)*x")

```

Try it online!

*-10 bytes relative to Java \<11, thanks to Kevin Cruijssen*

### \\$\large\textit{Full programs}\\$

# Python 2, 69 bytes

```
import re
re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()).re

```

Outputs via its exit code, value `0` for truthy (by exiting normally), and `1` for falsey (by triggering an `AttributeError`).

Try it online!

# Python 2, ~~71~~ 70 bytes

```
import re
re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*input()).re

```

Outputs via its exit code, value `1` for truthy and `0` for falsey, using the truth-inverted regex.

Try it online!

Alternative method using the uninverted regex, outputting exit code `1` for truthy (by triggering a `NameError`), and `0` for falsey (by exiting normally), at **71 bytes**:

```
import re
if re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()):z

```

Try it online!

# Python 2, ~~79~~ 74 bytes

```
import re
print re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input())>0

```

Outputs `True` or `False` via stdout.

Try it online!

# Python 3, ~~84~~ 83 bytes

```
import re
print(not re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*int(input())))

```

Try it online!

The above uses the truth-inverted regex. Without it is **84 bytes**:

```
import re
print(bool(re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*int(input()))))

```

Try it online!

# PHP `-F`, 70 bytes

```
<?=preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$argn));

```

Try it online!

# Perl `-p`, ~~45~~ 43 bytes

*-2 bytes thanks to dingledooper*

```
$_=1x$_~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/

```

Try it online!

Beaten by Ton Hospel's **41 byte** answer which mixes regex and code: Try it online!

# Perl, ~~46~~ 44 bytes

```
say 1x<>~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/

```

Try it online!

Now beats a port of Ton Hospel's answer (**45 bytes**):

```
$_=1x<>;$_=$`while/\B(?!(11+)\1+$|$)|11$/;say

```

Try it online!
> 10 votes

# Answer
# Pyth, ~~18~~ ~~15~~ 14 bytes

*Thanks to @Maltysen for -1 byte*

```
#=-QefP_TUQ)q1

```

A program that takes input on STDIN and prints `True` or `False` as appropriate.

Try it online

**How it works**

```
#=-QefP_TUQ)q1  Program. Input: Q
#          )    Loop until error statement (which occurs when Q<3):
         UQ      Yield [0, 1, 2, 3, ..., Q-1]
     fP_T        Filter that by primality
    e            Yield the last element of that
 =-Q             Q = Q - that
            q1  Q is 1 (implicit variable fill)
                Implicitly print

```

**Old version with reduce, 18 bytes**

```
qu-G*<HGH_fP_TSQQ1

```

Try it online

**How it works**

```
qu-G*<HGH_fP_TSQQ1  Program. Input: Q
              SQ    Yield [1, 2, 3, ..., Q]
          fP_T      Filter that by primality
         _          Reverse it
 u                  Reduce it:
                Q    with base case Q and
                     function G, H ->
     <HG              H<G
    *   H             *H (yields H if H<G, else 0)
  -G                  Subtract that from G
q                1  The result of that is 1
                    Implicitly print

```
> 8 votes

# Answer
# Julia (0.4), 32 bytes

(Update (as of 1.4): This is rather out-of-date, now - `primes` is no longer in Base, and `?:` needs spaces around the `?` and the `:`)

While it's not going to be the shortest solution among the languages, this might be the shortest of the human-readable ones...

```
!n=n>2?!(n-primes(n-1)[end]):n<2

```

Try it online!

Or, to put it in slightly clearer terms

```
function !(n)
  if n>2
    m=primes(n-1)[end]   # Gets largest prime less than n
    return !(n-m)        # Recurses
  else
    return n<2           # Gives true if n is 1 and false if n is 2
  end
end

```

Called with, for example, `!37`.
> 7 votes

# Answer
# JavaScript (ES6), ~~64~~ 63 bytes

*Saved 1 byte thanks to @Neil*

```
g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))

```

I wrote this in 2 minutes... *and it worked perfectly the first time.* First user to find the inevitable bug wins....

### Try it out

```
g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))
```

```
<input type="number" value=3 min=3 onchange="A.innerHTML=f(this.value)"><br>
<p id=A>1</p>
```

### How it works

First we define **g(x)** as the function that finds the first prime number **p \<= x**. This is done using the following process:

1. Start with **n = x-1**.
2. If **n \< 2**, **x** is prime; return **x**.
3. If **x** is divisible by **n**, decrement **x** and go to step 1.
4. Otherwise, decrement **n** and go to step 2.

The solution to this challenge, **f(x)**, is now fairly straightforward:

1. If **x \< 3**, return **x = 1**.
2. Otherwise, subtract **g(x-1)** and try again.
> 7 votes

# Answer
## Pyke, ~~15~~ 11 bytes

```
WDU#_P)e-Dt

```

Try it here!

```
            - stack = input
W           - while continue:
  U#_P)     -     filter(is_prime, range(stack))
       e    -    ^[-1]
 D      -   -   stack-^
         Dt -  continue = ^ != 1

```

Returns `1` if true and raises an exception if false
> 6 votes

# Answer
# Husk, ~~11~~ 9 bytes

```
εωλ-→fṗŀ¹

```

Try it online!

-2 bytes from Leo.

None of the testcases reach zero because the max number we can subtract from `n` can only be `n-1`. Hence, we can check insignificance instead of equality with 1.

## Explanation

```
εωλ-→fṗŀ¹
 ωλ       iterate on the input till fixpoint
       ŀ¹  range 0..n-1
     fṗ    filter out nonprimes
    →      last element
   -       subtract from n
ε         is fixed point insignificant? (<= 1?)

```
> 5 votes

# Answer
# Python3, 102 92 90 89 88 bytes

```
f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])

```

Golfing suggestions welcome! I see that `gmpy` contains a function `next_prime`, but I can't test it yet :(

-2 bytes, thanks to @JonathanAllan!

-1 byte, thanks to @Aaron!

## Testcases

```
f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])

s="3 4 6 8 10 11 12 14 16 17 18 20 22"
h="5 7 9 13 15 19 21 25 28 31 33 36 39"

for j in s.split(" "):print(f(int(j)))
for j in h.split(" "):print(f(int(j)))

```

Output is 13 truthy values and 13 falsey values. `s` contains the truthy cases and `h` the falseys.
> 4 votes

# Answer
# Haskell, ~~65~~ 63 bytes

```
f n|n>2=f$n-last[p|p<-[2..n-1],all((>0).mod p)[2..p-1]]|1>0=n<2

```

Try it online!
> 4 votes

# Answer
## Mathematica, 32 bytes

```
2>(#//.x_/;x>2:>x+NextPrime@-x)&

```

This is an unnamed function which takes an integer and returns a boolean.

### Explanation

There's a lot of syntax and funny reading order here, so...

```
   #                               This is simply the argument of the function.
    //.                            This is the 'ReplaceRepeated' operator, which applies
                                   a substitution until the its left-hand argument stops
                                   changing.
       x_/;x>2                     The substitution pattern. Matches any expression x as
                                   long as that expression is greater than 2.
              :>                   Replace that with...
                  NextPrime@-x     Mathematica has a NextPrime built-in but no
                                   PreviousPrime built-in. Conveniently, NextPrime
                                   works with negative inputs and then gives you the
                                   next "negative prime" which is basically a
                                   PreviousPrime function (just with an added minus sign).
                x+                 This gets added to x, which subtracts the previous
                                   prime from it.
2>(                           )    Finally, we check whether the result is less than 2.

```
> 3 votes

# Answer
# Python, with sympy, 60 bytes

```
import sympy
f=lambda n:n>2and f(n-sympy.prevprime(n))or n<2

```

---

My previous method was 83 bytes without sympy using recursion, but I took truthy/falsey to mean distinguishable and consistent, but I have been informed that's an incorrect interpretation. I can't seem to salvage it due to the tail, but I'll leave it here in case someone knows how to do so:

```
f=lambda n,p=0:n>2and(any(p%x==0for x in range(2,p))and f(n,p-1)or f(n-p,n+~p))or n

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 27 bytes

```
{⍵<3:⍵=1⋄∇⍵-⊃⌽(⊢~∘.×⍨)2↓⍳⍵}
 ⍵<3 ⍝ Termination condition
   :⍵=1 ⍝ return value
     ⋄ ⍝ Separator
       ∇ ⍝ Recursive call
         ⍵-⊃⌽ ⍝ Subtract largest prime
           (⊢~∘.×⍨) ⍝ Calculate primes less than argument
             2↓⍳⍵ ⍝ Range 2–(N-1)

```

Try it online!
> 3 votes

# Answer
# Brachylog, 11 bytes

```
1|-↙Xṗ∧X≜!↰

```

Try it online!

```
1              The input is 1,
 |             or:
       X≜      X is the integer with the least absolute value such that
  -↙X          it is positive, and if it is subtracted from the input
     ṗ∧        the result is prime.
         !     Consider no other value of X.
          ↰    Call this predicate again with X as the input.

```
> 3 votes

# Answer
# Vyxal, 7 bytes

```
‡∆ṗεẊ1=

```

Try it Online!

Very nice and neat answer (flagless too!)

## Explained

```
‡∆ṗεẊ1=
‡∆ṗε    # lambda x: abs(x - prev_prime(x))
    Ẋ   # repeat that on the input until it doesn't change
     1= # does that equal 1?

```
> 3 votes

# Answer
# CJam, ~~21~~ 16 bytes

*Thanks to Dennis for saving 4 bytes.*

```
ri{_1|{mp},W=-}h

```

Try it online!

### Explanation

```
ri       e# Read input and convert to integer N.
{        e# Run this block as long as N is positive (or until the program aborts
         e# with an error)...
  _1|    e#   Duplicate and OR 1. This rounds up to an odd number. For N > 2, this
         e#   will never affect the greatest prime less than N.
  {mp},  e#   Get all primes from 0 to (N|1)-1.
         e#   For N > 2, this will contain all primes less than N.
         e#   For N = 2, this will contain only 2.
         e#   For N = 1, this will be empty.
  W=     e#   Select the last element (largest prime up to (N|1)-1).
         e#   For N = 1, this will result in an error and terminate the program, which
         e#   still prints the stack contents though (which are 1, the desired output).
  -      e#   Subtract from N. Note that this gives us 0 for N = 2, which terminates the
         e#   loop.
}h

```
> 2 votes

# Answer
# MATL, 13 bytes

```
`tqZq0)-t2>}o

```

Try it online! Or verify all test cases at once.

### Explanation

```
`        % Do...while
  t      %   Duplicate. Takes input implicitly in the first iteration
  qZq    %   All primes less than that
  0)     %   Get last one
  -      %   Subtract (this result will be used in the next iteration, if any)
  t      %   Duplicate
  2>     %   Does it exceed 2? If so: next iteration. Else: execute the "finally"
         %   block and exit do...while loop
}        % Finally
  o      %   Parity. Transforms 2 into 0 and 1 into 1
         % End do...while implicitly
         % Display implicitly

```
> 2 votes

# Answer
# Perl, 42 bytes

Includes +1 for `-p`

Run with input on STDIN

`reach1.pl`:

```
#!/usr/bin/perl -p
$_=1x$_;$_=$`while/\B(?!(11+)\1+$|$)|11$/

```

Uses the classic primality regex
> 2 votes

# Answer
## .NET Regex, 38 bytes

Just to show that it can be checked in a single regex.

```
^(?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+.$

```

Input is assumed to be in unary.

### Explanation

It simply implements the requirement to the word, repeatedly removing the biggest prime and check whether there remainder is 1.

* `(?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+`: Non-backtracking group makes sure the biggest prime we found is not overriden, and `+` simply repeat the process of matching the biggest prime.

+ `(?<=(.*))..+(?<!^\1\2+(.+.)|$)`: Match the biggest prime less than the remaining number

    - `(?<=(.*))`: Record how much we have subtracted to establish an "anchor" point for assertion.
        - `..+`: Look for the biggest number...
        - `(?<!^\1\2+(.+.)|$)`: ... which is prime and less than the remaining number.
            * `(?<!^\1\2+(.+.))`: The usual prime test routine, with `^\1` tacked in front to make sure we are checking the amount matched by `..+`
            * `(?!<$)`: Assert less than the remaining number
> 2 votes

# Answer
# Python 2.7: ~~88~~ 87 Bytes

```
r=lambda n:n>2and r(n-[a for a in range(2,n)if all(a%b for b in range(2,a))][-1])or n<2

```

Thx @TuukkaX for -1 more byte!
> 2 votes

# Answer
# Factor \+ `math.primes`, 51 bytes

```
[ [ dup 1 - primes-upto last - dup 2 > ] loop 1 = ]

```

Try it online!
> 2 votes

# Answer
# Vitsy, ~~28~~ 26 bytes

This can definitely be shortened.

```
<]xN0)l1)-1[)/3D-];(pD-1[D

```

```
<                    Traverse the code in this direction, rotating on the line.
                     For the sake of reading the code easier, I'm reversing the
                     code on this line. This will be the order executed.

 D[1-Dp(;]-D3/)[1-)1l)0Nx]
 D                         Duplicate the top member of the stack.
  [      ]                 Do the stuff in brackets until break is called.
   1-                      Subtract 1 from the top item of the stack.
     D                     Duplicate the top member of the stack.
      p(                   If the top member is a prime...
        ;                  break;
          -                Pop a, b, push a - b.
           D3/)[         ] If this value is less than 3, do the bracketed code.
                1-         Subtract the top item of the stack by 1.
                  )        If the top item is zero...
                   1       Push 1.
                    l)     If the length of the stack is zero...
                      0    Push 0.
                       N   Output the top member of the stack.
                        x  System.exit(0);

```

Try it online!
> 1 votes

# Answer
# Floroid, 45 30 29 bytes

```
f=Bb:b<2Fb<3Gf(b-en(b-1)[-1])

```
> 1 votes

# Answer
# Perl 6,  ~~54 53 52~~  51 bytes

```
{($_,{$_-($_-1...2).first: *.is-prime}...3>*)[*-1]==1}
{($_,{$_-($_-1...2).first: *.is-prime}...3>*).any==1}
{any($_,{$_-($_-1...2).first: *.is-prime}...3>*)==1}

```

```
{any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}

```

## Explanation:

```
# bare block lambda with implicit parameter ｢$_｣
# used to generate all of the rest of the elements of the sequence
{
  # create an any Junction of the following list
  any(
    $_, # initialize sequence with the inner block's argument

    # bare block lambda with implicit parameter ｢$_｣
    {
      # take this inner block's argument and subtract
      $_ -

      ( ^$_ )            # Range up-to and excluding ｢$_｣
      .grep(*.is-prime)\ # find the primes
      [ * - 1 ]          # return the last value
    }

    ...   # keep doing that until

    3 > * # the result is less than 3

  # test that Junction against ｢1｣
  # ( returns an ｢any｣ Junction like ｢any(False, False, True)｣ )
  ) == 1
}

```

## Example:

```
# show what is returned and if it is truthy
sub show ($_) {
  # ｢.&{…}｣ uses the block as a method and implicitly against ｢$_｣
  my $value = .&{any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}
  say join "\t", $_, ?$value, $value.gist;
}

show 3;  # 3    True    any(False, True)
show 4;  # 4    True    any(False, True)
show 5;  # 5    False   any(False, False)
show 10; # 10   True    any(False, False, True)
show 28; # 28   False   any(False, False, False)
show 49; # 49   False   any(False, False)
show 50; # 50   True    any(False, False, True)

```
> 1 votes

# Answer
# Irregular, 63 bytes

```
p~?1_$-1p:;
n=i(0)?1_$-1p:;
_~
N=n
1(?!(11+)\1+$)11+~1
^11$~0
N

```

I created this language two days ago, and the basic premises are that there are no built in loops, the only features are basic arithmetic and decision making, and program evaluation is based on regular expressions.

## Explanation

```
p~?1_$-1p:;
n=i(0)?1_$-1p:;
_~
N=n

```

This part converts the input into unary. It repeatedly subtracts 1 from the input until it equals 0, prepending `1_` each time. It then removes all of the `_`s. If I hadn't forgotten a `break` in my code it could be written as so:

```
p~?1_$-1p:;
_~
n=i(0)?1_$-1p:;

```

The next part repeatedly removes the largest prime from the input until it is equal to `1` or `11`, with `11` being replaced with `0`.

```
1(?!(11+)\1+$)11+~1
^11$~0
N

```

I used the regex from Martin Ender's answer.
> 1 votes

# Answer
## PowerShell v2+, 81 bytes

```
param($n)while($n-gt2){$n-=(($n-1)..2|?{'1'*$_-match'^(?!(..+)\1+$)..'})[0]}!--$n

```

Takes input `$n`. Enters a `while` loop so long as `$n` is still `3` or greater. Each iteration, subtracts a number from `$n`. The number is the results of the regex primality test applied against a range `($n-1)..2` via the `Where-Object` (`?`) operator, then the first `[0]` of the results (since the range is decreasing, this results in the largest one being selected). After concluding the loop, `$n` is either going to be `1` or `2`, by definition, so we pre-decrement `$n` (turning it into either `0` or `1`), and take the Boolean-not `!` thereof. That's left on the pipeline and output is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> 3..20|%{"$_ --> "+(.\can-the-number-reach-one.ps1 $_)}
3 --> True
4 --> True
5 --> False
6 --> True
7 --> False
8 --> True
9 --> False
10 --> True
11 --> True
12 --> True
13 --> False
14 --> True
15 --> False
16 --> True
17 --> True
18 --> True
19 --> False
20 --> True

```
> 1 votes

# Answer
# Clojure, 125 bytes

```
#(loop[x %](if(> x 2)(recur(- x(loop[y(dec x)](if(some zero?(vec(for[z(range 2 y)](mod y z))))(recur(dec y))y))))(quot 1 x)))

```

Yikes, that is one long piece of code. The most verbose language strikes again!

Ungolfed:

```
(defn subprime [n]
  (loop [x n]
    (if (> x 2)
      (recur
        (- x
          (loop [y (dec x)]
            (if (some zero? (vec (for [z (range 2 y)] (mod y z))))
              (recur (dec y)) y))))
      (quot 1 x))))

```
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
ΔD<ÅPà-

```

Outputs `2` as falsey (only `1` is truthy in 05AB1E).

Try it online or verify all test cases.

**Explanation:**

Unfortunately the *previous prime* builtin `ÅM` goes into an infinite loop for \\$\leq2\\$, otherwise it could have been used to save a few bytes.

```
Δ        # Loop until the result no longer changes:
 D       #  Duplicate the current value
         #  (which is the implicit input-integer in the first iteration)
  <ÅP    #  Pop it, and push a list of all primes < this value:
  <      #   Decrease the value by 1
   ÅP    #   Pop and push a list of all primes <= this value-1
     à   #  Pop and push the maximum prime of this list
         #  (or an empty string if the list is empty)
      -  #  Subtract it from the value (where subtracting the empty string is a no-op)
         # (after which the found result is output implicitly)

```
> 1 votes

# Answer
# Haskell, 79 bytes

Not really short but pointfree :)

```
(<2).until(<3)(until(flip(`until`(+1))2.(.)(<1).mod>>=(==))pred.pred>>=flip(-))

```
> 0 votes

# Answer
# Matlab, 51 bytes

```
v=@(x)x-max(primes(x-1));while(x>=3)x=v(x);end;x==1

```

This is VERY similar to the JS6 solution by ETHProductions, but needs the variable to be in the workspace.
> 0 votes

---
Tags: code-golf, number, primes, decision-problem
---