title: Make an alphabet searchlight!

text:
# Question
Title: Make an alphabet searchlight!
Inspired by a bug in a solution to this challenge, your challenge is to produce this exact text:

```
                         ZYXWVUTSRQPONMLKJIHGFEDCBA
                        YXWVUTSRQPONMLKJIHGFEDCBA
                       XWVUTSRQPONMLKJIHGFEDCBA
                      WVUTSRQPONMLKJIHGFEDCBA
                     VUTSRQPONMLKJIHGFEDCBA
                    UTSRQPONMLKJIHGFEDCBA
                   TSRQPONMLKJIHGFEDCBA
                  SRQPONMLKJIHGFEDCBA
                 RQPONMLKJIHGFEDCBA
                QPONMLKJIHGFEDCBA
               PONMLKJIHGFEDCBA
              ONMLKJIHGFEDCBA
             NMLKJIHGFEDCBA
            MLKJIHGFEDCBA
           LKJIHGFEDCBA
          KJIHGFEDCBA
         JIHGFEDCBA
        IHGFEDCBA
       HGFEDCBA
      GFEDCBA
     FEDCBA
    EDCBA
   DCBA
  CBA
 BA
A

```
* The first line will have 25 spaces, then the alphabet backwards starting from the 26th letter (`ZYXWVUTSRQPONMLKJIHGFEDCBA`), then a newline.
* The second line will have 24 spaces, then the alphabet backwards starting from the 25th letter (`YXWVUTSRQPONMLKJIHGFEDCBA`), then a newline.
* ...
* The last (26th) line will have no spaces, then the alphabet backwards starting from the 1st letter (`A`), then a newline.

Additional rules:

* Your program may use any allowed output methods.
* One trailing newline and/or one leading newline is allowed.
* There must be one newline between lines containing the letters, no more.
* The letters must be all uppercase.

As with , the shortest submission wins. Good luck!

Leaderboard:

```
var QUESTION_ID=141725,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# 05AB1E, 7 bytes

### Code:

```
₂žp.s1Λ

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
 žp.s      # Get the suffixes of ZYX...CBA
      Λ    # Using the canvas mode, print the
₂          # first 26 elements of the array
     1     # into the upper-right direction

```
> 20 votes

# Answer
# , ~~67~~ 55 bytes

```
for(i in 26:1)cat(rep(" ",i-1),LETTERS[i:1],"
",sep="")

```

Try it online!
> 22 votes

# Answer
# Python 2, 57 bytes

```
i=26
while i:i-=1;print' '*i+bytearray(range(65+i,64,-1))

```

Try it online!
> 17 votes

# Answer
# , ~~13~~, 11 bytes

```
¬ZAòY>HGpxl

```

Try it online!

Hexdump:

```
00000000: ac5a 41f2 593e 4847 7078 6c              .ZA.Y>HGpxl

```

Written from my phone :P.

```
¬ZA         " Insert the alphabet backwards
   ò        " Recursively:
    Y       "   Yank this current line
     >H     "   Add one space to every line
       G    "   Move to the last line in the buffer
        p   "   Paste the line we yanked
         x  "   Delete one character
          l "   Move one character to the right, which will throw an error on
            "   the last time through, breaking the loop

```
> 16 votes

# Answer
# PowerShell, 42 bytes

```
25..0|%{' '*$_+-join[char[]]((65+$_)..65)}

```

Try it online!

### Explanation:

```
25..0|%{                                 } # Loop from 25 to 0
                             (65+$_)..65   # Construct a range of the specific ASCII codes
                    [char[]](           )  # Cast that as a character array
               -join                       # that has been joined together into a string
        ' '*$_+                            # Prepended with the correct amount of spaces

```
> 13 votes

# Answer
# Bash + GNU sed, 60

```
printf %s {Z..A}|sed 'h
s/./ /g
G
s/ \n//
:x
p
s/ \S//
tx
d'

```

Try it online.
> 11 votes

# Answer
# ///, ~~105~~ 97 bytes

```
/:/\\\\*//#/: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//\\*/\/\/_____#
\/ //_/     //*#

```

Try it online!

### Explanation

/// only knows one command, `/<pattern>/<substitution>/<text>` replaces all occurrences of `<pattern>` in `<text>` with `<substitution>`. Additionally `\` can be used to escape characters.

Shortened code for simplicity:

```
/:/\\\\*//#/:E:D:C:B:A//\\*/\/\/__#
\/ //_/  //*#

```

The first command `/:/\\\\*/` replaces `:` with `\\*` in the subsequent code. This gives:

```
/#/\\*E\\*D\\*C\\*B\\*A//\\*/\/\/__#
\/ //_/  //*#

```

Then `/#/\\*E\\*D\\*C\\*B\\*A/` replaces `#` with `\*E\*D\*C\*B\*A`:

```
/\\*/\/\/__\*E\*D\*C\*B\*A
\/ //_/  //*\*E\*D\*C\*B\*A

```

Then `/\\*/\/\/__\*E\*D\*C\*B\*A<newline>\/ /` replaces `\*` with `//__*E*D*C*B*A<newline>/`:

```
/_/  //*//__*E*D*C*B*A
/ E//__*E*D*C*B*A
/ D//__*E*D*C*B*A
/ C//__*E*D*C*B*A
/ B//__*E*D*C*B*A
/ A

```

Notice: I had to use `\*` for replacement. Since `*` is also part of the substitution, it would generate an infinite loop if I only replace `*`.

Then command `/_/ /` replaces `_` with spaces, and `/*//` deletes all `*`:

```
EDCBA
/ E//    EDCBA
/ D//    EDCBA
/ C//    EDCBA
/ B//    EDCBA
/ A

```

The next command `/#//` replaces `#` by nothing. Since there is no `#` in the code, it does nothing. This is just here to remove the two leadings `//` from the beginning of the code. This leaves

```
EDCBA
/ E//    EDCBA
/ D//    EDCBA
/ C//    EDCBA
/ B//    EDCBA
/

```

Then the command `/ E//` removes `<space>E`, so this will leave the code

```
    EDCBA
   DCBA
/ D//   DCBA
/ C//   DCBA
/ B//   DCBA
/

```

Similar `/ D//` removes `<space>D`:

```
    EDCBA
   DCBA
  CBA
/ C//  CBA
/ B//  CBA
/

```

`/ C//`:

```
    EDCBA
   DCBA
  CBA
 BA
/ B// BA
/

```

`/ B//`:

```
    EDCBA
   DCBA
  CBA
 BA
A
/

```

And the last command is incomplete, so it does nothing:

```
    EDCBA
   DCBA
  CBA
 BA
A

```
> 10 votes

# Answer
## Haskell, ~~53~~ 52 bytes

```
f(a:b)=(b>>" ")++a:b++'\n':f b
f x=x
f['Z','Y'..'A']

```

Try it online!

How it works

```
f['Z','Y'..'A']        -- call f with the full backwards alphabet

f(a:b)=                -- let `a` be the first char and `b` the rest. Return
   (b>>" ") ++         -- replace each char in b with a space, followed by
   a:b ++              -- the input string, followed by
   '\n' :              -- a newline, followed by
   f b                 -- a recursive call of `f` with `b`
f x=x                  -- stop on an empty input string

```
> 9 votes

# Answer
# JavaScript (ES6), ~~83~~ ~~77~~ 76 bytes

```
f=(n=0,p='')=>n<26?f(++n,p+' ')+p+`ZYXWVUTSRQPONMLKJIHGFEDCBA
`.slice(~n):''

o.innerText = f()
```

```
<pre id=o>
```
> 8 votes

# Answer
# Python 2, ~~66~~ 64

```
i=26
while i:i-=1;print' '*i+'ZYXWVUTSRQPONMLKJIHGFEDCBA'[25-i:]

```

Try it online!
> 8 votes

# Answer
# Jelly, 12 bytes

```
ØAµ⁶ṁḊ;ṚµƤṚY

```

Try it online!

```
ØAµ⁶ṁḊ;ṚµƤṚY  Main Link
ØA            "ABC...XYZ"
         Ƥ    For each prefix,
  µ⁶ṁḊ;Ṛµ     Monadic Link
   ⁶          ' '
    ṁ         (with automatic repetition) molded to the shape of
     Ḋ        All but the first letter of the input (repeat - 1)
      ;       With the input          appended to it
       Ṛ                     reversed
           Y  Join on newlines
          Ṛ   Flip upside down

```

-3 bytes thanks to miles
> 7 votes

# Answer
# brainfuck, 105 bytes

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

```

Try it online!

Minified and formatted:

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

```

Readable version:

```
[
  pre-initialize the tape with the values 10 90 32 >26<
  C_NEWLINE: 10
  V_ALPHA: 90
  C_SPACE: 32
  V_COUNTER: 26

AS:

  10 = 8 *  1 + 2
  90 = 8 * 11 + 2
  32 = 8 *  4 + 0
  26 = 8 *  3 + 2
]

8 ++++++++ [
  *  1 >+
  * 11 >+++++++++++
  *  4 >++++
  *  3 >+++
<<<<-]
PLUS 2 >++
PLUS 2 >++
PLUS 0 >
PLUS 2 >++

UNTIL V_COUNTER == 0 [
  COPY V_COUNTER to RIGHT and RIGHT_RIGHT
  [->+>+<<]
  TAPE: 10 V_ALPHA 32 >0< V_COUNTER_R V_COUNTER_RR
  V_COUNTER_R SUB 1 TIMES: >-[-
     PRINT C_SPACE <<.
  >>]
  TAPE: 10 V_ALPHA 32 0 >0< V_COUNTER_RR
  V_COUNTER_RR TIMES: >[-
    PRINT V_ALPHA <<<<.
    DECREMENT V_ALPHA -
    INCREMENT V_COUNTER_R >>>+
  >]
  TAPE: 10 V_ALPHA 32 0 V_COUNTER_R(26) >0<
  V_COUNTER_R SUB 1 TIMES: <-[-
    INCREMENT V_COUNTER <+
    INCREMENT V_ALPHA <<+
  >>>]
  PRINT C_NEWLINE <<<<.
>>>]

```
> 7 votes

# Answer
# Poetic, 601 bytes

```
one night i camped a bit
throughout all the forest now
the sweet sights
i saw giant things
i saw little small things
here i am
seated around all my trees i saw
i sleep
i sle-e-p
sleep in a cabin
i am sleep-y
i sleep a bit
i awaken in bed
i stand
i walk
i am ready
i saw a vision of a dragon
i am fooled
i know i am
should i f-ight
i f-light
i did f-light
i did a flight
go away,i do imply
i*m afraid
i run
i leave
i flee
i am timid
i*m just a person,not toughie-tough-guy
no,never
i*m waste
i am stupid
a quitter i was
i am stupid
i*m turning around
i do not appreciate camping
i cry
i am crying
no
no

```

Poetic is an esolang I created in 2018 for a class project, and it is a brainfuck derivative in which the lengths of words correspond to brainfuck commands (and the +, -, \>, and \< commands each have 1-digit arguments).

The fact that only word-length dictates the commands means that I technically could have created a program entirely composed of non-words (i.e. the letter X as many times as needed, with spaces in between words), but I wanted to make an interesting free-verse poem out of it while not adding any unnecessary bytes.

If you want to try it online (which is half the point of the class project in the first place), check out my online interpreter!
> 7 votes

# Answer
# Octave, ~~53~~ ~~49~~ ~~46~~ 45 bytes

*1 byte removed thanks to @Sanchises*

```
for k=25:-1:0,disp([blanks(k) 65+k:-1:65])end

```

Try it online!
> 6 votes

# Answer
# 05AB1E, 10 bytes

```
žpDvÐg<ú,¦

```

Try it online!

**Explanations:**

```
žpDvÐg<ú,¦
žp           Push the uppercased alphabet, reversed
  D          Duplicate
   v         For each letter (we just want to loop 26 times, so we use the
                already pushed alphabet for that purpose)
    Ð        Triplicate
     g<      Length of the string - 1
       ú     Add that number of spaces at the beginning of the string
        ,    Print with newline
         ¦   Remove the 1st element of the remaining copy of the string

```
> 5 votes

# Answer
# Perl 6, 37 bytes

*Saved 9 bytes thanks to @Massa.*

```
say " "x$_,chrs $_+65...65 for 25...0

```

Try it online!

**Explanation:** `25...0` is a range from 25 to 0 (as expected). We iterate over that range, saying (= printing with newline) that many spaces and the string of characters that have ASCII codes (`chrs`) from 65 + that number (`$_+65...65`).
> 5 votes

# Answer
# Vim, 43 keystrokes

```
:h<_<CR>jjYZZPVgUxjpqqy$-i <Esc>lpl"aDYPD"ap+q25@q

```

You can see it in action in this GIF made using Lynn's python script
> 5 votes

# Answer
# Charcoal, ~~19~~ 11 bytes

*-8 bytes thanks to ASCII-only.*

```
Ｆ²⁶«Ｐ⮌…α⊕ι↗

```

Try it online! Link is to verbose version.
> 4 votes

# Answer
# Cubix, 43 ~~46~~ bytes

```
$/\;u:\s/':(!$u;:'@^!@Wu;oSU;o+<u(;;oN;(!|

```

Try it online!

Cubified

```
      $ / \
      ; u :
      \ s /
'  : ( ! $ u ; : ' @ ^
! @ W u ; o S U ; o + <
u ( ; ; o N ; ( ! | . .
      . . .
      . . .
      . . .

```

Watch it run

Have managed to shave a few more of this, but it was a bit more difficult than I thought. There is a substitute character after the first quote to give me 26.

* `'<sub>` push 26 onto the stack as the base number
* `:(!` duplicate base as a counter, decrement, test for truthy
* `u` on true skip the `$` command and u-turn to the right
    + `So;u` push 32, output as character, pop 32 and u-turn right onto the decrement
* `$` on false jump the next `u` command
* `;:'@^` pop, duplicate the base number, push 64 onto stack and redirect into a torturous route
* `$\s/:\/u;$` this is the order of the steps on the top face. It boils down to swap the counter with the 64. Ends with a skip over the redirect that put it here.
* `<+o;U` redirect to add, output character, pop, u-turn left
* `(!` decrement, test for truthy. If true starts on a path which hits the u-turn and goes back to the redirect.
* `|(;No` on false, reflect, redundant test, redundant decrement, pop, push 10 and output character
* `;;(u!@W` pop down to the base number, decrement, u-turn right onto truthy test, halt if false otherwise change lane onto the duplicate at the beginning. Rinse and repeat.
> 4 votes

# Answer
# Perl 5 \+ `-p`, 37 bytes

```
}{$\=$"x$-++.($a=$_.$a).$/.$\for A..Z

```

## Explanation

Since `-p` is being used with no input, the leading `}{` is to break out of the implicit `while(<STDIN>){` that's added. This builds the string, in reverse, into `$\` which is implicitly output after any content that is `print`ed. `for` each char in `A..Z`, `$\` is set to `$-` (which starts as `0` and is post-incremented for the next loop) `$"`s (which is the record separator and is initialised to space) to indent the string, concatenated with `$a` (which is prepended with `$_`, the current letter from the `for` loop), followed by `$/` (the line terminator, defaults to `"\n"`) and the existing contents of `$\`.

Try it online!

---

# Perl 5 \+ `-M5.10.0`, 37 bytes

```
$#@-=say$"x$#@,reverse@@for\(@@=A..Z)

```

## Explanation

This approach outputs the string in order directly. `for` each char in the reference (`\(...)`) to `@@` (which is set to `A..Z`), this runs the loop once for each letter, `@@`'s final index is decremented by the result of outputting (`say`, includes a final newline) `$"` (space) 'the final index of `@@` times', followed by the `reverse` of `@@`. Using the return from `say` as the decrement means that the output happens before the final index is removed avoiding the need to add another entry to the list. So in the first iteration this outputs 25 spaces and `Z` to `A`, then 24 spaces and `Y` to `A` ... then 1 space and `BA` and 0 spaces and `A`.

I feel like it should be possible to remove some syntax here. I played around with a way to define a list that shrinks but doesn't stop the loop halfway through and the `\(...)` seems to do just that, whereas `[...]` is seen as one list entry instead. Also trying to find a non-word character that works with the `$#_` notation was trickier than I'd hoped, `@;` \- my usual go-to results in evaluation of `$#` (which is removed).

Try it online!
> 4 votes

# Answer
# Ruby, 54 52 bytes

```
25.downto 0{|n|puts' '*n+[*?A..?Z][0..n].reverse*''}

```

Try it online!
> 4 votes

# Answer
# Python, 83 bytes

```
[print(' '*i+''.join([chr(64+i)for i in range(i+1,0,-1)]))for i in range(25,-1,-1)]

```

My first answer on codegolf :)
> 4 votes

# Answer
# sed 4.2.2 \+ Bash, 50 bytes

```
s/^/printf %25s;printf %s {Z..A}/e
:
p
s/ \S//
t
d

```

Try it online!

---

# Bash \+ sed 4.2.2, 51 bytes

```
printf %s {Z..A}|sed 'h
s/./ /g
G
:
s/ [^ ]//p
t
d'

```

Building on @DigitalTrauma's answer.

Try it online!
> 4 votes

# Answer
# SOGL V0.12, ~~10~~ 8 bytes

```
Z±{Xf}⁰¼

```

Try it Here!
> 3 votes

# Answer
# Perl 5, 49 bytes

```
$_=$"x26 .join'',reverse A..Z,Z;say while s/ \S//

```

Try it online!
> 3 votes

# Answer
# JavaScript, ~~75~~ 74 bytes

*1 byte saved thanks to Rick Hitchcock*

```
f=(a=65,b='',c)=>a>90?'':f(a+1,b+' ',c=String.fromCharCode(a)+[c])+`
`+b+c

```

Try it online!
> 3 votes

# Answer
# Common Lisp, ~~84~~ 82 bytes

```
(dotimes(i 26)(format t"~v@{ ~}~a
"(- 25 i)(subseq"ZYXWVUTSRQPONMLKJIHGFEDCBA"i)))

```

Try it online!

Two bytes less thanks to @Ascii-only!
> 3 votes

# Answer
# PHP (63 58 55 bytes)

This is possibly my favorite strange corner of PHP, a corner which it inherits from Perl:

```
for($c=A;$c!=AA;$q="$s$z
$q",$s.=" ")$z=$c++.$z;echo$q;

```

This outputs the trailing newline, as explicitly permitted. This can be run in `php -r` to save the opening `<?php` needed to put this in a file.

Explanation: when a variable containing the string `'A'` is incremented in PHP, it becomes `'B'` and then `'C'` and so on up until `'Z'` becomes `'AA'`. There is no digit before `'A'` to start with in this madcap algebra, and the decrement operator does not undo it, so we save the incrementally reversed alphabet to `$z` (which defaults to `NULL` which when it gets concatenated with a string behaves like the empty string -- the same happens with `$s` and `$q`). Whitespace is accumulated in `$s` and the whole string is accumulated backwards in variable `$q` which means we have to echo it at the end.

Thanks to Titus for golfing off my curly braces and telling me that I don't need to take a penalty for inline-evaluation flags like `-r`.
> 3 votes

# Answer
# Pyke, 8 bytes

```
G_.<XFo}h-

```

Try it here!

```
           -  o = 0
G_         -    reversed(alphabet)
  .<       -   suffixes(^)
    XF     -  for i in ^:
      o    -      o++
       }   -     ^ * 2
        h  -    ^ + 1
         - -   i.lpad(" ", ^)
           - for i in reversed(^):
           -  print i

```

I can see the right language doing this in 6 bytes if they had a builtin for `prepend n spaces to string` as well as what Pyke does
> 3 votes

# Answer
# Python 3, 71 69 bytes

```
for i in range(26):print(' '*(25-i)+'ZYXWVUTSRQPONMLKJIHGFEDCBA'[i:])

```

Try it online!
> 3 votes

# Answer
# Python 2, ~~72~~ 67 bytes

```
i=26
while-~i:print' '*i+''.join(map(chr,range(65,91)))[i::-1];i-=1

```

Try it online!
> 2 votes

# Answer
# Bubblegum, 85 bytes

Hexdump:

```
0000000: 53c0 05a2 2223 c2c3 4243 8283 0203 fcfd  S..."#..BC......
0000010: 7c7d bcbd 3c3d dcdd 5c5d 9c9d 1cb9 7069  |}..<=..\]....pi
0000020: 2159 0789 ea49 524d 825a a255 12a9 8e28  !Y...IRM.Z.U...(
0000030: 5544 a821 a882 803c 5e59 3c72 3865 7088  UD.!...<^Y<r8ep.
0000040: 6315 c522 8621 82c6 47e1 21b1 e12c 280d  c..".!..G.!..,(.
0000050: 2681 d811 00                             &....

```

Try it online!
> 2 votes

# Answer
# Mathematica, ~~79~~ 73 bytes

```
Column@(T=Table)[T[" ",26-i]<>ToUpperCase@Alphabet[][[-i;;1;;-1]],{i,26}]

```

or without `Alphabet`

# Mathematica, ~~75~~ 66 bytes

```
Column@Array[Table[" ",26-#]<>Reverse@CharacterRange[65,91-#]&,26]

```

*thanks @JungHwanMin for golfing more both of my answers*
> 2 votes

# Answer
# K (oK), ~~31~~ 27 bytes

**Solution:**

```
{`c$(x#32),65+|!x+1}@/:|!26

```

Try it online!

**Explanation:**

Iterate over the list of `25..0`, each iteration create the reverse alphabet joined with x many spaces:

```
{`c$(x#32),65+|!x+1}@/:|!26 / solution
                        !26 / til 26 (0..25)
                       |    / reverse (25..0)
                    @/:     / each (25, 24, 23...)
{                  }        / lambda function
                x+1         / increment x (25->26)
               !            / til x (0..26)
              |             / reverse
           65+              / add 65, 0+65 = ASCII "A"
          ,                 / join
    (x#32)                  / x take 32 (e.g 32, x many times)
 `c$                        / cast everything to characters

```
> 2 votes

# Answer
## C++, ~~146~~ ~~142~~ ~~141~~ ~~140~~ ~~137~~ 133 bytes

-4 bytes thanks to MD XF

-4 bytes thanks to Zacharý

```
#include<iostream>
#define F for(i=26-g;i;--i)std::cout<<
void f(){for(int g=1,i;g<27;g+=2){F ' ';--g;F char(64+i);std::cout<<'\n';}}

```
> 2 votes

# Answer
# Tcl, 140 bytes

Still very ungolfed, will do it later!

```
set n 26;time {set c $n;append s [string repe \  $n];incr n -1;time {append s [format %c [expr 65+[incr c -1]]]} $c; append s \n} 26;puts $s

```

Try it online!

---

~~Tcl, 142 bytes
```
set n 26;while \$n {set c $n;append s [string repe \  $n];incr n -1;time {append s [format %c [expr 65+[incr c -1]]]} $c; append s \n};puts $s

```
Try it online!<br>~~
> 2 votes

# Answer
# SimpleTemplate, 102 bytes

This is just a very straight-forward implementation, nothing fancy.

```
{@setV 25}{@forfrom"Z"to"A"}{@callstr_repeat intoX" ",V}{@callrange intoZ _,"A"}{@echolX,Z}{@incby-1V}

```

Try it on http://sandbox.onlinephpfunctions.com/code/a31f7d1b8532385cc135cc1bf64e05d702ebcce4

---

**Ungolded:**

```
{@set spaces 25}
{@for i from "Z" to "A"}
    {@call str_repeat into padding " ", spaces}
    {@call range into letters i, "A"}
    {@echo EOL, padding, letters}
    {@inc by -1 spaces}
{@/}

```

Should be almost self-explainatory
> 2 votes

# Answer
# CJam, 25 bytes

Fixed. Thanks to Martin Ender for the help fixing it!

```
'[,65>W%_,,_Sf*W%\@f>.+N*

```

Try it online!

Explanation:

```
'[,65>W%_,,_Sf*W%\@f>.+N*
'[,65>                     e# From the cjam golfing tips, generate A-Z
      W%                   e# Reverse the array: Z-A
        _,                 e# Take the size of that range (so, 26)
          ,                e# Make a range 0..25
           _               e# Dupe that range
              f*           e# For each value of that range
             S             e# Repeat a space that amount of times
                W%         e# Reverse this list of strings
                  \        e# Swap the top and the second elements of the stack
                   @       e# Brings the first stack el. to the top
                    f>     e# For each value in that range, remove N elements from the alphabet (generate ZYX..., until, CBA, BA, A).
                      .+   e# Vectorized append (appends space with the alphabet chunks)
                        N* e# Join with newline

```
> 2 votes

# Answer
# AWK, 76 bytes

```
{for(;++j<27;)printf"%"53-2*j"s\n",substr("ZYXWVUTSRQPONMLKJIHGFEDCBA",++z)}

```

Try it online!

Tried 3-4 different versions, including double `for` loop, this is the fewest bytes I could come up with.

Not sure if I should add 1 byte since it does require some input to produce output.
> 2 votes

# Answer
# vim, 46 bytes

```
:set nf=alpha
25a <ESC>aZ<ESC>qaylp<CTRL+X>q24@aqayyphxxq24@a

```

**Ungolfed:**

```
:set nf=alpha    " add letters to the set of number formats used by CTRL+A, CTRL+X
25a <ESC>aZ<ESC> " add the leading spaces and the Z
qaylp<CTRL+X>q   " record macro to copy and decrement the last letter, and
24@a             " run 24 times
qayyphxxq        " record macro to copy/paste the last line, and delete the last space and first letter.
24@a             " run 24 times.

```

`<ESC>` and `<CTRL+X>` are 0x1B and 0x18 respectively.

Try it online!
> 2 votes

# Answer
# Ruby, 60 bytes

I couldn't beat @Snack's answer, but here are some solutions that I found interesting:

```
25.downto 0{|i|$><<" "*i;i.downto 0{|e|$><<(65+e).chr};puts}

```

Try it online!

I'm also particularly entertained by calculating the spaces this way and was saddened that it wasn't shorter:

```
z="";(?A..?Z).each{|e| (?A..e).each{|k| z+=k}; z+=" "*(z.size**0.5-1)+?\n};puts z.reverse

```

At least it's the only answer that uses a square root!
> 2 votes

# Answer
# Java (OpenJDK 8), 105 bytes

```
z->{for(int i=0;i<26;)System.out.printf("%"+(51-i*2)+"s%n","ZYXWVUTSRQPONMLKJIHGFEDCBA".substring(i++));}

```

Try it online!
> 2 votes

# Answer
# Python 3, 69 bytes

```
for i in range(26):print(" "*(25-i)+"ZYXWVUTSRQPONMLKJIHGFEDCBA"[i:])

```

Try it online!

This is my first challenge. I hope i've done this right.

Edit: Had a 26 where a 25 should have been.
> 2 votes

# Answer
# J, 21 bytes

```
({.~1-2*#)\.u:90-i.26

```

Try it online!

## original version

```
(,~' '#~<:@#)\.|.26$65|.a.

```
* `26$65|.a.` get A - Z
* `|.` reverse them
* `\.` take successive prefixes from the right side
* `(,~' '#~<:@#)` append to each one (`,~`) a number of spaces equal to the length of the prefix minus 1 (`<:@#`)

Try it online!
> 2 votes

# Answer
# Haskell, ~~52~~ ~~48~~ 53 bytes

```
do x<-scanr(:)[]['Z','Y'..'A'];tail$(' '<$x)++x++"\n"

```
> 2 votes

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

```
Module M
Sub Main
Dim S,I,J
For I=0To 25
S=Space(25-I)
For J=0To 25-I
S+=Chr(90-I-J)
Next
Console.WriteLine(S)
Next
End Sub
End Module

```

Try it online!
> 2 votes

# Answer
# Python 3, 71 bytes

```
for x in range(26):print(' '*(25-x),*map(chr,range(90-x,64,-1)),sep='')

```

Try it online!
> 2 votes

# Answer
# Brachylog, 16 bytes

```
∧Ẓa₁ụ?b{~wṢ}ᵐ&ẉ⊥

```

Try it online!

Prints with a single trailing newline.
> 2 votes

# Answer
# Whitespace, 163 bytes

Try it online!

```
                                    (s = space, t = tab, l = linefeed)
sssttstsl   push 26                 For x = 26 times

lssl        start: ""
sls         dup (Stack: [26, 26])       For y = x times

lsssl       spaces:
ssstl       push 1
tsst        sub                             decrement space counter
sls         dup
ltstl       jz end_spaces                   if space counter > 0
ssstsssssl  push 32
tlss        outchar                             print space
lslsl       jmp spaces
lsstl       end_spaces:                 next y

sll         drop                        drop y
sls         dup (Stack: [26, 26])

lssssl      letters:
sls         dup                         for y = x to 0
ssstssssssl push "@"
tsss        add (Stack: [26, 26, "Z"])      add y to "@" to get start letter
tlss        outchar                         print that letter
ssstl       push 1
tsst        sub                             decrement y
sls         dup
ltsstl      jz end_letters
lslssl      jmp letters                 next y
lssstl      end_letters:

sll         drop                        drop y
ssstl       push 1
tsst        sub                         decrement x
sls         dup
ltsttl      jz end
ssststsl    push 10
tlss        outchar                     print newline
lsll        jmp start               next x

```
> 2 votes

# Answer
# Vyxal, 9 bytes

```
kA¦₄ʁ꘍RṘ⁋

```

Try it Online!

could be -1 byte by replacing the  at the end with the `j` flag

-4 bytes from the initial working version thanks to ovs
some golfs were proposed by other people but they broke the answer
-2 bytes thanks to Aaron Miller

```
kA¦₄ʁ꘍RṘ    Full Program
kA          "ABC...XYZ"
  ¦         "A", "AB", "ABC", ..., "ABC...XYZ"
   ₄        26
    ʁ       0..25
     ꘍      a + " " * b (returns "A", "AB ", "ABC  ", ...)
      R     Reverse each ("A", " BA", "  CBA", ...)
       Ṙ    Reverse the entire list
        ⁋   Join on newlines

```
> 2 votes

# Answer
# Python 3, ~~84~~ ~~80~~ 73 bytes

```
for i in range(25,-1,-1):print(' '*i+"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i::-1])

```

Try it online!

Saved 7 bytes thanks to `@Mr. Xcoder`
> 1 votes

# Answer
# Japt, ~~17~~ 16 bytes

```
;26Çn26 î +Bw tZ

```

Try it online!
> 1 votes

# Answer
# Pyth - ~~16~~ 15 bytes

```
V_UG+*dN_<rG1hN

```

Try it online here.
> 1 votes

# Answer
# Pyth, 15 bytes

```
j_.e+*kd_rb1._G

```

**Try it online!**

---

# Explanation

* `j_.e+*kd_rb1._G` \- Full program.
* `._G` \- Prefixes of the lowercase alphabet.
* `.e` \- Enumerated map, with `k` as the indexes and `b` as the values.
* `*kd` \- A space repeated a number of times equal to the current index.
* `_rb1` \- And the current element converted to uppercase.
* `+` \- String concatenation.
* `_` \- Reverse.
* `j` \- Join by newlines.
> 1 votes

# Answer
# Japt `-R`, ~~15~~ ~~12~~ 11 bytes

```
;Båi ËiEçÃÔ

```

Test it

```
;Båi ËiEçÃÔ
;B              :Uppercase alphabet
  å             :Cumulatively reduce by
   i            :  Prepending
     Ë          :Map each element a 0-based index E
      i         :  Prepend
       Eç       :  Space repeated E times
         Ã      :End map
          Ô     :Reverse
                :Implicit output joined with newlines

```
> 1 votes

# Answer
# C (gcc), ~~75~~ 72 bytes

*-3 bytes thanks to Steadybox*

```
i=27;main(j){for(;--i;)for(printf("\n%*c",j=i,64+i);--j;putchar(64+j));}

```

Try it online!
> 1 votes

# Answer
# PHP, 82 bytes

```
$l=strlen($s=$argv[1]);while($l)echo strrev(str_pad(substr($s,0,$l),$l+$l--))."
";

```

Called with `ABCDEFGHIJKLMNOPQRSTUVWXYZ` as an argument.

Do I get bonus points because it produces the desired effect with any string? :P
> 1 votes

# Answer
# Implicit, ~~24~~ ~~23~~ ~~22~~ 19 bytes

```
À¦\^(-(1ß-);%\1^ß1ö
À                    « push alphabet                       »;
 ¦                   « swap case                           »;
  \                  « reverse                             »;
   ^                 « push length                         »;
    (                « do                                  »;
     -               «  decrement string length            »;
      (1..)          «  while top of stack truthy          »;
        ß            «   print space                       »;
         -           «   decrement string length           »;
           ;         «  pop string length                  »;
            %        «  print string                       »;
             \1      «  knock first character off string   »;
               ^     «  push length                        »;
                ß1   «  print newline                      »;
                  ö  «  exit without implicit output if top of stack falsy  »;
                     « implicit infinite loop              »;

```

Try it online!
> 1 votes

# Answer
# RProgN 2, 17 bytes

```
AL«]' '*\A\ùi.‹»;

```

## Explained

```
AL«]' '*\A\ùi.‹»;
AL                  # Length of the Alphabet, 26.
  «            »;   # For each, numbers 1 through 26 inclusive.
   ]                # Duplicate the index eg.                   (5, 5)
    ' '*            # Repeat ' ' by the index.                  (5, '     ')
        \           # Flip the top of the stack,                ('     ', 5)
         A\         # Push the alphabet under the top.          ('     ', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 5)
           ù        # Get the first n characters.               ('     ', 'ABCDE')
            i       # Reverse the top of the stack.             ('     ', 'EDCBA')
             .      # Concatenate.                              ('     EDCBA')
              ‹     # Rotate left, to remove the extra space.   ('    EDCBA ')

```

This leaves each result on the stack, and RProgN2 implicitely prints the stack upside down, which conveniently gives us our result.

Try it online!
> 1 votes

# Answer
# SpecBAS - 89 bytes

```
1 s=25,a$="ZYXWVUTSRQPONMLKJIHGFEDCBA"
2  ?" "*s;a$
3 a$=a$(2 TO),s-=1
4 IF s>0 THEN 2
5  ?a$

```

Bit of string splicing, rinse and repeat
> 1 votes

# Answer
# VB, 167 bytes

```
i = 26

For a = i To 1 Step -1
    For j = a To 1 Step -1
        c = c + "  "
        b = b + Chr(64 + j)
    Next

    d = d & c & b & vbNewLine
    c = ""
    b = ""
Next
msgbox d

```

first time to participate but i'm not competing to everyone, just myself. lol
> 1 votes

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

```
_=>new int[26].Select((x,i)=>"ZYXWVUTSRQPONMLKJIHGFEDCBA".Substring(i).PadLeft(51-2*i))

```

Also included in byte count:

```
using System.Linq;

```

Try it online!

This outputs a collection of strings (for each line).

Explanation:

```
_ =>                                   // A function that takes one argument (unused)
    new int[26].                       // Create new collection size 26
    Select((x, i) =>                   // Replace every member with
        "ZYXWVUTSRQPONMLKJIHGFEDCBA"   //    Our alphabet
        .Substring(i)                  //    Take it's part based on line number
        .PadLeft(51 - 2 * i)           //    Add spaces to the left
    )

```

Here's non-kolmogorov version (for any string) - 76 + 18 bytes:

```
a=>new int[a.Length].Select((x,i)=>a.Substring(i).PadLeft(a.Length*2-1-2*i))

```

Try it online!
> 1 votes

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

**Solution:**

```
raze@/:(1_')\[(25#" ";(|).Q.A)]

```

**Example:**

```
q)raze@/:(1_')\[(25#" ";(|).Q.A)]
"                         ZYXWVUTSRQPONMLKJIHGFEDCBA"
"                        YXWVUTSRQPONMLKJIHGFEDCBA"
"                       XWVUTSRQPONMLKJIHGFEDCBA"
"                      WVUTSRQPONMLKJIHGFEDCBA"
"                     VUTSRQPONMLKJIHGFEDCBA"
"                    UTSRQPONMLKJIHGFEDCBA"
"                   TSRQPONMLKJIHGFEDCBA"
"                  SRQPONMLKJIHGFEDCBA"
"                 RQPONMLKJIHGFEDCBA"
"                QPONMLKJIHGFEDCBA"
"               PONMLKJIHGFEDCBA"
"              ONMLKJIHGFEDCBA"
"             NMLKJIHGFEDCBA"
"            MLKJIHGFEDCBA"
"           LKJIHGFEDCBA"
"          KJIHGFEDCBA"
"         JIHGFEDCBA"
"        IHGFEDCBA"
"       HGFEDCBA"
"      GFEDCBA"
"     FEDCBA"
"    EDCBA"
"   DCBA"
"  CBA"
" BA"
,"A"
""

```

**Explanation:**

Create two lists, 1 with 25 spaces, 1 with the reversed alphabet, then drop the first item from each list and join together. Use converge `\` to terminate when the output matches previous output (hence this results in a trailing empty line):

```
raze each (1_')\[(25#" ";reverse .Q.A)] / ungolfed solution
                 (      ;            )  / two item list
                  25#" "                / 25 take " ", whitespace 25 long
                         reverse .Q.A   / .Q.A is uppercase alphabet A..Z, reverse reverses, so Z..A
          (   )\[                     ] / converge running left function with right arguments
           1_'                          / 1 drop (_) each (') removes first item from each sublist and returns result (2 lists)
raze each                               / raze reduces a list of lists, so we reduce each sublist of 2 lists to a single list

```
> 1 votes

# Answer
# Perl 6, 44 bytes

```
$_=chrs 32 xx 27,91...65;.say while s/\s\S//

```

Try it online!
> 1 votes

# Answer
# QBIC, 48 bytes

```
[26|Q=Q+chr$(a+64)][26,1,-1|?space$(b)+_s_fQ|,-b

```

## Explanation

```
[26|            FOR a = 1; a <= 26; a++
Q=Q+chr$(a+64)  Add to Q$ a chr() being a+64 (A-Z in succession)
]               NEXT (at the end of the loop, Q$ is ABC...XYZ)
[26,1,-1|       FOR b = 26; b >= 1; b--
?space$(b)      PRINT b spaces,
+_s             and a substring of
   _fQ|         Q$ reversed,
   ,-b          taking b characters from the right

```
> 1 votes

# Answer
# DUP, 48 bytes

```
25 65[^[$][32,1-]#%^^+[^^\-][$,1-]#,10,^][\1-\]#

```

Online DUP interpreter
> 1 votes

# Answer
# Octave, 38 bytes (or 46 bytes in tio)

```
flip([spdiags(hankel(90:-1:65)) '']')'

```

Generates the correct output at least on windows installation of Octave, but in tio to be correctly shown the character `0` should be replace by space:

```
[max(32,flip(spdiags(hankel(90:-1:65))')') '']

```

Try it online!
> 1 votes

# Answer
# Perl 6, 57 bytes

```
.put for (' 'Xx(25...0))Z~(('Z'...'A') »...»'A')».join

```

Try it online!

## Expanded:

```
  .put              # print with trailing newline

for                 # for each of the following

  (
      ' '

    Xx              # cross using string repetition operator

      ( 25 ... 0 )  # from 25 down to 0
  )

  Z~                # zip using string concatenation

  (
    ( 'Z' ... 'A' ) # descending sequence of starting values
    »...»           # combine those into sequences each with an end value of 'A'
    'A'
  )».join           # combine each of the sub sequences into strings

```
> 1 votes

# Answer
# brainfuck, 119 bytes

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

```

Try it online!

Could be golfable by better initializing the tape - there is a modulo solution that would pop 90,32,26 and 10, that would also probably leave the tape a little less fragmented.

Also could combine all three loops unto one, by juggling the index as the difference from the ASCII code 'Z', or something.
> 1 votes

# Answer
# Clojure v1.8, 93 bytes

Converted Renzo's answer to Clojure.

```
(dotimes[i 26](prn(apply str(concat(repeat(- 25 i)" ")(subs"ZYXWVUTSRQPONMLKJIHGFEDCBA"i)))))

```

# Explanation

```
(dotimes [i 26] ...)                 We will print 26 lines, i is between[0, 26)
(subs"ZYXWVUTSRQPONMLKJIHGFEDCBA"i)  Take the string starting from position 'i'
(repeat(- 25 i)" ")                  Repeat the whitespaces, we start from 25 because the last line doesn't have whitespaces
(prn(apply str(concat(repeat(- 25 i)" ")(subs"ZYXWVUTSRQPONMLKJIHGFEDCBA"i)))) Concatenate the sequence of whitespaces and the string in order to have the desired effect with 'str' next

```

Try it online!
> 1 votes

# Answer
# Java, ~~196~~ 134 bytes

Yes, this has no chance of winning overall, but it helps to re-familiarize myself with the language. Any improvements are welcome, but know I have not yet had time to read the Tips or Golfing in Java.

~~`public class A{public static void main(String[]a){for(int i=0;i<26;i++){for(int j=0;j<25-i;j++)System.out.print(" ");for(char c=(char)(90-i);c>=65;c--)System.out.print(c);System.out.println();}}}`~~

Thanks to JollyJoker for suggesting improvements. I won't get a chance to investigate lambdas for this one, but I'll remember it for the future. This is as short as I'll make this one. Eclipse kept complaining when I changed all ints to chars, so I'll look into that some more.

```
String a(){String r="";for(int i=0;i<26;i++){for(int j=0;j<25-i;j++)r+=" ";for(char c=(char)('Z'-i);c>=65;c--)r+=c;r+="\n";}return r;}

```

Try it online!

Ungolfed:

~~`public class A {
 public static void main(String[] args) {
 for (int i = 0; i < 26; i++) {
 for (int j = 0; j < 25 - i; j++)
 System.out.print(" ");
 for (char c = (char)(90 - i); c> = 65; c--)
 System.out.print(c);
 System.out.println();
 }
 }
 }`~~

```
String a() {
    String r = "";
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < 25 - i; j++)
            r += " ";
        for (char c = (char)('Z'-i); c >= 65; c--)
            r += c; r+= "\n";
    }
    return r;
}

```
> 1 votes

# Answer
# Python 2, ~~86~~ 83 bytes

```
for x in range(25,-1,-1):print(" "*x)+"".join([chr(y+65)for y in range(x+1)][::-1])

```

Thanks to Stephen for the 3 extra bytes.
> 1 votes

# Answer
# Javascript, 82 bytes

```
for(i=26;i;){console.log(" ".repeat(i-1)+"ZYXVUTSRQPONMLKJIHGFEDCBA".slice(-i--))}

```

Try it online!
> 1 votes

# Answer
# Pyth, 14 bytes

-2 from dave and ven thanks guys

```
V_UG+*dNrG1=PG

```

Explanation coming when I ~~figure it out~~ wake up.

## Pyth, 16 bytes

```
V26p*-25Nd>_rG1N

```

Explanation:

```
V26        26 times, could've written lG, but it's the same
   p*-25Nd Print without newline: 25-index spaces (could've used + instead of p but it's simpler to explain)
   >_rG1N  Implicit print with newline: The last index characters of the reverse uppercase alphabet

```

Try it online!

While you're here, here's Artemis's first answer ported into Pyth:

## Pyth, ~~21~~ 20 bytes (non-competing)

```
J26W=tJ+*dJ>_rG1-25J

```

An explanation for Artemis's answer:

```
J26        Set J to 26
W          While...
 =tJ       Decrement J (J-=1)
 +*dJ      J spaces plus...
 >_rG1-25J The last 25-index characters of the reverse uppercase alphabet

```

I should stop writing these on my phone

Try it online!
> 1 votes

# Answer
# Twig, 93 bytes

Twig is a template language developed to be used in PHP, which is similar to Smarty, Django or Jinja.

```
{%for a in "Z".."A"%}{{("%"~(26-loop.index)~"s%s")|format(f,range(a,"A")|join())}}
{%endfor%}

```

This code relies in the fact that the environment option `strict_variables` defaults to `false`. Otherwise, it will break.

Try it on https://twigfiddle.com/9umogr (check the **raw** result).
If you want to copy-paste the code, make sure that you disable `strict_variables`, since the website sets that to `true`.
> 1 votes

# Answer
# Recursiva, ~~50 24 23~~ 22 bytes

```
{B26"P+*' '-L(}Z~}_(26

```

Try it online!
> 1 votes

# Answer
# Dyalog APL, ~~34~~ ~~23~~ 21 bytes<sup>SBCS</sup>

```
↑{(1-2×⍵)↑⌽⍵↑⎕A}¨⌽⍳26

```

Try it online!

Thanks to Adám for the help!

Explanation:

```
↑{(1-2×⍵)↑⌽⍵↑⎕A}¨⌽⍳26
                  ⍳26 ⍝ 1..26
                 ⌽    ⍝ Reverse, 26..1
 {             }¨     ⍝ For each in this range. Iteration: ⍵
            ↑         ⍝ Take...
           ⍵          ⍝ ...⍵ elements...
             ⎕A       ⍝ ...from the alphabet
          ⌽           ⍝ Reverse
         ↑            ⍝ Pad with spaces...
  (1-2×⍵)             ⍝ ...(1 - 2*current iteration) elements
↑                     ⍝ Format

```
> 1 votes

# Answer
# Bash + coreutils, 64 bytes

```
printf '%s' {Z..A}|sed 'h;s/./ /g;G;s/ \n//;p;:a;s/ \b.//p;ta;Q'

```
> 1 votes

# Answer
# C, 82 characters

```
char*a="ZYXWVUTSRQPONMLKJIHGFEDCBA\n",i=54;main(){while(i)printf("%*s",i-=2,a++);}

```

Works for any character coding, by embedding the full alphabet. We print subsequent trailing substrings in a field twice as wide as required, to get the leading spaces.

I had hoped to be able to reduce it further with `while(printf());`, but couldn't arrange for the return value to reach zero at the right point.
> 1 votes

# Answer
# Husk, 15 bytes

```
mṠ+ȯR' ←Lhṫ…"ZA

```

Try it online!

-5 thanks to Zgarb. Still a newb :p
> 1 votes

# Answer
## Retina, 38 bytes

```

25$* Z
{-2=`
$'
}T`L`_L`.$
;{:G`
 \w

```

Try it online!

### Explanation

```

25$* Z

```

Initialise the working string to 25 spaces and a single `Z`.

```
{-2=`
$'
}T`L`_L`.$

```

The usual approach for generating the alphabet: repeatedly duplicate the last letter, then decrement that letter with a transliteration, removing `A`s instead of decrementing them further. That means once we get to `A`, the second stage will delete the letter which was added by the first stage, so there won't be any net change and the loop stops. That gives us the first line of the output.

```
;{:G`
 \w

```

Now we really just repeatedly print the current line and the drop a space followed by a letter. The construction is slightly weird due to how loops and printing works in Retina. We need to print before we drop the letter, which requires a separate stage that otherwise doesn't do anything, and we also need to disable the implicit printing at the end of the program.
> 1 votes

# Answer
# Java, 206 bytes

```
public class Main{public static void main(String[]args){int i,j,k,l=90;for(k=26;k>=0;k--){for(i=k-1;i>0;i--){System.out.print(" ");}for(j=l;j>=65;j--){System.out.print((char)j);}l--;System.out.println();}}}

```

Try it online!
> 1 votes

# Answer
# Kotlin, ~~87~~ 71 bytes

## Submission

```
{(0..25).map{(it..25).map{print(" ")
it}.map{print('Z'-it)}
println()}}

```

## Beautified

```
        {
            // For it from 25 to 0
            (0..25).map {
                // Print that number of spaces
                // Print the alphabet backwards from that letter
                (it..25).map { print(" ")
                it}.map { print('Z' - it) }
                // Newline
                println()
            }
        }

```

## Test

```
var f:()->Unit =
{(0..25).map{(it..25).map{print(" ")
it}.map{print('Z'-it)}
println()}}
fun main(args: Array<String>) {
    f()
}

```
> 1 votes

# Answer
# VBA, 65 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window

```
For i=0To 25:?Spc(25-i);:For j=0To 25-i:?Chr(90-j-i);:Next:?:Next

```

### Naïve Version, 68 Bytes

```
For i=0To 25:?Spc(25-i)Right("ZYXWVUTSRQPONMLKJIHGFEDCBA",26-i):Next

```
> 1 votes

# Answer
# Acc!!, 113 bytes

```
26
Count i while i-_ {
	Count b while b-25+i {
		Write 32
	}
	Count t while t-_+i {
		Write 90-t-i
	}
	Write 10
}

```

Try it online!
> 1 votes

# Answer
# uBASIC, 74 bytes

That pesky `Chr$` function sure does like to add extra spaces

```
0ForI=0To25:?Tab(25-I);:ForJ=0To25-I:?Left$(Chr$(90-I-J),1);:NextJ:?:NextI

```

Try it online!
> 1 votes

# Answer
# MY-BASIC, 100 bytes

Anonymous function that takes no input and outputs to the console

```
For I=0 To 25
For J=I To 25
Print" "
Next
For K=0 To 25-I
Print Left(Chr(90-I-K),1)
Next
Print;
Next

```

Try it online!
> 1 votes

# Answer
# Yabasic, 79 bytes

Another BASIC answer for Ya.

```
For I=0To 25
For J=I To 25
?" ";
Next
For K=0To 25-I
?Chr$(90-I-K);
Next
?
Next

```

Try it online!
> 1 votes

# Answer
# Canvas, 6 bytes

```
Ｚ［↔］Ｒ⇵

```

Try it here!

Explanation (characters have been changed to their ASCII forms to look monospace):

```
Z       push the uppercase alphabet
 [ ]    map over prefixes
  ↔       reverse horizontally
    R   pad each line with the line number spaces
     ⇵  and reverse the whole thing vertically

```
> 1 votes

# Answer
## PHP, 113 Bytes

Try it online!

**Code, recursive function**

```
function f($s=0){echo ($s<26)?str_pad("", $s)
.implode(array_reverse(range(chr(65), chr(65+$s))))."
".f($s+1):"";}

```

**Explanation**

```
function f($s=0){
  echo ($s<26)?           #it stops at the 26 letter
  str_pad("", $s)         #padding whitespace
  .implode(array_reverse(range(chr(65), chr(65+$s))))
                          #implode the range of letters,
                          #yes, range works with characters too
                          #reverse the array because it always starts with A
  ."                      #concatenate a linebreak
   ".f($s+1):"";          #calling for the next letter
}

```
> 1 votes

# Answer
# Go, 127 Bytes

```
package main;import."strings";func main(){for i:=26;i>0;i--{print("\n",Repeat(" ",i-1));for j:=i;j>0;j--{print(string(j+64))}}}

```

This prints with a leading newline.

## Ungolfed and readable

```
package main
import . "strings"
func main(){
    for i := 26; i > 0; i-- {
        print("\n", Repeat(" ", i-1))
        for j := i; j > 0; j-- {
            print(string(j + 64))
        }
    }
}

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 82 bytes

```
	U =REVERSE(&UCASE)
O	OUTPUT =DUPL(' ',SIZE(U) - 1) U
	U LEN(1) REM . U	:S(O)
END

```

Try it online!

Finally got around to a SNOBOL answer for this challenge. Always prints with a trailing newline.
> 1 votes

# Answer
# SmileBASIC 3, ~~67~~ 64 bytes

*-3 bytes from @12Me21 using the `-I` trick*

Unfortunately the console is one character too narrow to fit the first line without wrapping the last character. Oh well.

```
FOR I=-25TO.?" "*-I+RIGHT$(@ZYXWVUTSRQPONMLKJIHGFEDCBA,-I+1)NEXT

```
> 1 votes

# Answer
# Stax, ~~13~~ 9 bytes

```
á*↔?[O╒v4

```

Run and debug it at staxlang.xyz!

### Unpacked (15 bytes) and explanation

```
VAr|]mc%Hv)
VAr                Uppercase alphabet, reversed
   |]              List of suffixes
     m             Map rest of program over array, printing each element with a linefeed:
      c              Copy top of stack
       %             Length
        Hv           Double and decrement
          )          Pad string on left with spaces to the specified length

```

~~I think that `VAr|]mc%Hv|z` SHOULD work for 10 bytes (once packed), but what looks to me like a bug kills that solution.~~ I stupidly confused `|z` with `)` there. Thanks @recursive for pointing that out (and saving even another byte)!
> 1 votes

# Answer
# Rust, 87 bytes

```
fn main(){for i in 0..26{println!("{:>1$}",&"ZYXWVUTSRQPONMLKJIHGFEDCBA"[i..],51-2*i)}}

```

## With Spaces and Indentation

```
fn main() {
    for i in 0..26 {
        println!("{:>1$}", &"ZYXWVUTSRQPONMLKJIHGFEDCBA"[i..], 51-2*i)
    }
}

```

Try it online
> 1 votes

# Answer
# Emojicode, 156 bytes

```
a                         ZYXWVUTSRQPONMLKJIHGFEDCBAi 0◀i 26a i➖25 ia➕i 25ai➕i 1

```

Try it online!

**Explanation:**

```
      start program
a                         ZYXWVUTSRQPONMLKJIHGFEDCBA      big ol string
i 0            declare loop variable
    ◀i 26       loop 26 times
                  print concatenated string
        a i➖25 i      number of spaces
        a➕i 25a      reverse alphabet minus last letter
        i➕i 1        increment loop variable
                   end loop
                  end program

```
> 1 votes

# Answer
# Swift, 118 bytes

```
var s="";for i in 0..<26{for _ in 0..<25-i{s+=" "};for j in 0..<26-i{s+="\(UnicodeScalar(90-i-j)!)"};s+="\n"};print(s)

```

**Prettyfied:**

```
var s = ""

for i in 0 ..< 26 {
    for _ in 0 ..< 25 - i {
        s += " "
    }

    for j in 0 ..< 26 - i {
        s += "\(UnicodeScalar(90 - i - j)!)"
    }

    s += "\n"
}

print(s)

```

Try it online!
> 1 votes

# Answer
# T-SQL, 115 bytes

```
DECLARE @ VARCHAR(51)=SPACE(25)+'ZYXWVUTSRQPONMLKJIHGFEDCBA'a:PRINT @
SET @=STUFF(@,len(@)/2,2,'')IF len(@)>0GOTO a

```

Shorter to just hard-code the initial string, then I used `STUFF()` to snip out two characters from the middle each loop.

I can save 3 bytes by using a `CHAR(51)` instead of a `VARCHAR(51)`, but that prints full-width trailing spaces for all rows, which don't appear to be allowed.
> 1 votes

# Answer
# C# (.NET Core), ~~133~~ 114 bytes

```
var S="";for(int I=26;I-->0;){var C='@';for(;C++<I+64;)S+=" ";for(;C>'@';)S+=C--;S+="\n";}System.Console.Write(S);

```

Try it online!

```
var S="";                   // Initialize the return string
for(int I=26;I-->0;){       // For all 26 rows (with I as the space count)
    var C='@';              // Initializing C with the char '@' which is one under 'A'
    for(;C++<I+64;)         // For all spaces needed and sets the char one up ('@' -> 'A', 'A' -> 'B')
        S+=" ";             // Add a space to the string
    for(;C>'@';)            // For all characters which are needed from the char countet above up down to 'A'
        S+=C;               // Add the char to the string
    S+="\n";                // Add a new line to the string
}
System.Console.Write(S);    // Output the string

```
> 1 votes

# Answer
# K4, 22 bytes

**Solution:**

```
,/'(1_')\0 25_|51$.Q.A

```

**Explanation:**

Generate two lists and reduce each until they are empty.

```
,/'(1_')\0 25_|51$.Q.A / the solution
                  .Q.A / A..Z
               51$     / pad to 51 chars
              |        / reverse it
         0 25_         / cut (_) at indices 0 and 25
   (   )\              / perform this along
    1_'                / drop (_) first from each (') list
,/'                    / flatten (,/) each (')

```

**Bonus:**

Another **22 byte** solution:

```
,/'(1_')\(25#$`;|.Q.A)

```
> 1 votes

# Answer
# \>\<\>, ~~51~~ 49 bytes

```
2d*:&:1(?v:"@"+$1-48*}40.
l2(?vob1.>r~
-20.>~ao&1

```

Try it online!
> 1 votes

# Answer
# Gaia, 14 bytes

```
26…v§&¦₵Av┅+†ṣ

```

Try it online!
> 1 votes

# Answer
# Ruby, 58 bytes

Not the best answer for Ruby, but still good enough to get second place out of three entries lol. I just wanted to try a regex-based solution.

```
s=' '*26+[*?A..?[].reverse*''
puts s while s.sub!(/ \S/){}

```

Try it online!
> 1 votes

# Answer
# Pip `-l`, 18 bytes

```
R R*AZ@,\,26.sX,26

```

Run it here! Alternately, here's the equivalent 19-byte solution in an older version of Pip: Try it online!

### Explanation

```
               ,26  Range(26)
             sX      String-multiply each element by space: list of 0 to 25 spaces
        \,26        Inclusive-range(1,26)
       ,             Range(each element)
      @              Use each range as an index into...
    AZ               Uppercase alphabet
            .       Concatenate those two lists itemwise
  R*                Reverse each string in the resulting list
R                   Reverse the list itself
                    Autoprint the list, one string per line (-l flag)

```

---

Another 18-byte answer using map:

```
RAZ@,1+_.sX_M R,26

```

Try it online! (19-byte equivalent)
> 1 votes

# Answer
# Lua, 82 bytes

```
s=' 'for i=90,65,-1 do o=s:rep(i-65)for j=i,65,-1 do o=o..s.char(j)end print(o)end

```

Try it online!

**Human readable code:**

```
s=' '
for i=90,65,-1 do
  o=s:rep(i-65)
  for j=i,65,-1 do
    o=o..s.char(j)
  end
  print(o)
end

```
> 1 votes

# Answer
# BRASCA, 23 bytes

```
e[{:[Eo{]x:}[{:D+o]lox]

```

Try it online!
> 1 votes

# Answer
# Zsh, 41 bytes

```
eval 1={A..Z}'$1;<<<${(l:#1-65:)}$1;'|tac

```

Try it online!

Explanation:

* `1={A..Z}'$1;<<<${(l:#1-65:)}$1;'`: construct the string `1=A$1;<<<${(l:#1-65:)}$1; 1=B...1; 1=C...1; ... 1=Z...1;` (with every letter from `A` to `Z` in place of the `{A..Z}` in each case)
* `eval`uate that string as `zsh` code:
    + `1=A$1`: prepend `A` (or which ever letter is in that repetition) to the variable `$1`
    + `${(l:#1-65:)}`: generate `#1-65` spaces:
        - `#1`: Take the ASCII character code of the first character of `$1`
        - subtract `65`. The first iteration will have `A` as the first character of `$1`, the character code of which is `65`, and since `65-65=0`, no spaces will be printed. Then for further letters, another space will be added each time.
    + `$1`: and append the variable `$1`
    + `<<<`: and print that with a newline
* `|tac` and reverse the output line-wise

---

# Zsh, 36 bytes

```
eval 2={A..Z}'$2;<<<$1$2;1+=\ ;'|tac

```

Try it online!
> 1 votes

# Answer
# Elixir, 84 bytes

```
import Enum
map 25..0,&(IO.puts List.duplicate(' ',&1)++reverse(slice ?A..?Z,0..&1))

```

Try it online!

Still want to find a way around that `List.duplicate` call....
> 1 votes

# Answer
# Forth (gforth), 54 bytes

```
: f for i spaces i for i 65 + emit next cr next ;
25 f

```

Try it online!

### How it works

```
: f ( n -- ) \ Print n+1 lines of searchlight.
  for        \ loop from n to 0 inclusive [i]
    i spaces   \ print i spaces
    i for      \ loop from i to 0 inclusive [j];
               \ in Forth, the innermost loop count is always i
      i 65 + emit \ print a char whose charcode is j + 65
    next       \ end inner loop
    cr         \ print a newline
  next ;     \ end outer loop
25 f       \ push 25 and call f

```

Just started fiddling with Forth. Unlike the golfing tip says, it looks like `n for .. next` loop is the shortest for simple decreasing loops and `n1 n0 do .. loop` for increasing loops. The recursive call word `recurse` or `recursive` is way too verbose, and it still costs at least an `if .. then`.
> 0 votes

# Answer
# 05AB1E, 16 bytes

```
₂F₂N-D<ð×?Aus£R,

```

Try it online!

```
₂F                # for N in [0, 1, 2, ..., 25]:
  ₂N-D<ð×?        # print 25 - N spaces with no trailing newline
          Aus£R,  # print the first 26 - N letters of the uppercase alphabet, reversed
                  # (implicit) exit for loop

```
> 0 votes

# Answer
# Pyth, 21 bytes

```
=_r1GV26
+*\ -25NG=tG

```

Try it online!

Basically, it sets G to `ZYXWVUTSRQPONMLKJIHGFEDCBA`, and next prints space repeated some amount of times and G, then removes the first letter of G.
> 0 votes

# Answer
# Rockstar, 101 bytes

```
X's26
while X
O's""
let Y be X
while Y
cast Y+64 into L
let O be+L
let Y be-1

let X be-1
say " "*X+O

```

Try it here (Code will need to be pasted in)
> 0 votes

# Answer
# Excel, 66 bytes

```
=LET(r,26-ROW(1:26),x,CONCAT(CHAR(65+r)),REPT(" ",r)&RIGHT(x,r+1))

```

Link to Spreadsheet
> 0 votes

# Answer
# Splinter, 253 bytes

```
Z{\A\
}H{\C\BZ}A{\M\L\K\JG{\I\HD}D{\G\F\E\DH}D}E{\V\U\TB{\S\R\Q\PF{\O\NA}F}B}S{\ }T{SS}U{TT}V{UU}W{VV}WVS\Z\Y\X\WEWV\Y\X\WESTUW\X\WETUW\WESUWEUW\U\TBSTW\TBTWBSW\R\Q\PFW\Q\PFSTUV\PFTUVFSUV\NAUVASTV\L\K\JGTV\K\JGSV\JGVGSTU\HDTUDSU\F\E\DHU\E\DHST\DHTHS\BZZ

```

Try it online!

Link is to a Python interpreter.
> 0 votes

# Answer
# Vyxal, ~~704~~ 24 bytes

Try it online!

```
₄ʀƛ:ʁṘƛ65+C;ṅ$ð*$+;Ṙ

```

Behind door number 3, we have this answer - again just prints out the string (Edit 1: never mind, it doesn't)
> 0 votes

# Answer
# Pyramid Scheme, 1431 bytes

```
    ^         ^
   / \       / \
  /set\     /do \
 ^-----^   ^-----^
/a\   / \ /a\   /[\
---  /26 \---  ^---^
     -----    ^-   -^
             ^-     -^
            /]\      -^
           ^---^      -^
          ^-   -^      -^
         ^-     -^      -^
        ^-       -^      -^
       /[\       / \     /[\
      ^---^     /set\   ^---^
     ^-   -^   ^-----^  -^  -^
    ^-     -^ /c\   /a\ / \  -^
   / \     / \---   ---/set\  -^
  /set\   /do \       ^-----^  -^
 ^-----^ ^-----^     /a\   /-\  -^
/b\   /a\-^   /[\    ---  ^---^  -^
---   ---/b\ ^---^       /a\ /1\  -^
         ---/ \  -^      --- ---  /[\
           /set\  -^             ^---^
          ^-----^  -^           ^-  / \
         /b\   /+\ /?\         / \ /out\
         ---  ^---^---^       /do \-----^
             / \ /b\ / \     ^-----^    -^
            /-1 \---/out\   /c\   /[\   / \
            -----  ^-----   ---  ^---^ /chr\
                  / \           ^-  / \-----^
                 /chr\         ^-  /out\   / \
                ^-----        / \  -----^ /10 \
               / \           /set\     / \-----
              /32 \         ^-----^   /chr\
              -----        /c\   /-\  -----^
                           ---  ^---^     /+\
                               /c\ /1\   ^---^
                               --- ---  /c\ / \
                                        ---/65 \
                                           -----

```

Try it online!

Yes, I wrote this all by hand. It's kinda therapeutic...
> 0 votes

# Answer
# C89, 96 bytes

```
i,j;main(){for(;i<26;)++j>25?puts("ZYXWVUTSRQPONMLKJIHGFEDCBA"+i),j=++i:putchar(' ');return 0;}

```

Try it online!

```
int i, j;

int main()
{
    while(i<26){
        extern int puts();
        extern int putchar();

        if (++j > 25) {
            puts("ZYXWVUTSRQPONMLKJIHGFEDCBA" + i);
            j = ++i;
        }
        else {
            putchar(' ');
        }
    }
    return 0;
}

```
> 0 votes

# Answer
# Uiua, 25 bytes

```
;⍥(-1&p⊂↯∶@ -1,⇌+@A⇡.).26

```

Try it online!

**Explanation:**

```
                       .26   # Put 26 onto the stack twice
 ⍥(                   )     # Repeat 26 times
                     .       # Copy the counter value
                    ⇡        # Make an array of natural numbers less than counter
                 +@A         # Add "A" to each element, getting ["A", "B",...]
                ⇌            # Reverse
             -1,             # Copy counter and subtract 1
         ↯∶@                 # Make an array of space chars
        ⊂                    # Join spaces with the letters
      &p                     # Print the result
    -1                       # Subtract 1 from the original counter
;                            # Pop the counter from the stack

```
> 0 votes

# Answer
# Vyxal 3 `j`, 7 bytes

```
kZ€ƛd«Ḣ

```

Try it Online!

```
kZ€ƛd«Ḣ
kZ€      # suffixes of uppercase reversed alphabet
   ƛd«Ḣ  # prepend spaces to make each double their length then remove the first space

```

Created with the help of Luminespire.
> 0 votes

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


title: Panfix to parenthesized infix

text:
# Question
Title: Panfix to parenthesized infix
Quylthulg is a language by Chris Pressey that attempts to solve the problem of infix notation using what it calls *panfix*:

> like postfix, panfix does not require the deployment of arcane contrivances such as parentheses to override a default operator precedence. At the same time, panfix allows terms to be specified in the same order and manner as infix, an unquestionably natural and intuitive notation to those who have become accustomed to it.

---

How do you get the convenience of infix notation along with the unambiguity of prefix or postfix? Use all three, of course!

```
=y=+*3*x*+1+=

```

More formally, let `+` be an operator, and `a` and `b` be expressions. Then `(a+b)` is a valid (parenthesized) infix expression, the panfix representation of that expression is `+a+b+`, where juxtaposition represents concatenation.

Your goal is to take a panfix string and convert it to fully parenthesized infix:

```
(y=((3*x)+1))

```

For simplicity, we'll make the following changes:

* Operators can only consist of two unique characters (you can choose any, but here I'll use `*` and `+`).
* There is only one literal, which consists of another distinct character (you can choose any, but here I'll use `_`).
* The input will be a well-formed panfix expression.

For *complexity*, we'll make the following change:

* Operators can consist of *any positive number* of characters, not just one.

This makes the challenge more tricky because you can't necessarily determine how a given substring of operator characters is partitioned without looking at the rest of the string.

Here is a reference implementation for the challenge, courtesy of @user202729.

## Test Cases

```
format: input -> output
+*+_*+_*+++_+*+_*+_*+++ -> ((_*+_)+(_+(_*+_)))
**++*+***++_+_++_+*++*+***_*++*+*****_**_*_*** -> ((((_+_)+_)*++*+***_)*(_*(_*_)))
***_**_***_* -> ((_**_)*_)
+_+_+ -> (_+_)
*+*+++**+***+++++_*+*+++**+***+++++_*+*+++**+***+++++ -> (_*+*+++**+***+++++_)
*++++*+*_*_*+*+++****+_++****+_++****++*+*+++_*+++ -> (((_*_)+*+(_++****+_))*+++_)
+**+_*+_*+*_*+*_*+*_+*_+**+ -> (((_*+_)*_)+(_*(_+*_)))
+**+++++_+++++_+++++*_*+*+_++++++_+++++_+++++++* -> (((_+++++_)*_)+*(_+(_+++++_)))
+*+*+_+*+_+*+*_*+*_*+*+_+*+_+*+*+ -> (((_+*+_)*_)+(_*(_+*+_)))
**_**_**_*_****_* -> ((_*(_*(_*_)))*_)

```

I used this program to generate infix strings for this challenge (converting to panfix was trivial, but reversing is not).

# Answer
> 6 votes
# Prolog (SWI), ~~194~~ 163 bytes

<sup>*Saved a whopping 31 bytes using this tip from 0 '!*</sup>

```
[C|T]/O/R:-C\=x,(T/P/R,concat(C,P,O);O=C,R=T).
[x|R]-x-R.
L-X-R:-L/O/A,A-Y-B,B/O/C,C-Z-D,D/O/R,atomics_to_string(['(',Y,O,Z,')'],X).
X^P:-string_chars(X,L),L-P-[].

```

The operator `^` takes for its left argument a string containing a panfix expression and sets its right argument to a string containing the corresponding parenthesized infix expression. It uses `x` as the literal in place of `_`.

Try it online!

### Explanation

Since Prolog is a declarative language, we just have to describe the relation between a panfix and a parenthesized expression.

The explanation uses this slightly ungolfed version:

```
oper([C|T],O,R) :- C\=x, oper(T,P,R), concat(C,P,O).
oper([C|T],C,T).

expr([x|R],x,R).
expr(L,X,R) :- oper(L,O,A), expr(A,Y,B), oper(B,O,C), expr(C,Z,D), oper(D,O,R),
               atomics_to_string(['(',Y,O,Z,')'],X).

parenthesize(X,P) :- string_chars(X,L), expr(L,P,[]).

```

Our main production is `parenthesize`, which takes in a panfix expression `X` as a string and sends out the corresponding parenthesized infix expression `P` as a string. It uses `string_chars` to convert the input string into a list of characters and then simply passes it on to `expr`.

`expr` takes in a list of characters `L`, parses the first panfix expression it finds in `L`, and sends out the parenthesized equivalent `X` and the remainder of the list of characters `R`. There are two possible kinds of expressions:

* If the first character of `L` is `x`, then the expression is `x` and the remainder is everything after the `x`.
* Otherwise, parse an operator `O` (see `oper` below); parse an expression `Y`; parse `O` again; parse another expression `Z`; and parse `O` a third time. The remainder is everything after the third instance of `O`. The expression is the result of joining `Y`, `O`, and `Z`, surrounded by parentheses, into a string.

`oper` takes in a list of characters, where the first character is `C` and the rest are `T`; it parses an operator (i.e. a run of one or more operator characters) and sends out the operator `O` and the remainder of the list of characters `R`. To form an operator, the character `C` must be something other than `x`; also, either

* an operator `P` must be parseable from `T`, with remainder `R`; in this case, `O` is the concatenation of `C` and `P`; or,
* `O` is the single character `C`; in this case, `R` is just `T`.

### A worked example

Let's take the input `+*+x+x++*x+*` for an example.

* We want to parse an expression from `+*+x+x++*x+*`. This doesn't start with `x`, so we parse an operator from the beginning.
* `oper` will parse as big of an operator as possible, so we try `+*+`.
    + Next we parse an expression from `x+x++*x+*`. This has to be `x`.
    + Now we try to parse the same operator, `+*+`, from `+x++*x+*`. However, this *fails*.
* So we backtrack and try parsing the operator `+*` instead.
    + We parse an expression from `+x+x++*x+*`. This doesn't start with `x`, so we need to parse an operator.
    + The only possibility is `+`.
    + Now parse a subexpression from `x+x++*x+*`. This has to be `x`.
    + Now parse `+` again from `+x++*x+*`.
    + Now parse another subexpression from `x++*x+*`. This has to be `x`.
    + Finally, parse `+` again from `++*x+*`.
    + The expression has been successfully parsed. We return the string `(x+x)`.
* Back at the previous recursion level, we parse the operator `+*` again from `+*x+*`.
* Now parse another subexpression from `x+*`. This has to be `x`.
* Finally, parse `+*` again from `+*`.
* The expression has been successfully parsed. We return the string `((x+x)+*x)`.

Since there are no more characters left, we have successfully translated the expression.

# Answer
> 4 votes
# Perl, ~~78~~ ~~60~~ ~~58~~ ~~57~~ 50 bytes

Includes `+1` for `p`

Uses `1` for `+` and `2` for `*` (or in fact any digit works for any operator)

```
perl -pe 's/\b((\d+)((?1)|_)\2((?3))\2)\b/($3 $2 $4)/&&redo' <<< 22_22_22_2_2222_2

```

For convenient testing versus the given examples you can use this which does the translations and space removal for you:

```
perl -pe 'y/+*/12/;s/\b((\d+)((?1)|_)\2((?3))\2)\b/($3 $2 $4)/&&redo;y/ //d;y/12/+*/' <<< "**_**_**_*_****_*"

```

# Answer
> 3 votes
# Retina 0.8.2, ~~138~~ 134 bytes

```
.+
($&)
+`\((\d+)(_|((?<i>(?<i>\d+))|_(?<-i>\k<i>)+)+(?(i)$.))\1(_|((?<i>(?<i>\d+))|_(?<-i>\k<i>)+)+(?(i)$.))\1\)
(($2)$1($4))
\(_\)
_

```

Try it online! Link includes the faster test cases. Explanation: The regex engine uses backtracking to split the string up into tokens which are then pushed on or popped from the `i` balancing group. There is a run of always at least one operator pushed at the start before the first variable. After a variable, at least one operator is popped, at which point either a pushed operator run or another variable is legal. Operators get pushed to the group in duplicate so that they can be popped correctly. Example:

```
Input           Stack
Push *          * *
Push *++*+***   * * *++*+*** *++*+***
Push +          * * *++*+*** *++*+*** + +
Push +          * * *++*+*** *++*+*** + + + +
Variable _
Pop +           * * *++*+*** *++*+*** + + +
Variable _
Pop +           * * *++*+*** *++*+*** + +
Pop +           * * *++*+*** *++*+*** +
Variable _
Pop +           * * *++*+*** *++*+***
Pop *++*+***    * * *++*+***
Variable _
Pop *++*+***    * *
Pop *           *
Push *          * * *
Variable _
Pop *           * *
Push *          * * * *
Variable _
Pop *           * * *
Variable _
Pop *           * *
Pop *           *
Pop *

```

Unfortunately this doesn't help us capture the results in order to bracket them, so the outer operator is matched manually. The brackets are added outside-in, so the first stage wraps the entire expression in brackets and the last stage removes them now that they have propagated down to the variables.

# Answer
> 3 votes
# Clean, ~~200~~ ~~192~~ 189 bytes

```
import StdEnv,Text
f"_"=["_"]
f l=["("+a+p+b+")"\\p<-[l%(0,i)\\i<-[0..indexOf"_"l]|endsWith(l%(0,i))l],t<-[tl(init(split p l))],n<-indexList t,a<-f(join p(take n t))&b<-f(join p(drop n t))]

```

Try it online!

Defines the function `f`, taking `String`, and returning a singleton `[String]` with the result inside.

Some neat stuff:

* Doesn't use regex
* Works with any character for operators *except `_`*

# Answer
> 1 votes
# Haskell, ~~167~~ 166 bytes

```
head.e
e('_':r)=["_",r]
e(x:r)=[x]%r
e _=[]
o%t@(c:r)|[x,u]<-e t,n<-length o,[y,v]<-e$drop n u,all((==o).take n)[u,v]=['(':x++o++y++")",drop n v]|p<-o++[c]=p%r
o%_=[]

```

Try it online! Example usage: `head.e "**_**_**_*_****_*"` yields `((_*(_*(_*_)))*_)`. All characters except `_` are interpreted as operators, `_` itself denotes an identifier.

# Answer
> 0 votes
# Python 3, 226 bytes

```
from re import*
P=r'([*+]+)'+r'(\(.+?\)|_)\1'*2;R=lambda i,J=lambda i,o:i[:o]+sub(P,lambda o:'('+o[2]+o[1]+o[3]+')',i[o:],1),s=search:s(P,i)and R([J(i,o)for o in range(len(i))if s(P,J(i,o))or J(i,o)[0]+J(i,o)[-1]=='()'][0])or i

```

Defines an anonymous function named `R`.

Try it Online!

# Answer
> 0 votes
# Tamsin, 135 bytes

```
e="_"|o->O&{!(e&m(O)&e&m(O))&o->E&O<-[O,E]}&e->L&m(O)&e->R&m(O)->O&'('+L+O+R+')'.o="+"|"*".m([X,Y])=m(X)->X&<<Y>>->Y&''+X+Y.m(X)=<<X>>.

```

Try it online!

---
Tags: code-golf, string, parsing
---


title: Minimal cost path in wall-breaking maze

text:
# Question
Title: Minimal cost path in wall-breaking maze
Inspired by this Puzzling challenge.

## Challenge

Given a 2D rectangular grid where each cell is either an empty space or a wall, find the path (or one of the paths) from the top left cell to the bottom right, which satisfies the following:

1. Only movement to one of four adjacent cells is allowed.
2. The path breaks (or passes through) the minimal number of walls possible. In other words, a longer path that breaks fewer walls is preferred over a shorter path that breaks more walls.
3. Among all paths that satisfy `2.`, the path is the shortest in terms of the number of cells visited in total.

The input can be taken as a matrix (or any equivalent) containing two distinct values to represent empty spaces and walls. The top left and bottom right cells are guaranteed to be empty.

Output the path as a grid (of the same dimensions as the input) containing two distinct values, one for the cells that are part of the path and the other for the rest.

Standard rules apply. Shortest code in bytes wins.

## Test cases

In the following examples, the input uses `.#` for empty/wall, and the output uses `.+` for non-path/path.

```
Input
..#..#..

Output
++++++++

Input
.#...
...#.

Output
+.+++
+++.+

Input
....
....
....
....

Output
++++
...+
...+
...+ (or any other path of same length)

Input
..#..
..#..
..#..

Output
+++++
....+
....+ (or any other path of same length that breaks only one walls)

Input
.#.#.
##.##
.###.

Output
+++++
....+
....+ (or 3 other possible answers)

Input
.......
######.
.......
.######
....#..

Output
+++++++
......+
......+
......+
......+

Input
.....#..
#######.
#######.
........
.#######
.#######
....#...

Output
++++++++
.......+
.......+
++++++++
+.......
+.......
++++++++

```

# Answer
# JavaScript (ES7),  ~~198 185 179~~  178 bytes

Expects a matrix of integers with `-1` for a wall and `0` for an empty cell. Returns a matrix of Boolean values.

```
m=>(g=(Y,w,n,X)=>w>=W&&w>W|n>N?0:m[Y+1]||1/m[Y][X+1]?m.map((r,y)=>r.map((v,x)=>v>0?1:(X-x)**2+(Y-y)**2^1?0:r[r[x]=1,g(y,w-v,-~n,x),x]=v)):o=g(-1,W=w,N=n))(0,0,W=++m[0][0]/0,0)&&o

```

Try it online!

### Commented

This is a depth-first search. Visited cells are marked with `1`. We keep track of the number of broken walls in `w` and the total number of visited cells in `n`. We abort as soon as the current path is worse than the best path found so far.

```
m => (                         // m[] = input matrix
  g = (                        // g is a recursive function taking:
    Y, w, n, X                 //   (X, Y) = current position
                               //   w = number of broken walls
  ) =>                         //   n = number of visited cells
  w >= W && w > W | n > N ?    // if (w, n) is worse than (W, N):
    0                          //   abort
  :                            // else:
    m[Y + 1] ||                //   if there's a cell below the current cell
    1 / m[Y][X + 1] ?          //   or a cell on the right:
      m.map((r, y) =>          //     for each row r[] at position y in m[]:
        r.map((v, x) =>        //       for each value v at position x in r[]:
          v > 0 ?              //         if v is positive:
            1                  //           yield 1
          :                    //         else:
            (X - x) ** 2 +     //           if the squared distance between
            (Y - y) ** 2 ^ 1 ? //           (X, Y) and (x, y) is not equal to 1:
              0                //             do nothing
            :                  //           else:
              r[r[x] = 1,      //             mark r[x] as visited by setting it to 1
                g(y, w - v,    //             do a recursive call at (x, y) with n+1
                  -~n, x),     //             if v = -1, w is also incremented
                x              //             actual index ...
              ] = v            //             ... to restore r[x] to v afterwards
        )                      //       end of inner map()
      )                        //     end of outer map()
    :                          //   else (bottom-right cell):
      o = g(-1, W = w, N = n)  //     update (W, N) and use a last recursive call
                               //     with X undefined and Y=-1 to build the output o
)(0, 0, W = ++m[0][0] / 0, 0)  // initial call to g at (0, 0); set the cell at (0, 0)
                               // to 1 and set W to +inf
&& o                           // return o

```

The purpose of the last recursive call `o = g(-1, W = w, N = n)` is to create a copy of the current maze where all visited cells are marked with *true* and all other cells are marked with *false*.

For this call, it's important to notice that:

* because `W = w` and `N = n`, the abort test is always false
* because `Y = -1`, the test on `m[Y + 1]` is always true
* because `X` is undefined, the squared distance is always *NaN*

Therefore, what is actually done is simply:

```
m.map((r, y) => r.map((v, x) => v > 0 ? 1 : 0))

```
> 4 votes

# Answer
# Charcoal, 92 bytes

```
≔⟦⟧θＷＳ⊞θι⊞υ⟦⁰¦⁰ω⟧≔⟦⟧ηＦυ«⪫θ¶←Ｆ§ι²✳κ+¿∨ⅈⅉＦruld«≔⊟ＫＤ²✳κζＦ№#.∨ζ+⊞υＥι⁺μ⎇⁼ν²κ⁼ν⌕#.ζ»⊞ηι⎚»Ｆ⊟⌊η✳ι+¦+

```

Try it online! Link is to verbose version of code. Times out for larger grids (can just about do 3×8 but can't do 4×6). Takes grid in example format and outputs using `+`s and spaces. Explanation:

```
≔⟦⟧θＷＳ⊞θι

```

Input the grid.

```
⊞υ⟦⁰¦⁰ω⟧

```

Start with an initial state of no `.`s, no `#`s and no moves. (Strictly speaking this is incorrect but all paths must include the initial square so it cancels out.)

```
≔⟦⟧η

```

Start with no paths that reach from the end to the start.

```
Ｆυ«

```

Perform a breadth-first search of the states.

```
⪫θ¶←

```

Draw the input to the canvas, leaving the cursor at the end point.

```
Ｆ§ι²✳κ+

```

Draw the path so far.

```
¿∨ⅈⅉ

```

If the start hasn't been reached, then:

```
Ｆruld«

```

Loop over the orthogonal directions.

```
≔⊟ＫＤ²✳κζ

```

Look at the next character in that direction.

```
Ｆ№#.∨ζ+

```

If the character is a `#` or a `.`, then...

```
⊞υＥι⁺μ⎇⁼ν²κ⁼ν⌕#.ζ

```

Create a new state, formed by adding to the existing state; for index 2, add the current direction; for index 1, add 1 if the character is a `.`; for index 0, add 1 if the character is a `#`. Push this state to the list of states.

```
»⊞ηι

```

But if the start was reached, then record this state.

```
⎚»

```

Clear the canvas ready for the next state (or the final output).

```
Ｆ⊟⌊η✳ι+¦+

```

Get the minimum state, which is that with the fewest walls, or for states with equal walls, the one with the fewest non-walls (which is equivalent to the shortest path). (For states with equal wall and path length, the tie is broken by preferring paths that go left rather than up from the end.) Draw this state, plus the final position.

Much faster 101-byte version readily handles all the test cases:

```
≔⟦⟧θＷＳ⊞θι⊞υ⟦⁰¦⁰ω⟧≔⟦⟧ηＷ∧υ⊟υＦ∨¬η‹ιη«⪫θ¶←Ｆ§ι²✳λ+¿∨ⅈⅉＦruld«≔⊟ＫＤ²✳λζＦ№#.∨ζ+⊞υＥι⁺ν⎇⁼ξ²λ⁼ξ⌕#.ζ»≔ιη⎚»Ｆ⊟η✳ι+¦+

```

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

```
≔⟦⟧θＷＳ⊞θι

```

Input the grid.

```
⊞υ⟦⁰¦⁰ω⟧

```

Create the initial state.

```
≔⟦⟧η

```

Start with no path.

```
Ｗ∧υ⊟υ

```

Perform a depth-first search of the states, by removing the most recently added state each time.

```
Ｆ∨¬η‹ιη«

```

If we don't have a path yet, or it's longer than our path so far, then:

```
⪫θ¶←Ｆ§ι²✳λ+

```

Draw the input and the path so far.

```
¿∨ⅈⅉＦruld«≔⊟ＫＤ²✳λζＦ№#.∨ζ+⊞υＥι⁺ν⎇⁼ξ²λ⁼ξ⌕#.ζ»

```

If the start hasn't yet been reached then consider all possible steps and push the resulting state to the list of states.

```
≔ιη

```

Otherwise this must be the shortest path so far, so save it.

```
⎚»

```

Clear the canvas ready for the next state (or the final output).

```
Ｆ⊟η✳ι+¦+

```

Draw the shortest path found.
> 3 votes

# Answer
# Python3, 378 bytes

```
def f(b):
 Q,W=len(b),len(b[0])
 q,d=[(0,0,[(0,0)],0)],{}
 for x,y,p,c in q:
  if(x,y)==(Q-1,W-1):d[c]=p;continue
  for X,Y in[(1,0),(0,1),(-1,0),(0,-1)]:
   if 0<=x+X<Q and 0<=y+Y<W and(T:=(x+X,y+Y))not in p and(((F:='#'!=b[x+X][y+Y])and(c not in d or len(p)+1<=len(d[c])))or(not d or(c+1<=max(d)and(c+1 not in d or len(p)+1<=len(d[c+1]))))):q+=[(*T,p+[T],c+(not F))]
 return d

```

Try it online!
> 1 votes

---
Tags: code-golf, grid, path-finding, puzzle-solver, maze
---


# Question
Title: Remove first encountered elements from a second list
*Inspired by this question on Stackoverflow.*

---

### The task

Let's have two lists/arrays of integers: `L1` and `L2` of equal length. You need to identify in `L2` the position of first occurrence of each number and remove from `L1` the values on the corresponding positions. Then print/output the modified `L1`.

Any reasonable input/ouput format is accepted as long as the lists are distinguishable.

### Example

```
L1 = [1 2 3 4 5 6 7 8 9]
L2 = [2 3 3 5 5 4 3 7 1]
First occurence of each number in L2:
L2 = [2 3 3 5 5 4 3 7 1]
      ^ ^   ^   ^   ^ ^
Corresponding elements to remove from L1:
L1 = [1 2 3 4 5 6 7 8 9]
      ^ ^   ^   ^   ^ ^
Output result:
[3 5 7]

```

### Test cases

```
Input -- Output
[1,2,3,4,5,6,7,8,9];[2,3,3,5,5,4,3,7,1] -- [3,5,7]
[1,1,1];[1,2,3] -- []
[2,2,2];[1,1,1] -- [2,2]
[-1,0,2,123456];[-1,0,-1,0] -- [2,123456]
[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,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40];[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,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,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]

```

# Answer
# Jelly, 5 bytes

```
ŒQ¬Tị

```

Try it online!

## Explanation

```
ŒQ¬Tị   Main dyadic link
ŒQ      Distinct sieve - replace first occurences with 1 and other occurences with 0
  ¬     Negate
   T    Get the indices with truthy elements
    ị   Index into the other array

```
> 6 votes

# Answer
# Python 2, 49 bytes

A cool new approach from @kops, which outputs by modifying the input.

```
def f(a,b):
 while b:b.pop()in b or a.pop(len(b))

```

Try it online!

### Python 2, 51 bytes

```
lambda a,b:[x for x in a[::-1]if b.pop()in b][::-1]

```

Try it online!

We can determine whether an element stays in `L1` by whether the corresponding element in `L2` is its first occurrence. This is done with `b.pop()in b`, which pops the last element from `L2` and checks if it still exists in the list.

Because we process the elements in reverse, `[::-1]` needs to be used twice. It makes the final code a lot larger than I had hoped, but I am not able to come up with a shorter approach.
> 10 votes

# Answer
# APL(Dyalog Unicode), ~~8~~ 6 bytes SBCS

```
/⍨∘~∘≠

```

Try it on APLgolf!

A function submission which takes L1 on the left and L2 on the right.

-2 bytes from Bubbler.

## Explanation

```
/⍨∘~∘≠
/⍨     remove elements from L! identified by:
   ~   the bitwise negation of
     ≠ unique mask of L2

```
> 9 votes

# Answer
# Haskell, ~~65~~ ~~52~~ 51 bytes

```
f[]
f z(a:s)(b:t)=[a|b`elem`z]++f(b:z)s t
f _[]_=[]

```

Try it online!

The solution is the anonymous function which calls `f` applied to the empty list: `f[]`. `f` keeps track of which elements of L2 we've seen already and only adds the corresponding element of L1 to the result if we haven't seen L2's head yet.

`import Data.List` for the builtins turns out to be too expensive:

### Haskell, 65 bytes

```
((map fst.((\\)<*>nubBy((.snd).(==).snd))).).zip
import Data.List

```

Try it online!

### How?

```
((map fst.((\\)<*>nubBy((.snd).(==).snd))).).zip
                                             zip -- zip the lists
           (\\)                                  -- delete from the zipped lists
                  nubBy                          -- the first occurence of each element under the equivalence class defined by:
                        ((.snd).(==).snd)        -- equality of the second element of each pair
  map fst                                        -- take the first element of each pair from the resulting list

```

and then a lot of punctuation to send the right arguments to the right places...
> 7 votes

# Answer
# , 29 bytes

```
function(x,y)x[duplicated(y)]

```

Try it online!

A rare case, where obscure `duplicated` function appears to be useful...
> 7 votes

# Answer
# , 6 bytes

```
#~1-~:

```

Try it online!

Filter by `#~` the complement of `1-` the nub sieve `~:`
> 6 votes

# Answer
# , ~~59~~ ~~35~~ 34 bytes

*Edit: -1 byte thanks to Giuseppe ...but now outgolfed by Kirill L's answer*

```
function(a,b)a[match(b,b)<seq(!b)]

```

Try it online!

`match(x,y)` finds the index of the first element in `y` equal to each element of `x`.

So, `match(b,b)` is equal to the index of each element if it's the first one with a particular value, otherwise it it'll be equal to an earlier index where that value was previously encountered.

`seq(!b)` is golfy shorthand for `seq_along(b)`, and returns a sequence of integers `1...b` (in other words, the indices of each element of `b`). Note that we need the `!` because `seq` defaults to outputting a sequence of `b` integers if `b` contains only a single numeric element; therefore, we use `!` to first convert the argument to a `logical`-type vector (where this can't happen).
> 6 votes

# Answer
# AWK, ~~30~~ 29 bytes

```
{a[++n]=b[$1]++}n>FNR&&a[++m]

```

Try it online! *(Thanks very much to Jonah for the TIO link)*

Takes input as two files L1 and L2, with one number per line in each (or, with the `-v RS=' '` option, space-separated on a single line).
> 6 votes

# Answer
# Haskell, ~~44~~ 43 bytes

```
x!y=[a|(i,a)<-zip[0..]x,y!!i`elem`take i y]

```

Try it online!

## How?

```
x!y=                        -- (!) is a function that takes lists x and y as input
    [a|                     -- and returns the list of all the elements a
    (i,a)<-zip[0..]x,       -- where a is the i-th element of x
    y!!i`elem`take i y]     -- and the i-th element of y is not a "first occurrence" in y

```
> 5 votes

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

```
a=>b=>a.filter((_,i)=>b.indexOf(b[i])<i)

```

Try it online!
> 4 votes

# Answer
# Arturo, 67 bytes

```
$[a b][loop reverse unique map b'x[index b x]'i[remove.index'a i]a]

```

Try it on the Arturo Playground!
> 4 votes

# Answer
# Red, 69 bytes

```
func[a b][foreach c unique b[change at a index? find b c none]trim a]

```

Try it online!
> 3 votes

# Answer
# Vyxal, 5 bytes

```
ÞU†Tİ

```

Try it Online!

Same as the APL and Jelly answer.

## Explained

```
ÞU†Tİ
ÞU    # unique mask over second list
  †   # vectorised not over that
   Tİ # and index the truthy indices into the first list

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
DÙõ.;.ïÏ

```

I have the feeling this could be shorter, but 05AB1E's builtin might not be the most suitable for this challenge.

\\$L2\\$ as first input, \\$L1\\$ as second.

Try it online or verify all test cases.

**Explanation:**

```
D         # Duplicate the first (implicit) input-list L2
 Ù        # Uniquify the values in the copied list
  õ.;     # Replace the first occurrences of the values in L2 to an empty string
     .ï   # Check for each item whether it's an integer (1 if an integer; 0 if an empty
          # string)
       Ï  # Only keep the values at the truthy indices in the (implicit) input-list L1
          # (after which the resulting list is output implicitly)

```
> 3 votes

# Answer
# Python 3, 76 bytes

```
f=lambda a,b,c=[],i=0:i<len(a)and f(a,b,c+[a[i]]*(b.index(b[i])!=i),i+1)or c

```

Try it online!
> 2 votes

# Answer
# Charcoal, 10 bytes

```
ＩΦθ›κ⌕η§ηκ

```

Try it online! Link is to verbose version of code. Explanation: Port of @tsh's JavaScript answer.

```
  θ         First list
 Φ          Filtered where
    κ       Current index
   ›        Is greater than
     ⌕      First index of
         κ  Current index
       §    Element of
        η   Second list
      η     In second list
Ｉ           Cast to string
            Implicitly print

```
> 2 votes

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

```
lambda a,b:[x for x,y in zip(a,b)if b==(b:={*b}-{y})]

```

Try it online!

A little better
> 2 votes

# Answer
# Husk, 9 bytes

```
M!-m←ηk¹ŀ

```

Try it online!

## Explanation

```
M!-m←ηk¹ŀ
      k   key
     η     the indices of each element on their value.
   m←     take the first index of each key
  -       remove this from
        ŀ the input, converted to indices.
M         map each index to
 !         the respective element in the second array

```
> 2 votes

# Answer
# Python 3, 108 bytes

```
k={y.index(x)for x in y};n='z=[v for i,v in enumerate(z)if i not in k]';exec(n);n=n.replace("z","y");exec(n)

```

Try it online!

Define two lists z and y
> 1 votes

# Answer
# Pyth, 8 7 bytes

```
.DExLQ{

```

Input is L2 and L1, separated by newlines

-1 because Pyth has a built-in for evaluated input I forgot about

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 35 bytes

```
#[[Union@@Rest/@PositionIndex@#2]]&

```

Try it online!
> 1 votes

# Answer
# Perl 5, 36 bytes

```
sub{my%s;grep$s{+shift}++,@{+shift}}

```

Try it online!
> 1 votes

# Answer
# Arturo, 44 bytes

```
$[a,b][i:0select a=>[in? b\[i]take b i'i+1]]

```

Try it

```
$[a,b][                    ; a function taking two lists a and b
    i:0                    ; set i to 0
    select a=>[            ; select elements from a where...
        in? b\[i]take b i  ; the ith element of b is found in b's elements that come before index i
        'i+1               ; increment i
    ]                      ; end select
]                          ; end function

```
> 1 votes

# Answer
# Japt, 8 bytes

```
gVðÏÀVbX

```

Try it

```
kÏ¶VbVgY

```

Try it
> 1 votes

# Answer
# Uiua SBCS, 3 bytes

```
▽¬◰

```

Try it!
> 1 votes

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


# Question
Title: Explicit-ify APL expressions involving trains
Related: Clearly parenthesize APL trains

## Background

In the most basic form, APL has two kinds of tokens: **arrays** and **functions**. For this challenge, we will use a lowercase letter `a-z` for an array, and an uppercase letter `A-Z` for a function. Furthermore, we will assume each character is a token of its own; `Fx` is equivalent to `F x`.

APL has two ways to call a function: monadic (taking one argument) and dyadic (taking two arguments). Monadic application is written in prefix `F x`, and dyadic one is written in infix `x F y`. There's nothing like "operator precedence"; an APL expression is always evaluated from right to left, which can be overridden with parentheses `()`.

```
x F G y -> x F (G y)
F x G y -> F (x G y)
x F y G z -> x F (y G z)
(F x) G H y -> (F x) G (H y)

```

A **train** is a way to compose functions to derive a more complex function. In essence, a train is formed when the rightmost token is a function. Here are the rules for 2- and 3-token trains:

```
(F G H) x -> (F x) G (H x)
(u G H) x -> u G (H x)
(G H) x -> G (H x)

x (F G H) y -> (x F y) G (x H y)
x (u G H) y -> u G (x H y)
x (G H) y -> G (x H y)

```

For 4-token and longer trains, the rightmost 3 tokens are recursively grouped to form a derived function until 2 or 3 tokens remain. As a whole, it can be thought of as follows:

```
Odd-length trains
(V D V D ... V D V) x -> (V x) D (V x) D ... (V x) D (V x)
x (V D V D ... V D V) y -> (x V y) D (x V y) D ... (x V y) D (x V y)

Even-length trains
(M V D V D ... V D V) x -> M (V x) D (V x) D ... (V x) D (V x)
x (M V D V D ... V D V) y -> M (x V y) D (x V y) D ... (x V y) D (x V y)

```

If an array `u` appears at the `V` position (other than the last), replace the cooresponding `(V x)` or `(x V y)` simply with `u`. An array appearing at `M` or `D` position is a syntax error.

Note that trains may also have sub-expressions that evaluate to an array or a function:

```
x ((D a) F G (u H J) K) y
   Expand 5(odd)-token train, leftmost V position being an array (D a)
-> (D a) F (x G y) (u H J) (x K y)
   Expand 3(odd)-token train (u H J)
-> (D a) F (u H (x G y) J (x K y))

```

## Challenge

Given a line of APL expression that evaluates to an array (which may or may not include one or more trains), convert it into an equivalent expression without a train.

You can assume that the input is valid under the rules stated above, and it doesn't contain any spaces. You don't need to worry too much about parentheses or spaces in the output; lacking or redundant parentheses/spaces are fine as long as they represent the equivalent expression.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
x(XY)y -> X(xYy)
uKKKv -> uKKKv
U(xVW)yZa -> UxVWyZa
MnP(QRsTU)VWx -> MnP(QVWx)RsTUVWx
x(XXxYYYdDD)y -> (xXy)XxY(xYy)YdDxDy
a((DEF)GHJ)Kb -> (D(aGKb)HaJKb)EF(aGKb)HaJKb
c((k(PQRSTU)m)(VW)(XY)(ZA)BCD)n -> V(P(kQm)R(kSm)T(kUm))WZ(XcYn)A(cBn)C(cDn)

```

# Answer
# APL (Dyalog Classic), ~~63 59 58 54 52~~ 51 bytes

```
∊⍎'.[A-Z].'⎕r'{0::&⍵⋄''() '',⍪⍺&⍵}'⊢'\w'⎕r'''&'''⊢⍞

```

Try it online!

put all letters in quotes, replace uppercase letters with dfns that return either "(left) self right" or "self right" depending on the presence of a left arg, and execute.
> 5 votes

# Answer
# Python3, 887 bytes:

```
def p(s):
 r=[]
 while s and(S:=s[0])!=')':
  if S.isalpha():r+=[s[0]]
  if'('==S:r+=[(K:=p(s[1:]))[0]];s=K[1]
  s=s[1:]
 return r,s
F=lambda x:(O:=ord(str(x)[0]))<=91 and(64<O<91 or all(F(i)for i in x[-2:]))
R=lambda x:[i for i in x if i]
def f(s,l=0,r=0):
 if F(s):
  J=[]
  while s:
   if F(S:=s.pop(0))==0:J+=[S]
   else:
    if len(s)>1 and F(s[0])==0:J+=[[S,s.pop(0)]]
    else:J+=[S]
  s=J
  c,s=[f([*s[0]])]if(t:=F(s[0])==0)else[],s[t:]
  c+=[f(R([l,s[0],r]))]if(S:=sum(map(F,s))%2)else[];s=s[S:]
  while s:
   if F(s[0])==0:c+=[s[0]];s=s[1:];continue
   a,b=s[:2];c+=[a,f(R([l,b,r]))if F(b) else f(b)];s=s[2:]
  return f(c)
 c=[]
 while s:
  if F(j:=s.pop(0)) and type(j)==list:
   c+=[f(j,l=c and not F(c[-1])and c.pop(),r=f(s))]
  else:c+=[j]
 return c
P=lambda e,l=0:e if str==type(e)else '('*(Y:=(l>0 and len(e)>1))+''.join(P(i,l+1)for i in e)+')'*Y
M=lambda s:P(f(p(s)[0]))

```

Try it online!

This ended up being longer than I had originally anticipated, but this is an intriguing problem, and I thought I would add a non-APL, parsing-based solution.
> 1 votes

# Answer
# Tamsin, 348 bytes

```
1=[2]->L&f->F&1->R&a(F,[L,R])|2.2="("&1->E&")"&E|"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".f="("&(f|2)/nil/list->T&")"&T|!(2|")")&any.a([F,G,H|T],A)=a(H,A)->L&a(F,A)->R&a(G,[L,R])->R&a([R|T],A).a([F|G],A)=a(F,A)->R&a(G,[nil,R]).a(F,[L,R])=n@F&R|1@F|n@L&''+F+R|'('+L+')'+F+R.n=“nil“.

```

Try it online!

Ungolfed version:

```
expr1 = [expr2] -> L & function -> F & expr1 -> R & apply(F, [L, R])
      | expr2.

expr2 = "(" & expr1 -> E & ")" & E
      | "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".

function = "(" & (function | expr2)/nil/list -> T & ")" & T
         | !(expr2 | ")") & any.

apply([F, G, H | T], A) = apply(H, A) -> L
                        & apply(F, A) -> R
                        & apply(G, [L, R]) -> R
                        & apply([R | T], A).

apply([F | G], A) = apply(F, A) -> R & apply(G, [nil, R]).

apply(F, [L, R]) = n @ F & R
                 | expr1 @ F
                 | n @ L & '' + F + R
                 | '(' + L + ')' + F + R.

n = “nil“.

```

Unfortunately Tamsin does not have a easy way to match only uppercase/lowercase letters, so we need to do `"a"|"b"|...|"z"` for matching arrays, though we can take a shortcut for functions by just matching any char that cannot be matched as a array and is not `(` and `)` as a bonus this means symbols (like `+`, `-`, `×`, etc.) are considered functions.
> 1 votes

---
Tags: code-golf, parsing, apl
---