# Question
Title: Mr. ASCII becoming uncanny with your own code
Let's make a little stupid program that simulates the meme "Mr. incredible becoming uncanny", but in this case, our little ASCII friend is going to react to our code length.

**Objective:**

Create a program that takes anything (preferably a program) as input and outputs this:

```
Pov:
<face>   you score X on codegolf

```

Where `X` is the length of the input and the face depends on the value of X:

```
X < 20         = \(^-^)/
20 ≤ X < 50    = -(o_o)-
50 ≤ X < 100   = /(¬_¬)\
100 ≤ X < 250  = /(º-º)\
250 ≤ X < 500  = /(ª@ª)\
X ≥ 500        = /(x_x)\

```

**Example:**

I have made my own ungolfed version in C#: Try it online!

```
using System;
class Program {
static void Main(string[] args) {
    Console.WriteLine("Pov:");

    if(args[0].Length < 20){
        Console.WriteLine("\\(^-^)/   you score "+args[0].Length+" on codegolf");

    }else if(args[0].Length < 50){
        Console.WriteLine("-(o_o)-   you score "+args[0].Length+" on codegolf");

    }else if(args[0].Length < 100){
        Console.WriteLine("/(¬_¬)\\   you score "+args[0].Length+" on codegolf");

    }else if(args[0].Length < 250){
        Console.WriteLine("/(º-º)\\   you score "+args[0].Length+" on codegolf");

    }else if(args[0].Length < 500){
        Console.WriteLine("/(ª@ª)\\   you score "+args[0].Length+" on codegolf");

    }else{
        Console.WriteLine("/(x_x)\\   you score "+args[0].Length+" on codegolf");

    }
}
}

```

If the program takes itself as input, it will output:

```
Pov:
/(x_x)\   you score 741 on codegolf

```

**Rules:**

* The output must have exactly three spaces betwen the face and the text.
* The shortest code in bytes wins.
* Input length should be counted in characters, not bytes.

# Answer
> 2 votes
# 05AB1E, ~~118~~ ~~113~~ ~~112~~ 80 bytes

*-32 thanks to Kevin Cruijssen.*

```
’ƒËŠˆ’Ig•È¼Ÿò8Ãx°иšü•"(\^-)/-o_¬ºª@x"Åв6ä•Û³™•51вT*ÅΔIg›}èJ.º“Pov:
ÿ  €îŒÂ ÿ€‰ ÿ

```

Try it online! Beats all other answers.

# Answer
> 5 votes
# Charcoal, ~~106~~ ~~102~~ ~~96~~ ~~94~~ 85 bytes

```
ＰPov:ＤＰ✂⁺”|ecT#Ｆ>”xªº´¬o^_@--_-ΣＥＩ⪪”←⧴⟲º"Ｑ⪫+R” ‹Ｌθιφ⁶←‖Ｂ”↶±=⧴KＣX≕‹#”ＩＬθ”↶←∨^⁹⁰y↔]

```

Try it online! Link is to verbose version of code. Note that the deverbosifier miscalculates the length of characters in the ISO-8851 code page; non-ASCII characters should count 3 bytes instead of 1. Explanation:

```
ＰPov:Ｄ

```

Print `Pov:` without moving the cursor (so it gets overwritten below), and output that on its own line.

```
Ｐ✂⁺”|ecT#Ｆ>”xªº´¬o^_@--_-ΣＥＩ⪪”←⧴⟲º"Ｑ⪫+R” ‹Ｌθιφ⁶

```

Concatenate the compressed string `////-\((((((` with the incompressible string `xªº¬o^_@--_-` (Charcoal can only compress ASCII strings), slice that with a starting offset depending on how many of the numbers in the compressed string `500 250 100 50 20` are greater than the length of the input and a step of 6, and print without moving the cursor.

```
←‖Ｂ

```

Butterfly the canvas, leaving the cursor after the face.

```
”↶±=⧴KＣX≕‹#”

```

Print the compressed string  `you score` .

```
ＩＬθ

```

Print the length of the input as a string.

```
”↶←∨^⁹⁰y↔]

```

Print the compressed string  `on codegolf`.

# Answer
> 5 votes
# Excel, 151 bytes

```
=LET(x,LEN(A1),"Pov:
"&IFS(x<20,"\(^-^)/",x<50,"-(o_o)-",x<100,"/(¬_¬)\",x<250,"/(º-º)\",x<500,"/(ª@ª)\",1,"/(x_x)\")&"   you score "&x&" on codegolf")

```

Input is in the cell `A1`. Output is wherever the formula is.

Everything I try that seems more clever than this simple approach ends up adding a few bytes.

# Answer
> 4 votes
# Python 3, 158 bytes

```
x=len(open(0).read())
print("Pov:\n"+r"////-\((((((xªº¬o^_@-__-xªº¬o^))))))\\\\-/"[sum(x<q*10for q in[2,5,10,25,50])::6],f"  you score {x} on codegolf")

```

Try it online!

-1 byte thanks to pxeger
-9 bytes thanks to Kateba

# Answer
> 4 votes
# Retina 0.8.2, 139 bytes

```
s`.+
Pov:¶$.&$*_   you score $.& on codegolf
_{500,}
/(x_x)\
_{250,}
/(ª@ª)\
_{100,}
/(º-º)\
_{50,}
/(¬_¬)\
_{20,}
-(o_o)-
_+
\(^-^)/

```

Try it online! Explanation:

```
s`.+
Pov:¶$.&$*_   you score $.& on codegolf

```

Get the length of the input and substitute it into the output string, plus also insert that many underscores for the face checking.

```
_{500,}
/(x_x)\
_{250,}
/(ª@ª)\
_{100,}
/(º-º)\
_{50,}
/(¬_¬)\
_{20,}
-(o_o)-
_+
\(^-^)/

```

Replace the underscores with the appropriate face.

# Answer
> 4 votes
# Zsh, 138 bytes

```
f='\(^-^)/-(o_o)-/(¬_¬)\/(º-º)\/(ª@ª)\/(x_x)\'
<<<"Pov:
${f:$[i=$#1/50+($#1>19),i>9?5:i>3?3+i/5:i]*7:7}   you score $#1 on codegolf"

```

Try it online!

Fancy ternaries, let's go through them:

```
i=$#1/50+($#1>19)         # div by 50, add one if at least 20
i>9?5:                    # if i > 9, then $#1 was at least 500
      i>3?3+i/5           # else if i > 3, then $# was between 100 and 500
               :i         # else i is correct

```

---

```
      ${f:$[ ... ]*7:7}           # string slice starting from $[ ]*7 of length 7
<<<"..${f:$[ ... ]*7:7}...$#1.."  # substitute in string. Embedded newlines are fine

```

# Answer
> 3 votes
# Rust, ~~192~~ 191 bytes

```
|x:&str|print!("Pov:
{}   you score {} on codegolf",match x.len(){0..=19=>r"\(^-^)/",0..=49=>"-(o_o)-",0..=99=>r"/(¬_¬)\",0..=249=>r"/(º-º)\",0..=499=>r"/(ª@ª)\",_=>r"/(x_x)\"},x.len())

```

Try it online!

*-1 byte thanks to Aiden4*

# Answer
> 2 votes
# JavaScript (ES6), 155 bytes

```
f=(s,i=0)=>[.4,1,2,5,10,n=s.length][i]*50>n?`Pov:
${"/-\\"[q=2>>i]}(${(c="^o¬ºªx"[i])+"-__-@_"[i]+c})${"\\-/"[q]}   you score ${n} on codegolf`:f(s,i+1)

```

Try it online!

# Answer
> 2 votes
# C# (.NET 6), <sup>~~190~~ \\$\cdots\\$ ~~172~~</sup> 170 bytes

```
int l=args[0].Length;Console.Write($"Pov:\n{(l<20?"\\(^-^)/":l<50?"-(o_o)-":l<100?"/(¬_¬)\\":l<250?"/(º-º)\\":l<500?"/(ª@ª)\\":"/(x_x)\\")}   you score {l} on codegolf");

```

*Golf of example code in OP*

Passing the program text as the first command line argument outputs:

```
Pov:
/(º-º)\   you score 170 on codegolf

```

Works on `.Net 6` but not on TIO.

# Answer
> 2 votes
# Jelly, 89 bytes

```
“µð1|ż‘Ḥ‘>@LS‘ị“\-/“(“^oḄṾȥx“-__-@_‘ŒḄ‘6¦U7¦0ịxɗ€6a"ƊZỌ¤
L⁶;“£ṭṛẇṣLe“¦ŒɱṣṀ^Tż»jṭÇ“Pov:¶”;

```

A full program accepting a (Python formatted) string argument that prints the result.

**Try it online!** Or see the test-suite.

### How?

```
“...‘Ḥ‘>@LS‘ị“...‘ŒḄ‘6¦U7¦0ịxɗ€6a"ƊZỌ¤ - Helper: list of characters, X
“...‘                                  - list of numbers = [9,24,49,124,249]
     Ḥ                                 - double = [18,48,98,248,498]
      ‘                                - increment = [19,49,99,249,499]
       >@L                             - length of X greater than? (vectorises)
          S                            - sum
           ‘                           - increment -> our "face index"
                                     ¤ - nilad followed by link(s) as a nilad:
             “...‘                     -   list of lists of numbers
                                           ...the ordinals of the characters:
                                              "\-/", "(", "^o¬ºªx", "-__-@_"
                  ŒḄ                   -   bounce
                                           ...this appends:
                                              "^o¬ºªx", "(", "\-/"
                    ‘6¦                -   increment the sixth - 2nd "(" -> ")"
                       U7¦             -   reverse seventh - 2nd "\-/" -> "/-\"
                                  Ɗ    -   last three links as monad:
                               6       -     literal six
                             ɗ€        -     for each - f(list, 6):
                          0ị           -       get the last one
                            x          -       repeat it six times
                                a"     -       zip with logical AND
                                               ...effectively extend the lists to
                                                  length six using the rightmost
                                                  ordinal.
                                   Z   -   transpose
                                    Ọ  -   convert the integers to characters
                                           ...a list of the faces
            ị                          - "face index" index into "faces"

L⁶;“...»jṭÇ“Pov:¶”; - Main Link: list of characters, X
L                   - length of X
 ⁶;                 - prefix with a space
   “...»            - compressed list of strings = "   you score", " on codegolf"
        j           - join with the score
          Ç         - call the helper link, above with X as the argument -> face
         ṭ          - tack the face to the front
           “Pov:¶”  - "Pov\n"
                  ; - concatenate
                    - implicit, smashing print

```

# Answer
> 0 votes
# Vyxal, 88 bytes

```
`Pov:
`»ẆḞẏǒ×Ȯ<§Jṙ¾»»ƛḂ}Ṁ≥⌐$ǍJ₄p∞wj»₁dτCτ6/»⋏∑ṗ»51τ₀*≬⁰L>ḟuJhiøM3`λ• ßµ `꘍?L` on ¬⋎»₅`Wṅ

```

Try it Online!

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


title: Diagonal Alphabet To the Input

text:
# Question
Title: Diagonal Alphabet To the Input
Inspired by this post. For those marking this question as a duplicate I urge you to actually read the question to see that mine is a modification of the one linked. The one linked does not ask for an input and is to just print the alphabet diagonally.

**The Challenge**

Given an input between 1-26 inclusively, print the alphabet diagonally, but begin printing vertically at the index of the given input.

**Examples**

Given the input:

```
16

```

Your program should output:

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

```

Input:

```
4

```

Output:

```
a
 b
  c
   d
   e
   f
   g
   h
   i
   j
   k
   l
   m
   n
   o
   p
   q
   r
   s
   t
   v
   w
   x
   y
   z

```

Input:

```
1

```

Output:

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

```

Input:

```
26

```

Output:

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

```

**Scoring**

This is , so the shortest answer in each language wins.

Good luck!

# Answer
# Charcoal, 9 bytes

```
↘✂β⁰Ｎ↓✂βη

```

Try it online!

### How it works

```
↘✂β⁰Ｎ↓✂βη
 ✂β⁰Ｎ         the alphabet from position 0 to the input
↘               print diagonally, down and to the right
        ✂βη    the alphabet starting from the position of the input
       ↓        print downwards

```

This solution no longer works in the current version of Charcoal (most likely due to a bug fix), but the issue is resolved for 10 bytes with `↘✂β⁰Ｎ↓✂βＩθ`.
> 13 votes

# Answer
# 05AB1E, 11 bytes

```
AvNI<‚Wysú,

```

First time trying 05AB1E, so I'm open to tips.

Try it online!

If a zero-indexed input from `0` to `25` is allowed, this can be 10 bytes by omitting the `<`.
> 7 votes

# Answer
# Python 2, ~~61 58 57~~ 56 bytes

```
def f(i,j=0):exec"print(' '*~-i)[:j]+chr(97+j);j+=1;"*26

```

-3 bytes thanks to Rod

-2 more bytes thanks to Mr. Xcoder
> 4 votes

# Answer
## JavaScript (ES2017), ~~73~~ ~~72~~ ~~71~~ 66 bytes

*Saved some bytes thanks to @JustinMariner*

```
f=(n,x=26)=>x?f(n,x-1)+(x+9).toString(36).padStart(x<n?x:n)+`
`:''

```
> 4 votes

# Answer
# Ruby, ~~51~~ ~~46~~ 43 bytes

```
->n{(0..25).map{|x|(' '*x)[0,n-1]<<(x+97)}}

```

Returns a list of strings.

Looks like the Python guys were on to something with their subscripts. -5 bytes by taking inspiration from Mr. Xcoder's improvement of ppperry's solution.

Previous solution with `rjust` (51 bytes):

```
->n{i=0;(?a..?z).map{|c|c.rjust i+=n>c.ord-97?1:0}}

```
> 4 votes

# Answer
# Python 2, ~~62~~ ~~50~~ 57 bytes

```
x=input();n=m=1
exec"print'%*c'%(m,n+96);n+=1;m+=x>m;"*26

```

Try it online!

Steals heavily from this answer by Dennis.
> 3 votes

# Answer
# Retina, ~~72~~ 68 bytes

```
^
z
{2=`
$`
}T`l`_l`^.
\D
$.`$* $&¶
\d+
$*
s`( *)( +)(?=.*¶\1 $)
$1

```

Try it online! Output includes trailing whitespace. Save 1 byte by deleting the space before the `$` if zero-indexing is allowed. Edit: Saved 4 bytes by using @MartinEnder's alphabet generator. Explanation:

```
^
z
{2=`
$`
}T`l`_l`^.

```

Insert the alphabet.

```
\D
$.`$* $&¶

```

Diagonalise it.

```
\d+
$*

```

Convert the input to unary as spaces.

```
s`( *)( +)(?=.*¶\1 $)
$1

```

Trim overlong lines so that no line is longer than the blank line at the end.
> 3 votes

# Answer
# R, ~~99~~ 89 bytes

*@MickeyT saved 10 bytes*

### function

```
function(x)for(i in 1:26)cat(paste(c(rep(" ",min(x,i)),letters[i]),collapse=""),sep="\n")

```

### demo

```
f <- function(x)for(i in 1:26)cat(paste(c(rep(" ",min(x,i)),letters[i]),collapse=""),sep="\n")
f(1)
f(10)
f(15)
f(26)

```
> 3 votes

# Answer
# Mathematica, 103 bytes

```
(T=Table;a=Alphabet[];c=Column)[c/@{T[""<>{T[" ",i],a[[i]]},{i,#}],T[""<>{T[" ",#],a[[i]]},{i,#,26}]}]&

```
> 2 votes

# Answer
# Pyth, ~~21~~ ~~17~~ 15 bytes

```
VlG+*d?>QNNQ@GN

```

Explanation:

```
VlG        For each character in the alphabet (G)
+          Concatenate...
 *d        Space (d) times...
   ?>QNNQ  Ternary; if Q (input) is less than N, return N, else Q
 @GN       The Nth character of the alphabet (G)

```

Try it online!
> 2 votes

# Answer
# Jelly, 11 bytes

```
26Ḷ«’⁶ẋżØaY

```

Try it online!
> 2 votes

# Answer
# Common Lisp, 84 bytes

```
(lambda(x)(dotimes(i 26)(format t"~v,,,@a~%"(if(< i x)(1+ i)x)(code-char(+ i 97)))))

```

Try it online!
> 2 votes

# Answer
# Python, 52 bytes

Quite surprised nobody noticed the obvious approach was also as short as the others.

```
lambda k:[(i*" ")[:k-1]+chr(i+97)for i in range(26)]

```

Try it online!

# Python, 53 bytes

```
lambda k:[min(k-1,i)*" "+chr(i+97)for i in range(26)]

```

Try it online!
> 2 votes

# Answer
# Gaia, 12 bytes

```
…26⊃§×¦₵a+†ṣ

```

Try it online!

### Explanation

```
…             Range 0..input-1
 26⊃          Repeat the last number enough times to make it have length 26
    §×¦       Turn each number into a string of that many spaces
       ₵a+†   Add the corresponding letter to each
           ṣ  Join with newlines

```
> 2 votes

# Answer
## Haskell, ~~58~~ 54 bytes

```
f n=do m<-[1..26];([2..min n m]>>" ")++['`'..]!!m:"\n"

```

Try it online!

How it works

```
f n=                  -- input number is n
  do m<-[1..26]       -- for each m from [1..26], construct a string and concatenate
                      -- them into a single string. The string is:
   [2..min n m]>>" "  -- min(n,m)-1 spaces,
      ++              -- followed by
   ['`'..]!!m         -- the m-th char after `
      :               -- followed by
   "\n"               -- a newline

```

Edit: @Lynn saved 4 bytes. Thanks!
> 2 votes

# Answer
# Java (OpenJDK 8), 69 bytes

```
n->{for(int a=0;a++<26;)System.out.printf("%"+(a<n?a:n)+"c%n",a+96);}

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), ~~12~~ 11 bytes

-1 as OP has now clarified that returning a list of strings is fine.

Prompts for input.

```
⎕A↑¨⍨-⎕⌊⍳26

```

Try it online!

`⍳26` first 26 strictly positive **ɩ**ntegers

`⎕⌊` minimum of input and those

`-` negate those

`⎕A↑⍨¨` for each letter of the **A**lphabet, take that many characters (from the rear, as all numbers are negative), padding with spaces as necessary

---

convert list of strings into matrix (only in TIO link to enable readable output)
> 2 votes

# Answer
# Japt, ~~16~~ 13 bytes

*Saved 3 bytes thanks to @Oliver*

```
;C£RiXiYmUÉ î

```

Test it online!
> 1 votes

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

```
n=>[..."abcdefghijklmnopqrstuvwxyz"].map((e,i)=>" ".repeat(i<n?i:n-1)+e)

```

Returns a list of strings.

Try it online!
> 1 votes

# Answer
# Mathematica, 67 bytes

```
SparseArray[x=#;{#,#~Min~x}->Alphabet[][[#]]&~Array~26,{26,#}," "]&

```

Returns a `SparseArray` of strings. To visualize, append `Grid@` in front.

Try it on Wolfram Sandbox

### Usage

```
Grid@SparseArray[x=#;{#,#~Min~x}->Alphabet[][[#]]&~Array~26,{26,#}," "]&[5]

```

> ```
> a
>  b
>   c
>    d
>     e
>     f
>     g
>
>     ⋮
>
>     z
>
> ```
> 1 votes

# Answer
# Python 2, 52 bytes

```
lambda n:['%*c'%(min(i+1,n),i+97)for i in range(26)]

```

Try it online!

I'm assuming a list of strings is fine...

Shortest I could get with recursion:

```
f=lambda n,i=0:i<26and['%*c'%(min(i+1,n),i+97)]+f(n,i+1)or[]

```
> 1 votes

# Answer
# SOGL V0.12, 12 bytes

```
z{ē.-.Hχ@*Ot

```

Try it Here!
> 1 votes

# Answer
# Perl 5, ~~47~~ 39 bytes

```
$l=<>;say$"x($#i+=$#i<$l-1).$_ for a..z

```

Try it online!
> 1 votes

# Answer
# Python 3, 52 bytes

```
lambda n:[('%*c'%(i,i+96))[-n:]for i in range(1,27)]

```

Try it online!
> 1 votes

# Answer
# C (gcc), 50 bytes

```
i;f(n){for(;i<26;printf("%*c\n",i++<n?i:n,i+97));}

```

Try it online!
> 1 votes

# Answer
# Pyth, 12 bytes

```
j.e+<*kdtQbG

```

**Try it here!**

If lists of Strings are allowed, this can be shortened to **11 bytes**:

```
.e+<*kdtQbG

```

# Pyth, 12 bytes

```
VG+<*dxGNtQN

```

**Try it here!**

# Pyth, 14 bytes

```
jm+<*d;tQ@Gd26

```

**Try it here.**

If lists of Strings are allowed, this can be shortened to **13 bytes**:

```
m+<*d;tQ@Gd26

```

---

# How do these work?

Unlike most of the other answers, this maps / loops over the lowercase alphabet in all 3 solutions.

### Explanation #1

```
j.e+<*kdtQbG - Full program.

 .e        G - Enumerated map over "abcdefghijklmnopqrstuvwxyz", with indexes k and values b.
     *kd     - Repeat a space a number of times equal to the letter's index.
    <   tQ   - Crop the spaces after the input.
   +      b  - Concatenate with the letter.
j            - (Optional): Join by newlines.

```

### Explanation #2

```
VG+<*dxGNtQN  - Full program.

VG            - For N in "abcdefghijklmnopqrstuvwxyz".
      xGN     - Index of the letter in the alphabet.
    *d        - Repeat the space a number of times equal to the index above.
   <     tQ   - But crop anything higher than the input.
  +        N  - Append the letter (at the end)

```

### Explanation #3

```
jm+<*d;tQ@Gd26 - Full program.

 m          26 - Map over [0...26) with a variable d.
    *d;        - Space repeated d times.
   <   tQ      - Crop anything whose length is higher than the input.
  +      @Gd   - Concatenate with the letter at that index in the alphabet.
j              - (Optional): Join by newlines.

```
> 1 votes

# Answer
# Proton, 40 bytes

Assuming that a list of Strings is fine.

```
k=>[(i*" ")[to~-k]+chr(i+97)for i:0..26]

```

Try it online!

# Proton, 49 bytes

As ASCII-art instead:

```
k=>'\n'.join((i*" ")[to~-k]+chr(i+97)for i:0..26)

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 66 + 18 bytes

```
n=>new int[26].Select((x,i)=>$"{(char)(i+97)}".PadLeft(i<n?i+1:n))

```

Byte count also includes

```
using System.Linq;

```

Try it online!

This returns a collection of strings, one for each line. If it's not allowed, the answer will swell by 17 bytes for `string.Concat()` and `\n` inside string

Explanation:

```
n =>
    new int[26]                      // Create a new collection of size 26
    .Select((x, i) =>                // Replace its members with:
        $"{(char)(i + 97)}"          // String of an alphabet character corresponding to the index
        .PadLeft(i < n ? i + 1 : n)  // Add spaces to the left
    )

```
> 1 votes

# Answer
# MATL, 14 bytes

```
26:tiXl2Y2oZ?c

```

Try it at MATL Online

**Explanation**

```
26      % number literal
:       % range; vector of equally spaced values [1...26]
t       % duplicate
i       % explicitly grab the input
Xl      % clamp the array to have a maximum value of the input
2Y2     % predefined literal: ['a'...'z']
o       % convert to a numeric array
Z?      % create sparse matrix using the first two inputs as the rows/columns
        % and the letters 'a'...'z' as the values
c       % convert back to character and implicitly display

```
> 1 votes

# Answer
# Perl 5, 36 bytes

**31 bytes code + 5 for `-i# -l`.**

**Note**: this takes input via `-i`, if that is unacceptable (since it's non-standard) I can remove.

```
$\.=$"x(--$^I>0),print for a..z

```

Try it online!

### Explanation

For this I'm abusing the special variable `$\` which is automatically printed after each call to `print`, to store the next line's indentation. Using the flag `-l` (which enables line ending processing), `$\` is pre-initialised to `"\n"` so we append a space each time we process an element in the range `a..z`, as long as `--$^I` isn't less than `0`. Using `$^I` (via the `-i` commandline flag) means I don't need to store input separately, but it's bit of a stretch as its not the usual way to accept input in Perl. Since the postfix `for` loop stores the current item in `$_`, we don't need any arguments to `print` (`$_` is automatically `print`ed and `$\` is automatically appended) so we just call it each iteration, appending spaces as we go to get the desired output. This does append trailing spaces though, which @SpookyGengar has allowed.

Thanks to @Xcali for pointing out an oversight!
> 1 votes

# Answer
# Haskell, 60 bytes

```
f n=unlines$scanl(\p c->take(n-1)(p>>" ")++[c])"a"['b'..'z']

```

This is a function that returns the output as a String.

Try it online.
> 1 votes

# Answer
# Java 1.8 (without Lambda), 98 Bytes

```
void m(int i){int c=0,o=97;String s="";for(;c++<26;s+=c<i?" ":"")System.out.println(s+(char)o++);}

```

The logic is straightforward. Provides no input data validation, very bad!

* Update: Function only! Thank you to @Olivier Grégoire
> 1 votes

# Answer
# q/kdb+, ~~33~~ 31 bytes

**Solution:**

```
-1{(&[x-1;til 26]#'" "),'.Q.a};

```

**Example:**

```
q)-1{(&[x-1;til 26]#'" "),'.Q.a}16;
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

```

**Explanation:**

Create a list of spaces (26) up to the length of the minimum of the input and the range of `0..25`), join with each letter of the alphabet, print to stdout.

```
-1{(&[x-1;til 26]#'" "),'.Q.a}; / solution
-1                            ; / print result to stdout and swallow return
  {                          }  / lambda function
                         .Q.a   / "abcd..xyz"
                       ,'       / concatenate (,) each
   (                  )         / do all this together
    &[   ;      ]               / minimum of each
      x-1                       / implicit input (e.g. 10) minus 1 (e.g. 9)
          til 26                / 0 1 2 ... 23 24 25
                   '#" "        / take " " each number of times (0 1 2 )

```

**Notes:**

* -2 bytes by rejigging the brackets
> 1 votes

# Answer
# SimpleTemplate, ~~79~~ 70 bytes

The code outputs the required text and a trailing newline.

```
{@forfrom"a"to"z"}{@echols,_}{@inca}{@ifa is lowerargv.0}{@sets s," "}

```

**Ungolfed**:

```
{@for letter from "a" to "z"}
    {@echo spaces, letter, EOL} {@// same as echol}
    {@inc by 1 index} {@// sets to 1 if it doesn't exist}
    {@if index is lower than argv.0}
        {@// creates an array like [[[...], " "], " "]}
        {@set spaces spaces, " "}
    {@/} {@//not required}
{@/} {@// not required}

```

You can try it on http://sandbox.onlinephpfunctions.com/code/a0ee99464f463d23072ff5d5be7dbd3a532f9c7c

(Old version: http://sandbox.onlinephpfunctions.com/code/a60e11b9dd2dcd54a84c11937f1918f26e0adcfa)
> 1 votes

# Answer
# PowerShell, ~~66~~ 60 bytes

```
param($a)65..90|%{" "*(($b=$_-65),($a-1))[$b-ge$a]+[char]$_}

```

Try it online!

Loops through the alphabet, each iteration using string multiplication to prepend the appropriate number of spaces (chosen using a pesudo-ternary `(,)[]`), then string-concatenates with the current character.
> 1 votes

# Answer
# Pyke, 6 bytes

```
G\xb1oh->

```

Try it here!

```
          - o = 0
G         -  alphabet
 \xb1     - for i in ^: (1 byte, pretty prints)
     oh   -    (o++)+1
       -  -   " "*^ + i
        > -  ^[input:]

```
> 1 votes

# Answer
# Bash, 50 bytes

```
for c in {A..Z};{ printf "%$[++i<$1?i:$1]s\n" $c;}

```

Try it online!

Takes input as a command-line argument.
> 1 votes

# Answer
# Japt `-R`, 9 bytes

```
;C¬ËùUm°E

```

Try it

```
;C¬ËùUm°E     :Implicit input of integer U
;C            :Lowercase alphabet
  ¬           :Split
   Ë          :Map each character at 0-based index E
    ù         :Left pad with spaces to length
     Um       :  Minimum of U and
       °E     :  E incremented
              :Implicit output joined with newlines

```
> 1 votes

# Answer
# Forth (gforth), 53 bytes

```
: f 1- 26. do dup i min spaces i 97 + emit cr loop ;

```

Try it online!

Pretty standard answer.
> 1 votes

# Answer
# Python 3, 101 bytes

```
def f(n,a=0):
 b="abcdefghijklmnopqrstuvwxyz"
 for l in range(len(b)):print(" "*a,b[l]);a+=[0,1][l<n]

```

Try it online!
> 1 votes

# Answer
# \>\<\> (-v), 51+2 Bytes

```
'a'$1-0\   /' 'o1-81.
'z')?;}>::?/~$:@@:@)+{:oao1+:

```

**Try it online**

## equivalent pseudo code

```
char = 'a'
input = read_number
input -= 1
tabCount = 0

while true
    for i from 0 to tabCount
        print ' '
    if tabCount < input
        ++tabCount
    print char
    print '\n'
    ++char
    if char > 'z'
        exit

```
> 0 votes

# Answer
# Excel VBA, <sub>~~53~~</sub> 50 Bytes

Anonymous VBE immediate window function that takes input of expected type `Integer` in the domain of `[1,26]` from range `[A1]` and outputs to the VBE immediate window

```
For i=0To 25:[B1]=i:?Spc([Min(1:1)])Chr(97+i):Next

```
> 0 votes

# Answer
# Brainbash, 98 bytes

```
+[-[---<]>>-]<-~++++++++[>++++>+++>+<<<-]>>++>++>#-<<[>>>[-<<<<.>>>>>+<]>[-<+>]<<{->+<}<<-~.+~>.<]

```

Try it online!

## Explanation

The code can be split into two parts:

```
+[-[---<]>>-]<-~++++++++[>++++>+++>+<<<-]>>++>++>#
-<<[>>>[-<<<<.>>>>>+<]>[-<+>]<<{->+<}<<-~.+~>.<]

```

Basically, generate the constants `97`, `32`, and `26`. Then, takes a number `N` as input. After input (`#`) the tape looks like:

```
[ ]   0      0     >97     0
[*]   0      32     26     10    >0

```

The second part executes `26` times, each time decrementing the input. Every time the input is decremented, the prefix length is incremented. After the input reaches zero, the prefix length remain constant. After each loop, the spaces, the letter, and a newline are printed.
> 0 votes

# Answer
# Röda, 48 bytes

```
f n{seq 1,26|min([n,_])<>chr 96+_1|print" "*_,_}

```

Try it online!

Each output line has one leading space.

Explanation:

```
f n{
  seq 1,26|    /* push numbers 1..26 to the stream (inclusive) */
               /* for each number in the stream: */
  min([n,_])<> /*  push min(n, _1) */
  chr 96+_1|   /*  push string containing _1 as a letter */
               /* for each number _1 and letter _2 in the stream: */
  print" "*_,_ /*  print _1 spaces and _2 */
}

```
> 0 votes

# Answer
## Elixir, 145 bytes

```
{n,_}=IO.gets("")|>Integer.parse;for x<-?a..?z,do: if x-97<n,do: IO.puts String.pad_leading(<<x>>,x-96),else: IO.puts String.pad_leading(<<x>>,n)

```

Try online
> 0 votes

# Answer
# PHP, 67 bytes

```
<?for($l=a;$l!=aa;)echo str_pad($l++,min($argv[1],++$x)," ",0)."
";

```

Try it online!
> 0 votes

# Answer
**VBA Excel, 51 bytes**

using Immediate Window and `[a1]` as input

```
for x=1to 26:?spc(iif(x<[a1],x,[a1]))chr(96+x):next

```
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 107 bytes

```
	N =INPUT
I	&LCASE POS(R) LEN(1) . L
	OUTPUT =DUPL(' ',X) L
	R =R + 1
	X =LT(R,N) X + 1
	LT(R,26)	:S(I)
END

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
27α‚A34SΛ

```

Try it online.

A golfed version of the existing 05AB1E answer in the new 05AB1E version is **9 bytes** as well:

```
Av<N‚ßyú,

```

Try it online.

**Explanation:**

```
27α        # Take the absolute difference of 27 with the (implicit) input
   ‚       # Pair it to the (implicit) input
    A      # Push the lowercase alphabet
     34S   # Push 34 as a list of digits: [3,4]
        Λ  # Use the Canvas builtin with these three as arguments:
           #  Direction [3,4], which translates to [↘,↓]
           #  Characters to draw: the lowercase alphabet
           #  Length of each part to draw: [input,|input-27|]
           # (after which the result is output immediately afterwards)

```

See this 05AB1E tip of mine for an in-depth explanation of how the canvas builtin works.

```
A          # Push the lowercase alphabet
 v         # Pop and loop over each of its characters `y`:
  <        #  Decrease the (implicit) input by 1
   N‚      #  Pair it with the 0-based loop index
     ß     #  Pop and push the minimum of this pair
      y    #  Push the current character
       ú   #  Pop both, and pad the character with leading spaces equal to the integer
        ,  #  Pop and print this string with trailing newline

```
> 0 votes

# Answer
# Vyxal `j`, 9 bytes

```
ka¨2?‹∵Ip

```

Try it Online!
> 0 votes

# Answer
# Python 3, 57 bytes

```
lambda n:[f"{chr(65+i):>{min(i+1,n)}}"for i in range(26)]

```

Try it online!

Used python formatting to automatically put spaces in output i.e. `{'a':>5}` will give  `a`
> 0 votes

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


title: Tips for Golfing in Standard ML

text:
# Question
Title: Tips for Golfing in Standard ML
**Standard ML** (or golfier: SML) is a general-purpose, modular, functional programming language with compile-time type checking and type inference. <sup>(from Wikipedia)</sup>

Though you almost certainly will never win a code golf challenge with SML, (ab-) using it for golfing can nevertheless be quite `fun` (\<- keyword for function declaration). So without further ado ...

# What tips do you have for golfing in Standard ML?

Please only post tips which are somewhat unique to SML. General golfing tips belong to Tips for golfing in all languages.

# Answer
# Use symbolic identifiers

From *The Definition of Standard Ml (revised)* \[PDF\], Section 2.4:

> An identifier is either *alphanumeric*: any sequence of letters, digits, primes (`'`) and underbars (`_`) starting with a letter or prime, or *symbolic*: any non-empty sequence of the following symbols:
>
> ```
> !  %  &  $  #  +  -  /  :  <  =  >  ?  @  \  ~  ‘  ^  |  *
>
> ```
>
> In either case, however, reserved words are excluded. This means that for example `#` and `|` are not identifiers, but `##` and `|=|` are identifiers.

The important part (concerning golfing) is that you do not need white space between symbolic identifiers and alphanumeric identifiers or keywords.

### Example

```
fun f a b c=if b then a else c

```

By replacing `f` by `$` and `b` by `!`, we can save 6 bytes:

```
fun$a!c=if!then a else c

```

Note, however, that a symbolic identifier needs white space when next to other symbols. That's why we cannot replace `a` and `c` in the above example to get to the same byte count:

```
fun f$b!=if b then$else!    (* syntax error because != is parsed as one token *)

```
> 9 votes

# Answer
# List functions

Lists are the standard data structure usually used recursively with `::` constructor. Indexing must be done using `nth`.

Short and maybe useful functions are

* `@`: append
* `hd`: head, but also try pattern matching
* `tl`: all but head
* `last`: tail
* `take`: first n elements
* `drop`: drop first n elements and return
* `rev`: reverse

Higher order functions:

* `map`: map
* `foldr`, `foldl`: fold and reverse fold
* `filter`: filter
* `exists`, `all`: exists, all bool cond
> 2 votes

# Answer
# Pattern matching in functions

Concise way to extract the values and write cases for recursive functions. Case statements are probably too long.

Extracting values:

```
fn(x,y)=>x+y   (* lambda fn *)
fun f x y=x+y  (* curried bound function *)

```

Recursive function with base case (this basic list sum is equivalent to `foldl op+ 0`):

```
fun f(x::L)=x+f L|f _=0

```
> 1 votes

# Answer
# Use wildcard matching instead of explicit matching

This broadly applies to any pattern matching construct with a fallthrough or wildcard: in some situations you can use the wildcard to match a pattern instead of an explicit pattern.

Empty list example (with formatting for clarity):

```
fun f([]) = 0
  | f(x::L) = x + f L

```

versus matching with wildcard saving a byte:

```
fun f(x::L) = x + f L
  | f(_) = 0

```
> 1 votes

---
Tags: tips
---


title: But is it a pretty place?

text:
# Question
Title: But is it a pretty place?
Your challenge, should you choose to accept it, is to take as input:

1. A program in DirectionLang (as an ASCII string consisting of DirectionLang instructions)
2. A list of pairs of integers, henceforth known as the pretty places. This list may be taken in any reasonable format.

You should then output a truthy value if the program halted at a pretty place, and a falsey value otherwise.

## DirectionLang

A DirectionLang instruction is hereby defined to be either

1. `<`: Decrement the x coordinate by 1.
2. `>`: Increment the x coordinate by 1.
3. `^`: Increment the y coordinate by 1.
4. `V`: Decrement the y coordinate by 1.
5. `S`: Skip the next instruction if the program is currently at a pretty place.

A DirectionLang program is executed by performing each instruction, in order. A DirectionLang program starts at the origin (coordinates `(0, 0)`). A DirectionLang program halts when every instruction has been executed.

If a DirectionLang program ends with an `S`, then its behavior is undefined.

If a DirectionLang program has no instructions, then its behavior is undefined.

DirectionLang is quite obviously not Turing complete, as there is not a way of looping.

## Test cases

```
"<>^^" [(0, 2), (0, 0)] -> True
"<>^^" [(0, 1)] -> False
"S^>>" [(0, 0), (2, 0)] -> True
"<SS^" [(-1, 0), (-1, 1)] -> True
"<SS^" [(-1, 0), (-1, -1)] -> False
"S^>>" [(2, 0)] -> False
"S^>>V" [(2, 0)] -> True

```

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

Expects `(program_string)(pretty_places)`. Returns \\$0\\$ or \\$1\\$.

```
s=>a=>Buffer(s+0).map(n=>(p=a.some(a=>x+[,y]==a),+s)?s=0:(n%=5)-3?y-=~-"121"[x+=n%3-1,n]:s=p,x=y=0)|p

```

Try it online!

### How?

The ASCII codes of the DirectionLang instructions are unique modulo \\$5\\$. Furthermore, the value of \\$dx\\$ can be easily deduced from them with an additional modulo \\$3\\$. We use a short lookup string for \\$dy\\$.

```
 char. | c  | n = c mod 5 | dx = (n mod 3) - 1 | dy = -~-"121"[n]
-------+----+-------------+--------------------+------------------
  "<"  | 60 |      0      |         -1         |        0
  ">"  | 62 |      2      |          1         |        0
  "^"  | 94 |      4      |          0         |        1
  "V"  | 86 |      1      |          0         |       -1
  "S"  | 83 |      3      |         n/a        |       n/a

```
> 4 votes

# Answer
# JavaScript, ~~118~~ 111 bytes

-7 bytes thanks to Arnauld!

```
p=>g=([d,...r],x=0,y=0,i='S>V ^'.indexOf(d),P=p.some(a=>x+[,y]==a))=>d?g(r.slice(!i&P),i<2?x+i:x,i<2?y:y+i-3):P

```

Try it online!

A recursive function expecting input as `f(p)(d)`, where `p` is a 2D array of pretty places, and `d` is a string of instructions. Outputs `true` if in a pretty place, otherwise `false`.

#### Ungolfed and Explained

```
p => g = (       // p = pretty places (PP's), g = recursive func
  [d, ...r],     // split instruction string and look at first char
  x = 0, y = 0,  // set default x and y
  i = 'S>V ^'.indexOf(d),   // find index of command
  P = p.some(a => x + [, y] == a)  // check if we are at PP
) => d ?  // check if we are at end of input
  g(      // if not, recurse
    r.slice(!i & P),       // if char is 'S' and at PP, skip one
    i < 2 ? x + i : x,     // if i < 2, change x by i
    i < 2 ? y : y + i - 3  // if i >= 2, change y by i-3
  ) :
  P       // if at end, return P

```

## Previous Answer, ~~125~~ 121 bytes

-4 bytes thanks to Steffan!

```
p=>g=([d,...r],x=0,y=0,P=!p.every(([u,v])=>u-x||v-y))=>d?g(r.slice(P&d=='S'),x+~~{'<':-1,'>':1}[d],y+~~{V:-1,'^':1}[d]):P

```

Try it online!

A recursive function expecting input as `f(p)(d)`, where `p` is a 2D array of pretty places, and `d` is a string of instructions. Outputs `true` if in a pretty place, otherwise `false`.

#### Ungolfed and Explained

```
p => g = (       // p = pretty places (PP's), g = recursive func
  [d, ...r],     // split instruction string and look at first char
  x = 0, y = 0,  // set default x and y
  P = !p.every(([u, v]) => u - x || v - y)  // check if we are at PP
) => d ?  // check if we are at end of input
  g(      // if not, recurse
    r.slice(P & d == 'S'),          // if char is 'S' and at PP, skip one
    x + ~~{'<': -1, '>': 1}[d],  // increment x by lookup
    y + ~~{V: -1, '^': 1}[d]     // increment y by lookup
  ) :
  P       // if at end, return P

```
> 3 votes

# Answer
# Python, 128 bytes

*-39 bytes thanks to `Wheat Wizard` and -12 bytes thanks to `ovs`.*

```
def f(p,l):
 s=a=0
 while p:h=p[0];s+=abs('< >'.find(h))-1;a+=abs('V ^'.find(h))-1;p=p[1+(h=='S'and(s,a)in l):]
 return(s,a)in l

```

Attempt This Online!
> 3 votes

# Answer
# Charcoal, 42 bytes

```
ＦＡ«Ｊ⊟ι⊟ι1»Ｊ⁰¦⁰ＦＳＦ¬∧υΣ⊟υ≡ιS⊞υＫＫＭ✳⊗⌕^<VιＴ¹¦¹

```

Try it online! Link is to verbose version of code. Takes the pretty places as the first argument and outputs `1` if the directions end on a pretty place, nothing if not. Explanation:

```
ＦＡ«

```

Loop over the pretty places.

```
Ｊ⊟ι⊟ι

```

Jump to those coordinates. (Note that on canvas they are actually rotated 90° from the description but I rotate the movements to compensate.)

```
1

```

Mark each pretty place with a `1`.

```
»Ｊ⁰¦⁰

```

Jump back to the origin.

```
ＦＳ

```

Loop over the instructions.

```
Ｆ¬∧υΣ⊟υ

```

If the previous instruction was not an `S` or we were not at a pretty place, then...

```
≡ιS

```

... if the current instruction is an `S` then...

```
⊞υＫＫ

```

... save the current cell for the check on the next loop, otherwise...

```
Ｍ✳⊗⌕^<Vι

```

... move in the appropriate direction.

```
Ｔ¹¦¹

```

Delete the canvas except for the current cell.
> 2 votes

# Answer
# Python 2, ~~112~~ ~~105~~ 102 bytes

*-7 bytes using the (c mod 5) formula from Arnauld's JavaScript answer*

```
s,p=input()
x=y=0
while s:k=(x,y)in p;exec'xyxky--+++'[ord(s[0])%5::5]+'=1';s=s[1+k/2:]
print(x,y)in p

```

Try it online!

Accepts input from STDIN as `<DirectionLang string>, <pretty places>`
> 2 votes

# Answer
# \[Ruby (2.7.0)\], 143 bytes

```
x=0i
y=!p
_,d,v=t.split ?"
a={?<=>-1,?>=>1,?^=>1i,?V=>-1i,?S=>0}
(d+?S).chars.map{|c|x+=a[c]if y
y=y&&c==?S?!v.match("(#{x.rect*', '})"):!p}
!y

```

Decided to try using complex numbers. Probably would be easier to do x,y and separate increment statements. The "a" hash is what we add to x for each character, the "y" is "yes" for if we should do the next line. We add an 'S' on the end to force the final comparison and return !y. Converting the complex number to "(x, y)" was pretty costly. Just uses a string match to see if the place is nice.

I should point out that "t" is the variable containing the full test string (the "program" and the nice values), if you needed it to be stdin, you'd need to change that to a gets or such. The final statement is the return value (!y), you'd need a "p !y" or $\> or such if you want it printed. Right now you can test/run it by wrapping it in a def like:

```
def directionLang(t)
   <code golf above>
end

```

\[edit\]

Actually I just wrote it without complex numbers and was surprised that it grew. There'd probably be a better way to handle the addition, but here's the basic code:

```
x=y=0
m=!p
_,d,v=t.split ?"
(d+?S).chars.map{|c|x+=(c==?<)?-1:(c==?>)?1:0if m
y+=(c==?V)?-1:(c==?^)?1:0if m
m=m&&c==?S?!v.match("(#{x}, #{y})"):!p}
!m

```
> 2 votes

# Answer
# MATL, ~~39~~ ~~38~~ ~~35~~ 33 bytes

```
x0Ti"@2\?y1GmY~}J@k11\Q^/+T]]x1Gm

```

Inputs are: a vector of complex coordinates, then a string.

Try it online! Or verify all test cases.

### How it works

```
x          % Input: numeric vector of complex coordinates. Delete
0          % Push 0. This is the complex coordinate where the program starts
T          % Push true. This is the interpret state: if false, the next
           % instruction should be skipped
i"         % Input: string containing the instrunctions. For each instruction:
  @2\      %   Push current instruction (converted to ASCII code), modulo 2
  ?        %   If nonzero (this is true only for 'S')
    y      %     Duplicate from below: push copy of current coordinate
    1Gm    %     Is it in the first input, i.e. is it pretty? Gives true or false
    Y~     %     XOR with interpret state. This toggles the interpret state.
           %     So if the state was true, it is now set to false because the
           %     current instruction is 'S' and the current coordinate is pretty.
           %     If the state was false, that means that the current instruction
           %     should have been skipped. So we simply set the interpret state
           %     to true
  }        %   Else (the current instruction is not 'S', but may need skipping)
    J      %     Push j (imaginary unit)
    @k     %     Push current instruction converted to lowercase
    11\    %     (Convert to ASCII code) modulo 11
    Q      %     Add 1
    ^      %     Power. This gives -1 for '<', 1 for '>', -j for '^', j for 'V'.
           %     Note that the values for '^' and 'V' are reversed
    /      %     Divide the current interpret state (true: 1, or false: 0) by
           %     the above value. Dividing, instead of multiplying, has the
           %     effect of reversing the values for '^' and 'V' (and not those
           %     for '<' and '>'), and gives 0 if the interpret state is false
    *      %     Add the result to the current coordinate, to update it
    T      %     Push interpret state (note that it has been consumed) as true
  ]        %   End
]          % End
x          % Delete interpret state
1Gm        % Is the current coordinate a member of the first input? Gives true
           % or false. Implicit display

```
> 1 votes

# Answer
# Java 10, 168 bytes

```
P->C->{var r=0>1;int x=0,y=0,f=9;for(var c:(P+0).getBytes()){r=0>1;for(var t:C)r|=x==t[0]&y==t[1];y+=f<1&r|c%7>3?0:c%6-3;x+=f<1&r|c%9<6?0:c%5-1;f=f<1?9:c%83;}return r;}

```

Try it online.

**Explanation:**

```
P->C->{          // Method with String + 2D int-array parameters & boolean return
  var r=0>1;     //  PrettyPlace-flag, starting at false
  int x=0,y=0,   //  x,y coordinates, starting at 0,0
      f=9;       //  Skip-flag, starting at non-0
  for(var c:(P+0)//  Append a trailing dummy '0' to the path-String (to determine
                 //  if we're at a PrettyPlace after the last input-character)
            .getBytes()){
                 //  Loop over the characters as codepoints:
    r=0>1;       //   Reset the PrettyPlace-flag to false
    for(var t:C) //   Loop over the input-coordinates:
      r|=        //    Check if any is truthy for the PrettyPlace-flag:
         x==t[0]&y==t[1];
                 //     Where an input-coordinate matches the current x,y
    y+=          //   Modify the y-coordinate by increasing with:
       f<1       //    If the skip-flag is 0,
       &r        //    and the PrettyPlace-flag is truthy
       |c%7>3?   //    Or if the current character is 'S'/'^'/'V':
         0       //     Leave y the same by increasing with 0
       :         //    Else (the current character is '<'/'>'):
         c%6-3;  //     Add -1 if '<', or add 1 if '>'
    x+=          //   Modify the x-coordinate by increasing with:
       f<1       //    If the skip-flag is 0,
       &r        //    and the PrettyPlace-flag is truthy
       |c%9<6?   //    Or if the current character is 'S'/'<'/'>':
         0       //     Leave x the same by increasing with 0
       :         //    Else (the current character is '^'/'V'):
         c%5-1;  //     Add -1 if 'V', or add 1 if '^'
    f=           //   Change the skip-flag to:
      f<1?       //    If the skip-flag was 0 this iteration:
        9        //     Reset it back to non-0
      :          //    Else:
        c%83;}   //     Set it to `c` modulo-83 (0 for 'S', non-0 otherwise)
  return r;}     //  After the loop, return the last PrettyPlace-flag as result

```

How the magic numbering works for the characters:

| Character | `c` | `c%7>3` | `c%6-3` | `c%9<6` | `c%5-1` | `c%83` |
| --- | --- | --- | --- | --- | --- | --- |
| '\<' | 60 | true |  | false | -1 | 60 |
| '\>' | 62 | true |  | false | 1 | 62 |
| '^' | 94 | false | 1 | true |  | 11 |
| 'V' | 86 | false | -1 | true |  | 3 |
| 'S' | 83 | true |  | true |  | 0 |
> 1 votes

---
Tags: code-golf, string, decision-problem
---


title: Alphabet triangle strikes again

text:
# Question
Title: Alphabet triangle strikes again
# Task

Your task is to print this exact text:

```
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
NOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY
ZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
JKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZA
BCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ

```

# Specs

* You may do it in all-lowercase instead of all-uppercase.
* Trailing newlines at the end of the triangle is allowed.
* Trailing spaces after each line is allowed.
* You must print to STDOUT instead of outputting an array of strings.

# Scoring

This is . Program with lowest byte-count wins.

# Answer
# Vim, 29 bytes

```
:h<_↵↵↵y$ZZ26P0qqa↵♥βjllq25@q

```

Where  represents the Return key,  the Escape key, and `β` the Backspace key.
> 41 votes

# Answer
# Python 2, 65 bytes

```
i=1
a=bytearray(range(65,91))*26
while a:print a[:i];a=a[i:];i+=2

```
> 9 votes

# Answer
# Jelly, 10 bytes

```
26RḤ’RØAṁY

```

Try it online!

### How it works

```
26RḤ’RØAṁY  Main link. No Arguments.

26          Set the return value to 26.
  R         Range; yield [1, 2, ..., 25, 26].
   Ḥ        Unhalve; yield [2, 4, ..., 50, 52].
    ’       Decrement; yield [1, 3, ..., 49, 51].
     R      Range; yield [[1], [1, 2, 3], ..., [1, ..., 49], [1, ..., 51]].
      ØA    Yield the uppercase alphabet.
        ṁ   Mold the alphabet as the array of ranges. This repeats the uppercase
            letters over an over again, until all integers in the range arrays
            have been replaced with letters.
         Y  Join, separating by linefeeds.

```
> 7 votes

# Answer
## VBA Excel (80 bytes, 1742 bytes)

---

# Excel, 1742 bytes

Inspired by the ugoren's creative answer, I managed to find an Excel formula to create the pattern as shown in the OP.

```
=MID(REPT("ABCDEFGHIJKLMNOPQRSTUVWXYZ",26),(ROW()-1)^2+1,2*ROW()-1)

```

Paste this formula in cell A1, then drag all over range A1:A26.

The length of the formula is 67 bytes but you have to replicate it 26 times, so it's equal to 67\*26=1742 bytes. Here is the output:

---

# Excel VBA, 80 bytes

Now it's possible we integrate Excel with VBA to automate the process and to save many bytes since VBA is built into most Microsoft Office applications, including Excel. Write and run the following code in the Immediate Window (use combination keys `CTRL`+`G` to display it in Visual Basic Editor):

```
[A1:A26]="=MID(REPT(""ABCDEFGHIJKLMNOPQRSTUVWXYZ"",26),(ROW()-1)^2+1,2*ROW()-1)"

```

The program works by printing the Excel formula above to the range A1:A26. Unfortunately, both Excel and VBA have no built-in alphabet.
> 7 votes

# Answer
## Haskell, 67 bytes

```
_#53=[]
s#i=take i s:drop i s#(i+2)
mapM putStrLn$cycle['A'..'Z']#1

```

A simple recursion over the length `i` of the line. In each step the next `i` chars are taken from an infinite repetition of the alphabet.
> 5 votes

# Answer
# Mathematica, 90 bytes

```
StringRiffle[Flatten[Alphabet[]&~Array~26]~Internal`PartitionRagged~Range[1,51,2],"
",""]&

```

Anonymous function. Takes no input and returns a string as output. Golfing suggestions welcome. An example of what `Internal`PartitionRagged` does:

```
In[1]:= Internal`PartitionRagged[{2, 3, 5, 7, 11, 13}, {2, 3, 1}]

Out[1]= {{2, 3}, {5, 7, 11}, {13}}

```
> 4 votes

# Answer
# C, 79 bytes

```
main(i,j){for(i=0,j=1;i<676;i++){putchar(i%26+65);if(j*j==i+1){puts("");j++;}}}

```

My first answer in C \o/

Golfing suggestions are more than welcome.
> 4 votes

# Answer
# Brachylog, 37 bytes

```
26~l<:1aLc~j[@A:I],L~@nw
=:2%1,.#@l?,

```

Try it online!

### Explanation

* Main predicate:

```
26~l         Let there be a list of 26 elements
<            This list is an ascending list of integers
:1aL         Apply predicate 1 to that list ; the resulting list of strings is L
c            Concatenate the list of strings into one big string
~j[@A:I],    That big string is the result of juxataposing the alphabet I times to itself
L~@n         Create a string which when splitted on line breaks results in L
w            Write that string to STDOUT

```
* Predicate 1: used to generate variable strings of odd lengths.

```
=            Assign a value to the Input
:2%1,        That value must be odd
.#@l?,       Output is a string of length Input

```
> 4 votes

# Answer
# Perl, ~~42~~ ~~41~~ 39 bytes

```
perl -E '@b=(A..Z)x26;say splice@b,0,$#a+=2for@b'

```

Just the code:

```
@b=(A..Z)x26;say splice@b,0,$#a+=2for@b

```

An obvious shorter version unfortunately triggers an internal perl problem (Use of freed value in iteration):

```
say splice@b,0,$#a+=2for@b=(A..Z)x26

```
> 4 votes

# Answer
# Pyramid Scheme, 1492 bytes

```
    ^         ^
   / \       / \
  /set\     /do \
 ^-----^   ^-----^
/a\   ^-  /!\   /[\
---  ^-  ^---  ^---^
    ^-  /=\   ^-  / \
   ^-  ^---^  -^ /out\
  ^-  ^-  /a\ ^- -----^
 ^-  / \  ---/[\     / \
 -^ /51 \   ^---^   /chr\
 ^- -----  ^-  / \  -----^
 -^       ^-  /do \     / \
 ^-      ^-  ^-----^   /10 \
 -^     /[\  -^   ^-   -----
 ^-    ^---^  -^  -^
 -^   / \  -^ /c\ ^-
 ^-  /set\ /[\--- -^
^-  ^-----^---^   ^-
-^ /a\   /+\  -^  -^
^- ---  ^---^  -^  -^
-^     /a\ /2\ / \  -^
 -^    --- ---/set\  -^
  -^         ^-----^ ^-
   -^       /c\   /a\-^
    -^      ---   --- -^
     -^               /[\
      -^             ^---^
       -^           ^-   -^
       /]\         / \    -^
      ^---^       /set\    -^
     ^-   -^     ^-----^    -^
    / \   ^-    /c\   /-\    -^
   /set\ ^-     ---  ^---^    -^
  ^-----^-          /c\ /1\    -^
 /b\   / \          --- ---    /]\
 ---  / -1\                   ^---^
      -----                  ^-  / \
                            / \ /out\
                           /set\-----^
                          ^-----^    -^
                         /b\   /?\    -^
                         ---  ^---^   / \
                             /!\  -^ /chr\
                            ^---  /+\-----^
                           /=\   ^---^   /+\
                          ^---^ /b\ /1\ ^---^
                         /b\ / \--- ---/ \ /b\
                         ---/25 \     /65 \---
                            -----     -----

```

Try it online!

Why? Why not?
> 4 votes

# Answer
# Pyth, 12 bytes

```
jtc*G26*Rd26

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 77 ~~82 88~~

EcmaScript 6 required just to save 1 byte using a template string literal for newline.

```
for(i=r=l=o='';l+52;r++||(r=l-=2,o+=`
`))o+=(i++%26+10).toString(36);alert(o)

```

*Less golfed*

```
for(i = r = l = o = '';
    l + 52;
    r++ || (r = l -= 2, o += `\n`))
  o += (i++ % 26 + 10).toString(36);
alert(o);

```

**Test**

```
for(i=r=l=o='';l+52;r++||(r=l-=2,o+=`
`))o+=(i++%26+10).toString(36);alert(o)
```
> 3 votes

# Answer
# Husk, 10 bytes

```
Cİ1ṠṁK…"AZ

```

Try it online!

### Explanation

```
Cİ1ṠṁK…"AZ
      …"AZ    Get the alphabet
   ṠṁK        Replace each letter with the whole alphabet
C             Cut the resulting string into lines with lengths
 İ1            equal to the list of odd numbers

```
> 3 votes

# Answer
# JavaScript, 129 bytes

```
z=1,i=0,g=a=>{b=0,c="";while(a+a-1>b){c+='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split``[i>26?i=0:i++];b++}console.log(c)};while(z<26)g(z++)

```
> 2 votes

# Answer
## Pyke, 14 bytes

```
G26*WDoh<
Ko>D

```

Try it here!
> 2 votes

# Answer
# Go, 133 bytes

```
package main
import S "strings"
func main(){s:=S.Repeat("ABCDEFGHIJKLMNOPQRSTUVXXYZ",26)
for i:=1;s!="";i+=2{println(s[:i]);s=s[i:]}}

```
> 2 votes

# Answer
# MATLAB, ~~112 109 95 79~~ 77 bytes

This will also work with **Octave**, you can try online here.

```
a=['' 65:90 65:90]';j=0;for i=1:2:52;b=circshift(a,j);j=j-i;disp(b(1:i)');end

```

So after some major changes, I've saved a further ~~14~~ 32 bytes. This one is getting to be much more like the length I would have expected from MATLAB. I've left the old version below as it is substantially different.

```
a=['' 65:90 65:90]';        %Create 2 copies of the upper case alphabet
j=0;                        %Initialise cumulative sum
for i=1:2:52;               %For each line length
    b=circshift(a,j);       %Rotate the alphabet string by the cumulative offset
    j=j-i;                  %Update cumulative negative sum of offsets.
    disp(
         b(1:i)'            %Extract first 'line length' characters from rotated alphabet.
               );           %Display next line (disp adds newline automatically)
end

```

---

**Original version:**

```
a=['' repmat(65:90,1,26)];c=cumsum(1:2:51);disp(cell2mat(arrayfun(@(s,f)[a(s:f) 10],[1,c(1:25)+1],c,'Un',0)))

```

Wow that one ended up being longer than I thought it would. I'll see if I can't knock a few bytes off it.

An ungolfed version to explain:

```
a=['' repmat(65:90,1,26)]; %Create 26 copies of the upper case alphabet
c=cumsum(1:2:51);          %Calculate the end index of each row in the above array, by cumulatively summing the length of each line
disp(
     cell2mat(
              arrayfun(@(s,f)
                             [a(s:f) 10], %Extract the part of the alphabet and insert a new line.
                                         [1,c(1:25)+1],c, %start index is the previous end of line plus 1. End index is as calculated by cumsum.
                       'Un',0 %The returned values are not all the same length
                       )   %Do this for each line
              )            %Convert back to a matrix now new lines inserted
     )                     %And display it

```

---

**Acknowledgements**

* 3 bytes saved - thanks @LuisMendo
> 2 votes

# Answer
## XPath 3.0 (and XQuery 3.0), 84 bytes

```
codepoints-to-string((0 to 25)!(subsequence(((1 to 26)!(65 to 90)),.*.+1,2*.+1),10))

```

Explanation:

`(1 to 26)!(65 to 90)` is the alphabet 26 times

`(0 to 25)!(subsequence(XX, start, len),10)` takes 26 subsequences of this, each followed by newline

`subsequence(X, .*.+1, 2*.+1)` takes successive subsequences with start position and length: (1, 1), (2, 3), (5, 5), (10, 9) etc.

`codepoints-to-string()` turns Unicode codepoints into characters
> 2 votes

# Answer
# Ruby, 46 bytes

```
26.times{|i|puts ([*?A..?Z]*26)[i*i,i*2+1]*""}

```

See it on ideone: http://ideone.com/3hGLB0
> 2 votes

# Answer
# 05AB1E (alternate) 15 bytes

```
A2×52µ¼D¾£,¾¼FÀ

```

Try it online!

Explanation:

```
A2×              # push a string containing a-za-z
   52µ           # Loop the rest of the program until counter = 52
      ¼          # increment counter (it's 0 initially)
       D         # Duplicate the alpha string on the stack
        ¾£       # Replace alpha with alpha[0..counter]
          ,      # Pop the substring and print it
           ¾¼FÀ  # rotate the alpha string left counter++ times.

```
> 2 votes

# Answer
# R, ~~120~~ ~~115~~ 111 bytes

```
v=c();for(i in 1:26){v=c(v,c(rep(LETTERS,26)[(sum((b=seq(1,51,2))[1:i-1])+1):sum(b[1:i])],"\n"))};cat(v,sep="")

```

**Ungolfed :**

```
a=rep(LETTERS,26)
b=seq(1,51,2)
v=vector()

for(i in 1:26)
    {
    v=c(v,c(a[(sum(b[1:i-1])+1):sum(b[1:i])],"\n"))
    }

cat(v,sep="")

```

Basically, `b` is the vector of the odd numbers between `1` and `51`, thus giving the length of each line. Obviously, the `sum` function *sums* the numbers of this vector, and gives the starting and ending indexes.

*-5 bytes* thanks to @plannapus !
*-4 bytes* thanks to @plannapus !
> 2 votes

# Answer
# R, 81 73 65 63 bytes

A simple `for` loop approach. Repeat the alphabet 26 times and loop through a sliding index range that is calculated using `(i^2-2*i+2):i^2`.

```
for(i in 1:26)cat(rep(LETTERS,26)[(i^2-2*i+2):i^2],"\n",sep="")

```
> 2 votes

# Answer
## Batch, 123 bytes

```
@set s=
@for /l %%i in (1,2,51)do @call set s=%%s%%ABCDEFGHIJKLMNOPQRSTUVWXYZ&call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%

```
> 1 votes

# Answer
# Dyalog APL, ~~31~~ ~~25~~ 23 bytes

Requires `⎕IO←0`, which is default on many systems.

```
↑(∊1,¨0⍴¨⍨2×⍳26)⊂676⍴⎕A

```

`676⍴⎕A` cycle the letters to get 676 of them

`(`...`)⊂` split on ones in

`⍳26` zero through 25; {0, 1, 2, 3, ..., 25}

multiply them by 2, {0, 2, 4, 6, ..., 50}

`0⍴¨⍨` generate zero-sequences of such lengths; {}, {0}, {0, 0}, etc.

`1,¨` prepend one to each sequence; {1}, {1, 0}, {1, 0, 0}, etc.

flatten; {1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, ..., 0}

stack the strings

TryAPL online!

-6 thanks to @jimmy23013
> 1 votes

# Answer
# 05AB1E, ~~18~~ 17 bytes

```
26FA26×N>n£NnF¦},

```

**Explanation**

```
26F                 # for N in range(0, 26) do
   A26×             # the alphabet repeated 26 times
       N>n£         # take (N+1)^2 letters
           NnF¦}    # throw away the first N^2 letters
                ,   # print with newline

```

Try it online!
> 1 votes

# Answer
# Actually, ~~27~~ ~~26~~ ~~22~~ ~~20~~ 17 bytes

Takes the lowercase alphabet 26 times, prints `1,3,5,...,(2*n+1)` at a time. Golfing suggestions welcome. Try it online!

**Edit:** Many thanks and -4 bytes to Leaky Nun and his suggestions.

```
úlú*iúl`╜u╟Σ)2╖`n

```

**Ungolfing:**

```
úl    Pushes 26 (the length of the lowercase alphabet).
ú*    26 * the lowercase alphabet.
i     Flatten the string.
úl    Pushes 26.
  `     Start function.
  ╜u    Push register 0 (default: 0) and increment (call it len, from now on)
  ╟     Take len elements from the stack
  Σ     sum() into a string.
  )     Rotate the string to the bottom of the stack.
  2╖    Add 2 to register 0.
  `     End function.
n     Run the above function (26) times.

```
> 1 votes

# Answer
# Dyalog APL, 18 bytes

`↑2{⍺↓⍵⍴⎕a}/×⍨0,⍳26`
> 1 votes

# Answer
# JavaScript (Using external library - Enumerable) (~~90~~ ~~88~~ ~~86~~ 80 bytes)

Link to lib: https://github.com/mvegh1/Enumerable

```
(z=_.Range)(0,26).WriteLine(x=>z(x*x,2*x+1).Write("",y=>(y%26+10).toString(36)))

```

Code explanation: Create range of ints 0 to 25, and for each write a new line according to the predicate. For each line, create a range of ints starting at the square of the current int, for a count of 2x+1. Then take that range, and join it into a string delimited by nothing where each int is casted to the String represented by the int ascii code
> 1 votes

# Answer
# PowerShell, 68 bytes

```
$a=-join(65..90|%{[char]$_})*26;26..1|%{$a=$a.Insert($_*$_,"`n")};$a

```

The section before the first semicolon produces a string containing 26 copies of the uppercase alphabet. The next section injects linebreaks at the index of each square number (working backward so I don't have to account for the shifting). Finally, the `$a` at the end just shoves that string variable onto PowerShell's equivalent of `STDOUT`.
> 1 votes

# Answer
# TSQL, 129 bytes

USE MASTER in the beginning of the script is to ensure that the query is run in the master database which is default for many users(not counting bytes for that).

**Golfed:**

```
USE MASTER

SELECT SUBSTRING(REPLICATE('ABCDEFGHIJKLMNOPQRSTUVWXYZ',26),number*number+1,number*2+1)FROM spt_values WHERE number<26and'P'=type

```

**Ungolfed:**

```
USE MASTER

SELECT SUBSTRING(REPLICATE('ABCDEFGHIJKLMNOPQRSTUVWXYZ',26),number*number+1,number*2+1)
FROM spt_values
WHERE number<26and'P'=type

```

**Fiddle**

**Fiddle for older version using xml path**
> 1 votes

# Answer
# Rexx, ~~74~~ 72 bytes

```
i=1;m=1;do 26;say substr(copies(xrange('A','Z'),26),i,m);i=i+m;m=m+2;end

```

Ungolfed:

```
i=1
m=1
do 26
  say substr(copies(xrange('A','Z'),26),i,m)
  i=i+m
  m=m+2
end

```
> 1 votes

# Answer
# C, 60 bytes

```
i;main(j){for(;j<27;j*j^++i||puts("",j++))putchar(i%26+65);}

```
> 1 votes

# Answer
## C++, 122 108 bytes

```
void a(){int a=65,l,i;for(l=1;l<53;l+=2){for(i=0;i<l;i++){std::putchar(a);a>90?a=65:a++;}std::cout<<'\n';}}

```

First time trying my hand at one of these, so it'll probably be super inefficient.

It creates an integer `a`, then enters a for loop with `l` representing the number of characters in a line (stopping when reaching the maximum amount, 53) Inside the loop, it enters another loop based on the value of `l`, which prints `a` to the console, then either increments it or sets it back to `A`. After completing that loop, it prints a `newline` to extend the pyramid.

EDIT: Improved by changing `a` from a char to an int, which eliminates the need for `(int)a++` among other things and saves precious bytes. Also replaced the while statement with an equivalent for.
> 1 votes

# Answer
# C++, 111 bytes

```
void a(){int c=65,i,j;for(i=0;i<26;i++){for(j=0;j<=2*i;j++){std::cout<<(char)c;c++;if(c==91)c=65;}std::cout<<'\n';}}

```

First try at one of these. Uses an int "c" to record which letter it needs to print at any given time. Once "c" passes 90 ('Z') it gets reset to 65 ('A'). Prints the pyramid using for loops.
> 1 votes

# Answer
# PHP, ~~76~~ 69 bytes

```
for(;$i<26&&$a.=join(range(A,Z));)echo substr($a,$i**2,1+2*$i++)."
";

```
* Create 26 alphabet (more than enough) and contactenate them in $a
* loop for i \< 26
* display $a substring start i^2, end 2\*i+1
> 1 votes

# Answer
# C#, 153 Bytes

```
using b=System.Console;class a{static void Main(){int i=0,j=0,k=0;while(i<26){b.Write((char)(65+j));j++;j%=26;k++;if(2*i+1==k){b.WriteLine();i++;k=0;}}}}

```

Compile using Microsoft .NET Framework 2.0 or later. (Written using Visual Studio 2015 Update 3.)
> 1 votes

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

```
A27×26L·<£»

```

Try it online!

Explanation:

```
A27×         # Push the alphabet repeated 27 times
    26L      # Push [1, 2, ..., 26]
       ·     # Multiply by 2 [2, 4, ..., 52]
        <    # Subtract 1 [1, 3, ..., 51]
         £   # Repeated slice
          »  # Join by newlines
             # Implicit print

```
> 1 votes

# Answer
# MY-BASIC, 72 bytes

Anonymous function that takes no input and outputs to the console.

```
For J=1 To 51
For K=1 To J
I=I Mod 26+1
Print Chr(64+I)
Next
Print;
Next

```

Try it online!
> 1 votes

# Answer
# K4, 25 bytes

**Solution:**

```
-1(0,+\1+2*!25)_676#.Q.A;

```

**Example:**

```
q)k)-1(0,+\1+2*!25)_676#.Q.A;
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
NOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY
ZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
JKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZA
BCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ

```

**Explanation:**

Slice up a list of the alphabet repeated 26 times...

```
-1(0,+\1+2*!25)_676#.Q.A; / the solution
-1                      ; / print to STDOUT and swallow return
                    .Q.A  / uppercase alphabet A-Z
                676#      / 676 take from the alphabet
               _          / cut at indexes given by left
  (           )           / do this stuff together
           !25            / range 0..24
         2*               / multiply by 2
       1+                 / add 1
     +\                   / calculate sums of list
   0,                     / prepend 0

```
> 1 votes

# Answer
## Pyth, 14 bytes

```
V26:*26G^N2^hN2

```

Try it here!

```
V26             - for N in range(26):
        ^N2     -   N**2
   :*26G        -  (alphabet*26)[^:V]
           ^hN2 -   (N+1)**2

```
> 0 votes

# Answer
## Java, 109 bytes

```
for(int i=0,c=-1,j;i<26;i++,System.out.println())for(j=0;j<1+2*i;j++)System.out.print((char)(65+(c=++c%26)));

```

Slightly ungolfed:

```
for (int i = 0, c = -1, j; i < 26; i++, System.out.println())
    for (j = 0; j < 1 + 2 * i; j++) System.out.print((char) (65 + (c = ++c % 26)));

```
> 0 votes

# Answer
# Actually, ~~18~~ 17 bytes

```
úl`╜²1╖╜²;ú*Ht`na

```

**Ungolfing:**

```
úl    Pushes 26 (the length of the lowercase alphabet).
  `     Start function
  ╜²    Push register 0 (default: 0) and square. Call this a.
  1╖    Increment register 0.
  ╜²;   Push register 0, square and duplicate. Call this b.
  ú*    b times the lowercase alphabet. Call this repeated_alphabet.
  Ht    Get repeated_alphabet[:b][a:]
  `     End function.
n     Run the above function (26) times.
a     Invert the stack.
      Print the stack implicitly with newlines.

```

Try it online!
> 0 votes

# Answer
## \>\<\>, 59 bytes

```
<v01'5'&0
+>    :@@:@$-?!v$&:d2*%'A'+o1+&1
 ^0;?=}:{:+2oa~<

```

This increments one item for each letter, another for how many letters in the current row, and checks that one to a constant to halt the program after the last line of 53 characters

Try it online
> 0 votes

# Answer
# Perl 6: 51 bytes

```
say .join for (|("A".."Z")xx*).rotor(1,3...51)[^26]

```
> 0 votes

# Answer
# Perl 6: 50 bytes

Regex based solution:

```
.put for (("A".."Z").join x 26)~~m:g/.**{1+2*$++}/

```
> 0 votes

# Answer
## Python 3, 83 bytes

```
[print("".join([chr((i%26)+97)for i in range(j*j,(j+1)*(j+1))]))for j in range(26)]

```

My first golfing experience.
> 0 votes

# Answer
## Matlab, 81 bytes

```
b=char('A'+(1:26)-1)';b=repmat(b,1,26);
for j=1:26
disp(b((j-1)*(j-1)+1:j*j))
end

```
> 0 votes

# Answer
## Racket 160 bytes

```
(let p((n 65)(t 0)(x 0))(when(> n 90)(set! n 65))(when(> x t)(set! t(+ 2 t))
(set! x 0)(displayln""))(when(< t 51)(display(integer->char n))(p(+ 1 n)t(+ 1 x))))

```

Ungolfed:

```
(define (f)
  (let loop ((n 65)
             (t 0)
             (x 0))
    (when (> n 90)
      (set! n 65))
    (when (> x t)
      (set! t (+ 2 t))
      (set! x 0)
      (displayln ""))
    (when (< t 51)
        (display (integer->char n))
        (loop (add1 n)
              t
              (add1 x)))))

```

Testing:

```
(f)

```

Output:

```
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
NOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY
ZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
JKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZA
BCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ

```
> 0 votes

# Answer
## Pip, ~~17~~ 16 bytes

15 bytes of code, +1 for `-n` flag.

```
zX26^@(1,27)**2

```

Try it online!

Explanation:

```
zX26             Lowercase alphabet, repeated 26 times
    ^@           Split at these indices:
       1,27        Range(1,27), i.e. numbers 1 through 26
      (    )**2    Square each number
                 Autoprint the resulting list, joined on newlines due to -n

```

---

My first solution is longer, but I think it's pretty cute:

```
L26P(zy,Y++++v+y)

```

Explanation:

```
L26               Loop 26 times:
      y             y is initially "", which is 0 in numeric context
       ,            Range from y to the following value:
         ++++v        v is initially -1; increment it twice (so it goes 1, 3, 5, ...)
        Y     +y      Add previous y to new v and yank result into y for next iteration
    (z          )   Use that range to get a slice from the lowercase alphabet (with
                    cyclical indexing)
   P                Print the slice (with trailing newline)

```
> 0 votes

# Answer
# Common Lisp, 139 bytes

```
(let((a"abcdefghijklmnopqrstuvwxyz"))(do((n 3(+ n 2))(i 0 j)(j 1(+ j n))(b a(format()"~a~a"b a)))((= n 55))(format t"~a~%"(subseq b i j))))

```

Try it online!
> 0 votes

# Answer
# Yabasic, 63 bytes

Long live BASIC.

```
For J=1To 51
For K=1To J
I=Mod(I,26)+1
?Chr$(64+I);
Next
?
Next

```

Try it online!
> 0 votes

# Answer
# uBASIC, 68 bytes

Anonymous function that takes no input and outputs to the console.

That pesky `Chr$(...)` function is forcing me to use `Left$(...,1)` again.

```
0ForI=1To51:ForJ=1ToI:K=KMod26+1:?Left$(Chr$(64+K),1);:NextJ:?:NextI

```

Try it online!
> 0 votes

# Answer
# Visual Basic .NET (Mono), 136 bytes

Declared `Sub`routine that takes no input and outputs to the console.

```
Module M
Sub Main
Dim I,J,K,S
For J=1To 51
S=""
For K=1To J
I=I Mod 26+1
S+=Chr$(64+I)
Next
Console.WriteLine(S)
Next
End Sub
End Module

```

Try it online!
> 0 votes

# Answer
# Vyxal `j`, 9 bytes

```
kA₅ẋ:żd‹ẇ

```

Try it Online!

## How?

```
kA₅ẋ:żd‹ẇ
kA        # Push the uppercase alphabet
  ₅       # Push the length without popping (26)
   ẋ      # Repeat it that many times
    :ż    # Duplicate and get range [1, length]
      d   # Double each
       ‹  # Decrement each
        ẇ # Split the repeated alphabet into chunks of that sizez

```
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
A26×ā·<£»

```

Try it online!

Outputs a zillion trailing newlines, but whatever.
> 0 votes

# Answer
# C#, 164 bytes

```
void a(){int i=0;Console.Write(String.Join("\n",Enumerable.Range(0,26).Select(n=>new string(Enumerable.Range(0,n*2+1).Select(m=>(char)(97+(i++)%26)).ToArray()))));}

```
> -1 votes

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


title: Build an Alphabet Pyramid

text:
# Question
Title: Build an Alphabet Pyramid
Today we're going to build a pyramid out of letters! Here's an example letter pyramid for the first 5 letters:

1. Write the first 5 letters with a space between, first ascending and then descending.

```
A B C D E D C B A

```
2. Do the same thing for the first four letters on the line above, but with two extra leading spaces:

```
  A B C D C B A
A B C D E D C B A

```
3. Repeat the same step until the last line is just 'A'

```
        A
      A B A
    A B C B A
  A B C D C B A
A B C D E D C B A

```
4. Repeat steps two and three going down instead of going up:

```
        A
      A B A
    A B C B A
  A B C D C B A
A B C D E D C B A
  A B C D C B A
    A B C B A
      A B A
        A

```

This same pattern can be extended up to 26 characters. Your challenge is to write a program or function that takes an integer as input, and produces the corresponding letter pyramid. You can choose to use uppercase or lowercase characters. You may always assume that the input will be an integer in `[1, 26]`, and the output may be any reasonable format for a 2d string. For example, a string with newlines in it, an array of characters, printing to a file, etc. Each line may have trailing spaces on it, and you may optionally output one trailing newline.

Here are some example inputs/outputs:

```
1:

A

2:

  A
A B A
  A

3:

    A
  A B A
A B C B A
  A B A
    A

5:
        A
      A B A
    A B C B A
  A B C D C B A
A B C D E D C B A
  A B C D C B A
    A B C B A
      A B A
        A

13:

                        A
                      A B A
                    A B C B A
                  A B C D C B A
                A B C D E D C B A
              A B C D E F E D C B A
            A B C D E F G F E D C B A
          A B C D E F G H G F E D C B A
        A B C D E F G H I H G F E D C B A
      A B C D E F G H I J I H G F E D C B A
    A B C D E F G H I J K J I H G F E D C B A
  A B C D E F G H I J K L K J I H G F E D C B A
A B C D E F G H I J K L M L K J I H G F E D C B A
  A B C D E F G H I J K L K J I H G F E D C B A
    A B C D E F G H I J K J I H G F E D C B A
      A B C D E F G H I J I H G F E D C B A
        A B C D E F G H I H G F E D C B A
          A B C D E F G H G F E D C B A
            A B C D E F G F E D C B A
              A B C D E F E D C B A
                A B C D E D C B A
                  A B C D C B A
                    A B C B A
                      A B A
                        A

26:

                                                  A
                                                A B A
                                              A B C B A
                                            A B C D C B A
                                          A B C D E D C B A
                                        A B C D E F E D C B A
                                      A B C D E F G F E D C B A
                                    A B C D E F G H G F E D C B A
                                  A B C D E F G H I H G F E D C B A
                                A B C D E F G H I J I H G F E D C B A
                              A B C D E F G H I J K J I H G F E D C B A
                            A B C D E F G H I J K L K J I H G F E D C B A
                          A B C D E F G H I J K L M L K J I H G F E D C B A
                        A B C D E F G H I J K L M N M L K J I H G F E D C B A
                      A B C D E F G H I J K L M N O N M L K J I H G F E D C B A
                    A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A
                  A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A
                A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A
              A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A
            A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A
          A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A
        A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A
      A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A
    A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A
  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 X W V U T S R Q P O N M L K J I H G F E D C B A
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 Y X W V U T S R Q P O N M L K J I H G F E D C B A
  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 X W V U T S R Q P O N M L K J I H G F E D C B A
    A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A
      A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A
        A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A
          A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A
            A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A
              A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A
                A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A
                  A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A
                    A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A
                      A B C D E F G H I J K L M N O N M L K J I H G F E D C B A
                        A B C D E F G H I J K L M N M L K J I H G F E D C B A
                          A B C D E F G H I J K L M L K J I H G F E D C B A
                            A B C D E F G H I J K L K J I H G F E D C B A
                              A B C D E F G H I J K J I H G F E D C B A
                                A B C D E F G H I J I H G F E D C B A
                                  A B C D E F G H I H G F E D C B A
                                    A B C D E F G H G F E D C B A
                                      A B C D E F G F E D C B A
                                        A B C D E F E D C B A
                                          A B C D E D C B A
                                            A B C D C B A
                                              A B C B A
                                                A B A
                                                  A

```

As always, this is so standard loopholes apply and the shortest answer in bytes wins!

# Answer
> 7 votes
# Python, ~~184 174~~ 169 bytes

```
R=range
def g(a):
 def f(x,y,z):
  for i in R(x,y,z):print "  "*(i-1)," ".join([chr(65+j) for j in R((a-i))]+[chr(65+(a-i-2)-j) for j in R((a-i-1))])
 f(a,0,-1);f(2,a,1)

```

**Edit:** saved 5 bytes thanks to @nedla2004

# Answer
> 6 votes
# 05AB1E, 13 bytes

Code:

```
A.ps£û€û€S».c

```

Explanation:

```
A.p             # Push all prefixes of the alphabet.
   s£           # Only get the first input elements.
     û          # Palindromize, turns ['a', 'ab', 'abc'] -> ['a', 'ab', 'abc', 'ab', 'a']
      €û        # Palindromize each, turns ['a', 'ab', 'abc', 'ab', 'a']
                  into... ['a', 'aba', 'abcba', 'aba', 'a']
        €S      # Split each element.
          »     # Gridify, joins the arrays be newlines and the arrays in the arrays
                  by spaces.
           .c   # Centralize, aligning the text to the center.

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 5 votes
# MATL, ~~25~~ 24 bytes

```
Zv&+64+G-t64>*1&!t0*hTec

```

Try it online!

Longer alternatives:

* `1Y20hiZv&+G-t0>*1&!t0*hTe)` (26 bytes)
* `Zv&+64+G-t64>*l2&Y"tZyP:o*c` (27 bytes)

### Explanation

```
         % Implicit input
Zv       % Symmetric range. For input 3 it gives [1 2 3 2 1]
&+       % Matrix of all pairwise additions. For input 3 it gives a 5×5 matrix
64+G     % Add 64 and subtract input. This gives the desired ASCII codes in the
         % central rhombus
t64>*    % Make values less than 65 equal to 0. This affects entries outside the
         % central rhombus
1&!      % Permute second and third dimensions. Transforms the 5×5 matrix into
         % a 5×1×5 array
t0*      % Push a copy of that array with all entries equal to 0
h        % Concatenate along the second dimension. Gives a 5×2×5 array
Te       % Collapse the second and third dimensions. Gives a 5×10 matrix
c        % Convert to char. Char zero is displayed as space
         % Implicit display

```

# Answer
> 4 votes
# , 45 bytes

```
i¬A[À|lDybA"Ó./&
òÄó¨á© á úe±
>>.YGp{òd

```

Try it online!

This ended up being *way* less golfy than I had hoped, so I'm not going to post an explanation yet. Hopefully I can whittle it down some more first. As usual, here is a hexdump:

```
0000000: 69ac 415b 1bc0 7c6c 4479 6241 1f12 221b  i.A[..|lDybA..".
0000010: d32e 2f26 200a f2c4 f3a8 e1a9 20e1 20fa  ../& ....... . .
0000020: 65b1 200a 3e3e 2e59 4770 7bf2 64         e. .>>.YGp{.d

```

# Answer
> 4 votes
# J, 34 bytes

```
(' ',u:65+i.26){~0>.]-[:+/~|@i:@<:

```

Takes the number as input and returns a 2D character array.

## Explanation

```
(' ',u:65+i.26){~0>.]-[:+/~|@i:@<:  input y
                                <:  y - 1
                             i:     "steps" -- i:2 -> -2 1 0 1 2
                           |        absolute value
                        +/~         addition table
                      [:            join right two tines into a conjunction
                    ]-              y - this table
                 0>.                max(0, that)
(' ',u:65+i.26)                     the alphabet preceded by a space
               {~                   index

```

## Decomposed test case

```
   n =: 5
   <: n
4
   i: <: n
_4 _3 _2 _1 0 1 2 3 4
   | i: <: n
4 3 2 1 0 1 2 3 4
   +/~ | i: <: n
8 7 6 5 4 5 6 7 8
7 6 5 4 3 4 5 6 7
6 5 4 3 2 3 4 5 6
5 4 3 2 1 2 3 4 5
4 3 2 1 0 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 3 4 5 6
7 6 5 4 3 4 5 6 7
8 7 6 5 4 5 6 7 8
   n - +/~ | i: <: n
_3 _2 _1 0 1 0 _1 _2 _3
_2 _1  0 1 2 1  0 _1 _2
_1  0  1 2 3 2  1  0 _1
 0  1  2 3 4 3  2  1  0
 1  2  3 4 5 4  3  2  1
 0  1  2 3 4 3  2  1  0
_1  0  1 2 3 2  1  0 _1
_2 _1  0 1 2 1  0 _1 _2
_3 _2 _1 0 1 0 _1 _2 _3
   0 >. n - +/~ | i: <: n
0 0 0 0 1 0 0 0 0
0 0 0 1 2 1 0 0 0
0 0 1 2 3 2 1 0 0
0 1 2 3 4 3 2 1 0
1 2 3 4 5 4 3 2 1
0 1 2 3 4 3 2 1 0
0 0 1 2 3 2 1 0 0
0 0 0 1 2 1 0 0 0
0 0 0 0 1 0 0 0 0
   u:65
A
   i.26
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
   65+i.26
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
   u:65+i.26
ABCDEFGHIJKLMNOPQRSTUVWXYZ
   ' ',u:65+i.26
 ABCDEFGHIJKLMNOPQRSTUVWXYZ
   (' ',u:65+i.26) {~ 0 >. n - +/~ | i: <: n
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA
 ABCDCBA
  ABCBA
   ABA
    A

```

Let's try this with input `5`.

## Test cases

```
   f =: (' ',u:65+i.26){~0>.]-[:+/~|@i:@<:
   f 1
A
   f 2
 A
ABA
 A
   f 3
  A
 ABA
ABCBA
 ABA
  A
   f 4
   A
  ABA
 ABCBA
ABCDCBA
 ABCBA
  ABA
   A
   f 5
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA
 ABCDCBA
  ABCBA
   ABA
    A
   f 26
                         A
                        ABA
                       ABCBA
                      ABCDCBA
                     ABCDEDCBA
                    ABCDEFEDCBA
                   ABCDEFGFEDCBA
                  ABCDEFGHGFEDCBA
                 ABCDEFGHIHGFEDCBA
                ABCDEFGHIJIHGFEDCBA
               ABCDEFGHIJKJIHGFEDCBA
              ABCDEFGHIJKLKJIHGFEDCBA
             ABCDEFGHIJKLMLKJIHGFEDCBA
            ABCDEFGHIJKLMNMLKJIHGFEDCBA
           ABCDEFGHIJKLMNONMLKJIHGFEDCBA
          ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
         ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
        ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
       ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
      ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
     ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
    ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
   ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
  ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
 ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA
 ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
  ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
   ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
    ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
     ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
      ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
       ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
        ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
         ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
          ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
           ABCDEFGHIJKLMNONMLKJIHGFEDCBA
            ABCDEFGHIJKLMNMLKJIHGFEDCBA
             ABCDEFGHIJKLMLKJIHGFEDCBA
              ABCDEFGHIJKLKJIHGFEDCBA
               ABCDEFGHIJKJIHGFEDCBA
                ABCDEFGHIJIHGFEDCBA
                 ABCDEFGHIHGFEDCBA
                  ABCDEFGHGFEDCBA
                   ABCDEFGFEDCBA
                    ABCDEFEDCBA
                     ABCDEDCBA
                      ABCDCBA
                       ABCBA
                        ABA
                         A

```

# Answer
> 4 votes
# Jelly, 13 bytes

```
RØAḣUz⁶ŒBṚŒḄG

```

**TryItOnline!**

### How?

```
RØAḣUz⁶ŒBṚŒḄG - Main link: n         e.g. 3
R             - range                     [1,2,3]
 ØA           - uppercase alphabet yield  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   ḣ          - head                      ["A","AB","ABC"]
    U         - upend (vectorises)        ["A","BA","CBA"]
     z        - transpose with filler...
      ⁶       -     space character       ["ABC"," AB","  A"]
       ŒB     - bounce (vectorises)       ["ABCBA"," ABA ","  A  "]
         Ṛ    - reverse                   ["  A  "," ABA ","ABCBA"]
          ŒḄ  - bounce (flat)             ["  A  "," ABA ","ABCBA"," ABA ","  A  "]
            G - grid format (join each with spaces and join with line feeds)
                                              A
                                            A B A
                                          A B C B A
                                            A B A
                                              A

```

# Answer
> 3 votes
# Python, ~~158~~ ~~154~~ ~~140~~ 139 bytes

```
r=range
s=int(raw_input())
a=map(chr,range(65,91))
for i in r(0,s)+r(0,s-1)[::-1]:
 print (' '.join(a[:i+1]+a[:i][::-1])).center(s*4-2,' '))

```

This is my first post so be gentle! I made heavy use of \[::-1\] to reverse strings, so maybe there's some optimization to be had there. Comments welcome.

EDITS:

Thanks @Rod for the pointer to the helpful link to the Python code golf topic and also for reminding me that the letters need spaces between them. Also thanks @wec for the general tips about removing spaces.

# Answer
> 3 votes
## Pyke, 12 bytes

```
FhGR<Q{s
)OX

```

Try it here!

Disable warnings for specified output

# Answer
> 2 votes
# C, ~~124~~ 123 bytes

Saving 1 byte thanks to Mukul Kumar

~~Currently cant get my head to transform the double loop into a single one, will leave it like this for the moment.~~ Actually, this is larger

```
for(l=0;l<4*n*(4*n+1);++l){
  i=l/(4*n+1)-2*n;
  j=l%(4*n+1)-2*n;

```

So i just let the nested loop.

```
i,j,k;f(n){for(i=-2*n-1;++i<2*n;){for(j=-2*n-1;++j<=2*n;k=abs(i/2)+abs(j/2),putchar(j-2*n?k>=n||i%2||j%2?32:65+n+~k:10));}}

```

Uses the Manhattan norm to get the diamond shape.

Ungolfed:

```
i,j,k;
f(n){
 for(i=-2*n-1;++i<2*n;){
  for(j=-2*n-1;++j<=2*n;
   k=abs(i/2)+abs(j/2),
   putchar(j-2*n?k>=n||i%2||j%2?32:65+n+~k:10)
  );
 }
}

```

# Answer
> 2 votes
## C#, ~~266~~ ~~263~~ ~~262~~ ~~261~~ ~~245~~ ~~238~~ ~~235~~ 232 bytes

Golfed:

```
List<string> F(int n){int i=0;var l=new List<string>();for(;i<n;i++){var h="";for(var c='A';c<'B'+i;c++)h+=" "+c;l.Add(new string(' ',(n-i+1)*2)+h+" "+string.Concat(h.Remove(i*2).Reverse()));}for(i-=2;i>=0;i--)l.Add(l[i]);return l;}

```

Ungolfed with comments:

```
    List<string> F(int n)
    {
        int i = 0;
        var l = new List<string>(); //collection of lines

        for (; i < n; i++)
        {
            var h = ""; //half of line

            //adding letters to first half of line
            for (var c = 'A'; c < 'B' + i; c++)
                h += " " + c;

            //adding leading spaces + half of line + reversed half of line to list
            l.Add(new string(' ', (n - i + 1)*2) + h + " " + string.Concat(h.Remove(i*2).Reverse()));
        }

        //adding lines in descending order
        for (i -= 2; i >= 0; i--)
            l.Add(l[i]);

        return l;
    }

```

Try it: http://rextester.com/WIL67940

Returns list of strings. Each string contains one output line.

I did that for fun and training. I realize that winning any of code-golf with C# is out of range.

EDIT1: Changed string interpolation to `+` operator.

EDIT2: `c <= 'A' + i` =\> `c < 'B' + i`

EDIT3: Swapped `char` with `var`.

EDIT4: Changed return type from `void` to `List`.

EDIT5: Removal of unnecessary variable.

EDIT6: New way of separating line halves.

EDIT7: @Kaspar Kjeldsen, thank you.

# Answer
> 2 votes
# Brain-Flak, 630 + 3 = 633 bytes

*This requires the `-A` flag to run*

Try it Online

```
(({})){(({}[()])<({}<({}<>)><>)<>(({}<>)<(({}[({})()])<{({}[()]<({}<(((((()()()()){}){}){}))>)>)}{}(({}<((((((()()()()){}){}){}){}()<>)<>)>)<{({}[()]<((()({}<(((((()()()()){}){}){}<>)<>)>)<>)<>)>)}{}({}<(((((()()()()){}){}){}<>)<>)>)((((()()()()){}){}){})>){(({})[()]<(({}((((()()()()){}){}){}){}<>)<>)(((((()()()()){}){}){}<>)<>)>)}{}>){({}[()]<<>(((((()()()()){}){}){}))<>>)}{}(((()()()()()){}<>)<>)>)>)}{}{}{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}((()()()()()){})<>{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}{{}({}[(()()()()()){}])}{}([]){{}({}<>)<>([])}{}<>

```

This is not a great golf but this challenge is quite difficult in Brain-Flak

# Answer
> 1 votes
# Pyth, 23 bytes

```
V+SQt_SQp*dy-QNt_pjd<GN

```

Try it online

# Answer
> 1 votes
# Ruby, ~~137 115 100~~ 84 bytes

```
->n{e=->s{s+s.reverse[1..-1]};e[(0..n-1).map{|i|"  "*(n-i)+e[[*?A..?Z][0..i]*' ']}]}

```

Thanks to manatwork for the comments.

# Answer
> 1 votes
# TSQL, ~~261~~ 236 bytes

```
DECLARE @i INT =5;

WITH C as(SELECT number z,abs(@i+~number)f
FROM spt_values WHERE'P'=type)SELECT
top(@i*2-1)space(f*2)+v+stuff(reverse(v),1,3,'')FROM(SELECT*,(SELECT
top(@i-f)char(65+z)+' 'FROM c
for xml path(''),type).value('.','varchar(52)')v FROM c)d

```

**Fiddle**

# Answer
> 1 votes
# Befunge 93, 175 bytes

Try it online!

Probably not very well golfed. Oh well. This was hard enough with befunge:

```
&:00p"B"\- :13v
v,: _v#`"@"<p5<
v," "<v`+*9<
>" ",: 35g7^
v47"v"_>1+ v
>p#  0^:>- v
v"A"g53<1v<
>+00g-` |53
v">",+91<p+
>74p35g:v11
_v# -g00<+^ _@#:
1>59*:91v> v
^p+199p8>#+ <

```

Good luck figuring out how it works! I barely know.

# Answer
> 1 votes
## C#, 199 bytes

```
q=>{Action<int>L=x=>{var s="";var k=0;for(;k<x;)s+=(char)('A'+k++)+" ";for(--k;--k>=0;)s+=(char)('A'+k)+" ";Console.WriteLine(new string(' ',(q-x)*2)+s);};var i=0;for(;i<q;)L(++i);for(;i>1;)L(--i);};

```

As always, C# is not much of a golfing language, but I prefer "readable" code much more than esoteric Code. Also I just did this for fun :)

Here's an ungolfed version, so you can easily understand what I did:

```
Action<int> C = q =>
{
    Action<int> L = x =>
    {
        var s = "";
        var k = 0;
        for (; k < x;)
            s += (char)('A' + k++) + " ";
        for (--k; --k >= 0;)
            s += (char)('A' + k) + " ";
        Console.WriteLine(new string(' ', (q - x) * 2) + s);
    };
    var i = 0;
    for (; i < q;)
        L(++i);
    for (; i > 1;)
        L(--i);
};

```

(I think this could be optimized a lot though..)

# Answer
> 1 votes
## Java, 213 bytes

```
void p(int n){int i=1,s=1,f,c;while(i>0){f=(n+1-i)*2;System.out.printf("%"+f+"s","");c=65;for(;c<64+i;)System.out.printf("%c ",c++);for(;c>64;)System.out.printf("%c ",c--);System.out.println();if(i==n)s=-1;i+=s;}}

```

Ungolfed:

```
void p(int n) {
    int i = 1, s = 1, f, c;
    while (i > 0) {
        f = (n + 1 - i) * 2;
        System.out.printf("%" + f + "s", "");
        c = 65;
        for (; c < 64 + i; ) System.out.printf("%c ", c++);
        for (; c > 64; ) System.out.printf("%c ", c--);
        System.out.println();
        if (i == n) s = -1;
        i += s;
    }
}

```

# Answer
> 1 votes
## Batch, 269 bytes

```
@echo off
set/an=%1-1
set a=ABCDEFGHIJKLMNOPQRSTUVWXYZ
for /l %%i in (-%n%,1,%n%)do set i=%%i&call:l
exit/b
:l
set s=
for /l %%j in (-%n%,1,%n%)do set j=%%j&call:c
echo%s%
exit/b
:c
set/aj=n-%i:-=%-%j:-=%
call set s= %%a:~%j%,1%%%s%

```

Line 2 ends in 25 spaces; this means that when the alphabet index goes negative those squares simply remain blank.

# Answer
> 0 votes
# Java, 394 Bytes

*I normally do C#, but it's good to mix it up...*

Golfed:

```
String P(int n){String a="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="",k="",s="";int i=0,j=0,l=0;java.util.List<String>b=new java.util.ArrayList<String>();for(i=1;i<=n;i++){k="";s=a.substring(0,i);l=s.length();for(j=0;j<l;j++)k+=s.toCharArray()[j]+" ";while(k.length()<n+n)k=" "+k;if(i>1)for(j=l-2;j>=0;j--)k+=s.toCharArray()[j]+" ";k+="\r\n";b.add(k);o+=k;}for(i=b.size()-2;i>=0;i--)o+=b.get(i);return o;}

```

Ungolfed:

```
public String P(int n)
{
    String a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", o ="", k="",s="";
    int i =0, j=0, l=0;
    java.util.List<String> b = new java.util.ArrayList<String>();
    for (i = 1; i <= n; i++) {
        k = "";
        s = a.substring(0, i);
        l = s.length();

        for (j = 0; j < l; j++)
            k += s.toCharArray()[j] + " ";

        while(k.length() < n + n)
            k= " " + k;

        if(i > 1)
            for (j = l-2; j >= 0; j--)
                k += s.toCharArray()[j] + " ";

        k += "\r\n";
        b.add(k);
        o += k;
     }

    for (i = b.size()-2; i >= 0; i--)
        o += b.get(i);

    return o;
}

```

Test:

```
BuildAnAlphabetPyramid b = new BuildAnAlphabetPyramid();
System.out.println(b.P(5));
System.out.println(b.P(26));

        A
      A B A
    A B C B A
  A B C D C B A
A B C D E D C B A
  A B C D C B A
    A B C B A
      A B A
        A

                                                  A
                                                A B A
                                              A B C B A
                                            A B C D C B A
                                          A B C D E D C B A
                                        A B C D E F E D C B A
                                      A B C D E F G F E D C B A
                                    A B C D E F G H G F E D C B A
                                  A B C D E F G H I H G F E D C B A
                                A B C D E F G H I J I H G F E D C B A
                              A B C D E F G H I J K J I H G F E D C B A
                            A B C D E F G H I J K L K J I H G F E D C B A
                          A B C D E F G H I J K L M L K J I H G F E D C B A
                        A B C D E F G H I J K L M N M L K J I H G F E D C B A
                      A B C D E F G H I J K L M N O N M L K J I H G F E D C B A
                    A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A
                  A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A
                A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A
              A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A
            A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A
          A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A
        A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A
      A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A
    A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A
  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 X W V U T S R Q P O N M L K J I H G F E D C B A
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 Y X W V U T S R Q P O N M L K J I H G F E D C B A
  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 X W V U T S R Q P O N M L K J I H G F E D C B A
    A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A
      A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A
        A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A
          A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A
            A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A
              A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A
                A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A
                  A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A
                    A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A
                      A B C D E F G H I J K L M N O N M L K J I H G F E D C B A
                        A B C D E F G H I J K L M N M L K J I H G F E D C B A
                          A B C D E F G H I J K L M L K J I H G F E D C B A
                            A B C D E F G H I J K L K J I H G F E D C B A
                              A B C D E F G H I J K J I H G F E D C B A
                                A B C D E F G H I J I H G F E D C B A
                                  A B C D E F G H I H G F E D C B A
                                    A B C D E F G H G F E D C B A
                                      A B C D E F G F E D C B A
                                        A B C D E F E D C B A
                                          A B C D E D C B A
                                            A B C D C B A
                                              A B C B A
                                                A B A
                                                  A

```

# Answer
> 0 votes
# R, ~~100~~ ~~97~~ 87 bytes

```
x=scan();z=LETTERS;for(i in c(1:x,x:2-1))cat(rep(" ",x-i+1),z[1:i],if(i>1)z[i:2-1],"\n")

4:
#>         A
#>       A B A
#>     A B C B A
#>   A B C D C B A
#>     A B C B A
#>       A B A
#>         A

```

( Update: `scan()` for input; abused (x-1):1 == x:2-1. )

Not too shabby for one of the keyword languages by the looks of it (those special-character ones are always going to be better).

# Answer
> 0 votes
# PHP, ~~122~~ 116 bytes

```
for($i=1-$n=$argv[1];$i<$n;)echo str_pad("",$a=abs($i++)),$s=join(range(A,chr(64+$n-$a))),substr(strrev($s),1),"\n";

```

is there a shorter way?

# Answer
> 0 votes
## JavaScript (ES6), 121 bytes

```
n=>[...Array(n+n--)].map((_,i,a)=>a.map((_,j)=>(j=10+n-g(i)-g(j))>9?(10-j).toString(36):` `,g=i=>i<n?n-i:i-n).join` `).join`\n`

```

Where `\n` represents the literal newline character. Outputs in lower case.

# Answer
> 0 votes
# Perl 5 \+ `-pa -M5.10.0`, 79 bytes

```
@A=A..Z;$\=$s.$/.$\,say$s="  "x--$F[0]."@A[0..--$_,reverse 0..--$_]"for 1..$_}{
```

Try it online!

---

# Perl 5 \+ `-pl`, 88 bytes

A slightly longer approach, but utilises ANSI escape codes and draws the letters in a spiral, starting with 9 o'clock, moving clockwise.

```
$l=A;$\x=($_-1);//,(map$\.="$l$_"x$',".[A ",". ","....","..[A.."),$\.=$l++.$"while$_--}{
```

Try it online!

# Answer
> 0 votes
# Canvas, 8 bytes

```
Ｚｍ［］／ ＊┼

```

Try it here!

##### Explanation:

```
Zm[]/ *+ | Full code (chars replaced with ASCII alternatives for monospace)
---------+---------------------------------------------------------------------
Z        | Push uppercase alphabet
 m       | Mold to length (i.e. first <input> chars)
  []     | Prefixes
    /    | Antidiagonal (put spaces before each line/entry)
     _*  | Put a space between each character (space underlined for visibility)
       + | Quad-palindromize with 1 overlap

```

# Answer
> 0 votes
# Vyxal `C`, 8 bytes

```
kA¦Ẏ∞ʁvṄ

```

Try it Online!

## How?

```
kA¦Ẏ∞ʁvṄ
kA       # Push the uppercase alphabet
  ¦      # Prefixes
   Ẏ     # Get the first input items
    ∞    # Palindromise this list
     ʁ   # Palindromise each in this list
      vṄ # Join each on spaces
         # C flag centers and joins on newlines

```

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