title: Round away from zero

text:
# Question
Title: Round away from zero
# Round away from zero

Inspired by Round towards zero.

Given a number input via any reasonable method, round the number "away from zero" - positive numbers round up, and negative numbers round down.

If you intend to take the input as a string (via STDIN, for example), you should be able to handle numbers with or without the decimal point. If you take it as a number, it should at least be able to handle floating-point precision (double precision not required) or rational numbers.

You can output a floating-point number with the decimal point (e.g. 42.0) if desired. (Or even have some test cases output floating-point and some output integer, if it makes your answer shorter.)

Standard loopholes are not allowed, etc etc.

## Test cases

```
-99.9 => -100
-33.5 => -34
-7    => -7
-1.1  => -2
0     => 0
2.3   => 3
8     => 8
99.9  => 100
42.0  => 42
-39.0 => -39

```

Sandbox Link

# Answer
# Excel, 13 bytes

```
=ROUNDUP(A1,)

```

### Alternative

```
=EVEN(A1*2)/2

```
> 17 votes

# Answer
# R, 32 bytes

```
x=scan()
sign(x)*ceiling(abs(x))

```
> 10 votes

# Answer
# Jelly, 4 bytes

```
ĊṠ¡Ḟ

```

A monadic Link accepting a number which yields an integer.

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

### How?

```
ĊṠ¡Ḟ - Link: number, N
  ¡  - repeat...
 Ṡ   - ...number of times: sign of N (repeating -1 is the same as 0 times)
Ċ    - ...action: ceiling
   Ḟ - floor (that)

```
> 8 votes

# Answer
# Vim, 36 bytes/keystrokes

```
:s/-/-<Space>
:g/\..*[1-9]/norm <C-v><C-a>lD
:s/<Space><cr>

```

Try it online! or Verify all Test Cases!

Explanation:

```
:s/             " Replace...
   -            "   A dash
    /-<Space>   "   With a dash and a space

:g/                             " On Every line matching this regex...
   \.                           "   A dot
     .*                         "   Followed By anything
       [1-9]                    "   Followed by a digit other than 0
            /norm               " Run the following keystrokes...
                  <C-v><C-a>    "   Increment the number by 1
                                "   This also conveniently places our cursor just before the dot
                            l   "   Move one character right
                             D  "   Delete everything after the cursor

:s/             " Replace...
   <Space>      "   A space
                "   (With nothing)

```
> 6 votes

# Answer
# Java (JDK), 18 bytes

```
d->d.setScale(0,0)

```

Try it online!

## Explanations

Uses a `BigDecimal` as input and output. `BigDecimal` has a method `setScale` that sets the scale of the number. The first parameter is the number of digits after the dot separator, the second is the rounding mode. `ROUND_UP` is the "away-from-zero" rounding and has a value of `0` so I hardcode that value.
> 6 votes

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

```
AĊ×Ṡ

```

Try it online!

This ports recursive's Stax answer into Jelly, so check that answer out for an explanation.

-1 byte thanks to Nick Kennedy

# Jelly, ~~6~~ 5 bytes

```
ĊḞ>?0

```

Try it online!

-1 byte thanks to Jonathan Allan

## How this one works

```
ĊḞ>?0 - Monadic link. Takes a float, x, as argument

   ?  - If:
  > 0 -   x > 0
      - Then:
Ċ     -   ceil(x)
      - Else:
 Ḟ    -   floor(x)

```
> 5 votes

# Answer
# Python 3, 23 bytes

```
lambda i:i-i%(1|-(i>0))

```

Try it online!

*-1 byte thanks to xnor*
> 5 votes

# Answer
# JavaScript (ES6), 20 bytes

```
n=>n%1?n<0?~-n:-~n:n

```

Try it online!

### Commented

```
n =>        // n = input
  n % 1 ?   // if n is not an integer:
    n < 0 ? //   if n is negative:
      ~-n   //     return -(floor(-n) + 1) = -floor(-n) - 1
    :       //   else:
      -~n   //     return -(-(floor(n) + 1)) = floor(n) + 1
  :         // else:
    n       //   return n unchanged

```
> 4 votes

# Answer
# Runic Enchantments, ~~18~~ 16 bytes

```
1µ-i:'-A{*+'.A@

```

Try it online!

"Adds" (away from zero) 0.999999 and floors the result. `µ` is the closest thing to an infinitesimal in language's operators. With a properly functioning `Trunc(x)` command, answer now supports `0` as input.
> 4 votes

# Answer
# Stax, 6 bytes

```
å├╪∙Bß

```

Run and debug it

### Procedure:

1. Absolute value
2. Ceiling
3. Multiply by original sign
> 4 votes

# Answer
# , 6 bytes

```
**>.@|

```

Try it online!

Just a 1 character change from my answer on the cousin question.
> 4 votes

# Answer
# C# (Visual C# Compiler), ~~41 bytes~~~~27 bytes~~24 bytes

```
s=>(int)s+Math.Sign(s%1)

```

Try it online!

First post here, had fun with it, hope u like it. Kinda felt C# place is empty here

-14 tnx to @expired data
-3 tnx to @night2
> 4 votes

# Answer
## C, ~~94~~ ~~43~~ 39 bytes

thanks to ceilingcat for 39 bytes

```
#define f(n)(int)(n>0?ceil(n):floor(n))

```

TIO
> 3 votes

# Answer
# Husk, 5 bytes

```
*±¹⌈a

```

Try it online! Just takes the sign of the input times the ceiling of its absolute value.
> 3 votes

# Answer
# Retina 0.8.2, 38 bytes

```
\.0+
.
\b9+\..
0$&
T`9d`d`.9*\..
\..*

```

Try it online! Link includes test cases. Explanation:

```
\.0+
.

```

Delete zeroes after the decimal point, to ensure that the number is not an integer; the next two matches fail if there are no digits after the decimal point.

```
\b9+\..
0$&

```

If the integer part is all `9`s, prefix a `0` to allow the increment to overflow.

```
T`9d`d`.9*\..

```

Increment the integer part of the number.

```
\..*

```

Delete the fractional part of the number.
> 2 votes

# Answer
# Perl 6, 18 bytes

```
{$_-.abs%-1*.sign}

```

Try it online!

### Explanation

```
{                }  # Anonymous block
    .abs  # Absolute value
        %-1  # Modulo -1
           *.sign  # Multiply by sign
 $_-  # Subtract from original

```
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
ÄîI.±*

```

A 5-byter should definitely be possible..

Try it online or verify all test cases.

**Explanation:**

```
Ä       # The absolute value of the (implicit) input,
 î      # ceiled
     *  # And then multiplied by
   .±   # the signum
  I     # of the input
        # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 18 bytes

```
Sign@#⌈Abs@#⌉&

```

Try it online!
> 2 votes

# Answer
# PHP, 30 bytes

```
<?=0^$argn-=0<=>fmod($argn,1);

```

Try it online!

If number is not integer, based on the sign -1 (for negative decimals) or 1 (for positive decimals) is added to it and then integer part of the new number is printed.

---

# PHP, 32 bytes

```
<?=[ceil,floor][$argn<0]($argn);

```

Try it online!

Basically outputs `floor` of input if it is less than 0, else `ceil` of it.

---

# PHP, 34 bytes

```
<?=($argn>0?:-1)*ceil(abs($argn));

```

Try it online!
> 2 votes

# Answer
# MathGolf, 5 bytes

```
‼σ±ü*

```

Try it online!

## Explanation

It's nice to find usage for the  operator.

```
‼       apply next two operators to (implicit) input
 σ      sign (-1, 0, or 1)
  ±     absolute value
   ü    ceiling of that absolute value
    *   multiply the rounded absolute value with the sign

```
> 2 votes

# Answer
# Brachylog, 7 bytes

```
⌋₁ℤ₁|⌉₁

```

Try it online!

or `⌉₁ℕ₁|⌋₁`.

```
⌋₁         The input rounded down
  ℤ₁       is an integer less than -1
    |      and the output, or, the input
     ⌉₁    rounded up is the output.

```
> 1 votes

# Answer
# Perl 5 `-pF/\./`, 35 bytes

```
$_&&=$F[0]+($_!=int&&$_*(@F-1)/abs)

```

Try it online!
> 1 votes

# Answer
# Factor, 57 bytes

```
: f ( x -- x ) [ signum ] [ abs ceiling ] bi * >integer ;

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 15 bytes

```
{⍎'⌈⌊'[0>⍵],⍕⍵}

```

Try it online!

Simple Dfn. Uses `⎕IO←0`.

### How:

```
{⍎'⌈⌊'[0>⍵],⍕⍵} ⍝ Main function, argument ⍵.
            ⍕⍵  ⍝ Stringified argument
           ,    ⍝ Appended to
      [0>⍵]     ⍝ This item... (0 if ⍵ is positive or 0, else 1)
  '⌈⌊'          ⍝ of this string (which are the functions Ceiling and Floor, respectively)
 ⍎              ⍝ Executed as APL code.

```
> 1 votes

# Answer
# sed, 131 bytes + 2 bytes for `-r` flag

```
/^-?[^.]*(\.0*)?$/bQ
s/^(-?)9/\109/
s/([0-8]9*)\..*$/_\1/
h
s/.*_//
y/0123456789/1234567890/
G
s/(.*)\n(.*)_(.*)/\2\1/
:Q
s/\..*$//

```

## Ungolfed

```
#!/bin/sed -rf

# identify integers
/^-?[^.]*(\.0*)?$/ b isInt

# add a leading 0 if we'll need it later
s/^(-?)9/\109/

# convert to format: -?[0-9]_[0-8]9*
s/([0-8]9*)\..*$/_\1/

# move the part that will remain constant into the hold buffer
h
s/.*_//

# [0-8]9* can be incremented via character substitution
y/0123456789/1234567890/

# reassemble parts
G
s/(.*)\n(.*)_(.*)/\2\1/

:isInt
# Get rid of anything after the decimal point
s/\..*$//

```
> 1 votes

# Answer
## JavaScript (node.js), ~~30~~ ~~23~~ 21 bytes

```
s=>~~s+Math.sign(s%1)

```

Inspired by the C# answer.

Thanks to @Value Ink and @Gust van de Wal for -7 bytes!

Thanks again, @Gust van de Wal for another -2 bytes!
> 1 votes

# Answer
# PowerShell Core, ~~54~~ 48 bytes

```
$a,$u=$args-split'\.'
(1,-1)[2*!+$u+($a-lt0)]+$a

```

Try it online!

Thanks @mazzy for the improved golfing !

## Original implementation

```
$a,$u="$args"|% s*t '.'
(((1,-1)[$a-lt0]+$a),$a)[!+$u]

```

Try it online!

## Explanations

```
$a,$u="$args"|% s*t '.'        # splits the input as a string using '.'
                        [!+$u] # if there are no decimals
(                   ,$a)       # return the int part as is
 ((1,-1)[$a-lt0]+$a)           # return the int part + or - one depending of the sign of the input

```
> 1 votes

# Answer
# PowerShell Core, ~~45~~ ~~38~~ 37 bytes

```
[int]("$args"-replace'\.0*[^0]','.9')

```

Try it online!
> 1 votes

# Answer
# Julia 1.0, 17 bytes

Save 6 bytes thanks to the awesome comments of MarcMush!

```
x->x+sign(x%=1)-x

```

Try it online!

An alternative with 22 bytes

```
x->sign(x)ceil(abs(x))

```

Try it online!
> 1 votes

# Answer
# Vyxal `r`, ~~5~~ 4 bytes

*Built-ins I previously didn't know existed FTW!*

```
ȧ⌈∆±

```

Try it Online!

Explanation:

```
      # Implicit input
ȧ     # Absolute value
 ⌈    # Ceiling
  ∆±  # Change to the sign of input
      # Implicit output

```
> 1 votes

# Answer
# Risky, 20 bytes

```
_?{0-1?{0/_?{1+_0+0+1?{0+_0+0+_0+0+_0+0

```

Try it online!

Takes a pair representing a rational number.
> 1 votes

# Answer
# Java (OpenJDK 8), 43 bytes

```
a->{return(int)((int)a/a<1?a>0?a+1:a-1:a);}

```

Try it online!
> 0 votes

# Answer
# Perl 6, 19 bytes

```
{$_+|0+.sign*?/\./}

```

Try it online!

Not the shortest solution, but I'm working on it. Basically this truncates the number, then adds one away from zero if the number was not whole to begin with
> 0 votes

# Answer
# Japt, 6 bytes

```
Î*Ua c

```

Try it here
> 0 votes

# Answer
# Red, 46 bytes

```
func[n][(pick[0 1]n = t: to 0 n)*(sign? n)+ t]

```

Try it online!

The slightly more readable version is 2 byte longer (those long function names!):

```
func[n][to 1(sign? n)* round/ceiling absolute n]

```
> 0 votes

# Answer
# Scala, 16 bytes

```
_.setScale(0,UP)

```

Try it online!

# Scala, 22 bytes

```
x=>x.signum*x.abs.ceil

```

Try it online!
> 0 votes

# Answer
# Zsh, ~~43~~ ~~36~~ 35 bytes

~~Try it online!~~ ~~Try it online!~~ Try it online!

Using nested ternaries, for extra confusion. XOR logic from the round to 0 solution.

```
x=$1
<<<$[(x^0-x?x+(x<0?-1:1):x)^0]

```

Explanation:

```
x=$1                                    #set x
         x^0-x?                         #if x has decimals (shorter than x^0!=x)
                                        #(0 is falsy in this context)
                    x+(x<0?-1:1)        #  if x<0 subtract 1 else add 1
                                :x      #otherwise the result is just x
<<<$[(                            )^0]  #truncate to int & output

```
> 0 votes

# Answer
# APL(Dyalog Unicode), 5 bytes SBCS

```
××⌈∘|

```

Try it on APLgolf!

A train submission which takes a number on the right. Uses recursive's idea.
> 0 votes

# Answer
# MMIX, 16 bytes (4 instrs)

```
40000002 17000200 17000300 F8010000

```

# Disassembly / Explanation

```
rfz BN   $0,0F              // if negative, skip next instruction
    FINT $0,ROUND_UP,$0     // round to integer towards +inf
0H  FINT $0,ROUND_DOWN,$0   // round to -inf, no effect if already rounded
    POP  1,0                // return

```
> 0 votes

---
Tags: code-golf, number
---


title: City names game

text:
# Question
Title: City names game
If you like, write a program which sorts cities according to the rules of city name game.

* Each name of the city should start from the last letter in the previous city name. E.g. `Lviv -> v -> Viden -> n -> Neapolis -> s -> Sidney -> y -> Yokogama -> a -> Amsterdam -> m -> Madrid -> d -> Denwer`
* In the sorted list first letter of the first city and last letter of the last shouldn't match anything doesn't have to be the same letter.
* You can assume city names have only letters.
* Program output should have same capitalization as input

Example:

```
% ./script Neapolis Yokogama Sidney Amsterdam Madrid Lviv Viden Denwer
["Lviv", "Viden", "Neapolis", "Sidney", "Yokogama", "Amsterdam", "Madrid", "Denwer"]

```

# Answer
### Ruby, 58 55 44 characters

```
p$*.permutation.find{|i|i*?,!~/(.),(?!\1)/i}

```

Yet another ruby implementation. Uses also case insensitive regex (as Ventero's old solution) but the test is done differently.

Previous version:

```
p$*.permutation.find{|i|(i*?,).gsub(/(.),\1/i,"")!~/,/}

```
> 11 votes

# Answer
## Python (~~162~~ ~~141~~ 124)

Brute force for the win.

```
from itertools import*
print[j for j in permutations(raw_input().split())if all(x[-1]==y[0].lower()for x,y in zip(j,j[1:]))]

```
> 5 votes

# Answer
# Python, 113

Very similar to @beary605's answer, and even more brute-forced.

```
from random import*
l=raw_input().split()
while any(x[-1]!=y[0].lower()for x,y in zip(l,l[1:])):
 shuffle(l)
print l

```
> 5 votes

# Answer
## Ruby 1.9, ~~63~~ 54 characters

New solution is based on Howard's solution:

```
p$*.permutation.max_by{|i|(i*?,).scan(/(.),\1/i).size}

```

This uses the fact that there'll always be a valid solution.

Old solution, based on w0lf's solution:

```
p$*.permutation.find{|i|i.inject{|a,e|a&&e[0]=~/#{a[-1]}/i&&e}}

```
> 5 votes

# Answer
## Ruby ~~74 72 104 103 71~~ 70

```
p$*.permutation.find{|i|i.inject{|a,e|a[-1].casecmp(e[0])==0?e:?,}>?,}

```

**Demo:** http://ideone.com/MDK5c (in the demo I've used `gets().split()` instead of `$*`; I don't know if Ideone can simulate command-line args).
> 4 votes

# Answer
# Haskell, ~~94~~ 74 bytes

```
g[a]=[[a]]
g c=[b:r|b<-c,r<-g[x|x<-c,x/=b],last b==[r!!0!!0..]!!32]
head.g

```

Recursively finds all solutions. -7 bytes if it's ok to output all solutions instead of the first. Thanks to @Lynn for getting rid of the pesky import, shaving 18 bytes off the score!

Try it online!
> 3 votes

# Answer
### GolfScript, 78 characters

```
" ":s/.{1${1$=!},{:h.,{1$-1={1$0=^31&!{[1$1$]s*[\](\h\-c}*;}+/}{;.p}if}:c~;}/;

```

A first version in GolfScript. It also does a brute force approach. You can see the script running on the example input online.
> 2 votes

# Answer
# Jelly, 25 18 bytes (Improvements welcome!)

```
UżḢŒuE
ḲŒ!çƝẠ$ÐfḢK

```

Try it online!

```
UżḢŒuE        dyadic (2-arg) "check two adjacent city names" function:
Uż            pair (żip) the letters of the reversed left argument with the right argument,
  Ḣ           get the Ḣead of that pairing to yield just the last letter of left and the first letter of right,
   Œu         capitalize both letters,
     E       and check that they're equal!
ḲŒ!çƝẠ$ÐfḢK    i/o and check / fold function:
ḲŒ!            split the input on spaces and get all permutations of it,
   çƝẠ$        run the above function on every adjacent pair (çƝ), and return true if Ȧll pairs are true
       Ðf      filter the permutations to only get the correct ones,
         ḢK    take the first of those, and join by spaces!

```

Thanks to @Lynn for most of these improvements!

**25-byte solution:**

```
Uḣ1Œu=⁹ḣ1
çƝȦ
ḲŒ!©Ç€i1ị®K

```

Try it online!

```
Uḣ1Œu=⁹ḣ1      dyadic (2-arg) "check two adjacent city names" function:
Uḣ1Œu          reverse the left arg, get the ḣead, and capitalize it (AKA capitalize the last letter),
     =⁹ḣ1      and check if it's equal to the head (first letter) of the right argument.
çƝȦ            run the above function on every adjacent pair (çƝ), and return true if Ȧll pairs are true
ḲŒ!©Ç€i1ị®K     main i/o function:
ḲŒ!©           split the input on spaces and get all its permutations, ©opy that to the register
    Ç€         run the above link on €ach permutation,
      i1       find the index of the first "successful" permutation,
        ị®K    and ®ecall the permutation list to get the actual ordering at that ịndex, separating output by spaces

```
> 2 votes

# Answer
# Husk, 10 bytes

```
←fΛ~=o_←→P

```

Try it online!

### Explanation

```
←fΛ~=(_←)→P  -- example input: ["Xbc","Abc","Cba"]
          P  -- all permutations: [["Xbc","Abc","Cba"],…,[Xbc","Cba","Abc"]]
 f           -- filter by the following (example with ["Xbc","Cba","Abc"])
  Λ          -- | all adjacent pairs ([("Xbc","Cba"),("Cba","Abc")])
   ~=        -- | | are they equal when..
     (_←)    -- | | .. taking the first character lower-cased
         →   -- | | .. taking the last character
             -- | : ['c'=='c','a'=='a'] -> 4
             -- : [["Xbc","Cba","Abc"]]
←            -- take the first element: ["Xbc","Cba","Abc"]

```

### Alternatively, 10 bytes

We could also count the number of adjacent pairs which satisfy the predicate (`#`), sort on (`Ö`) that and take the last element () for the same number of bytes:

```
→Ö#~=o_←→P

```

Try it online!
> 2 votes

# Answer
# Mathematica 236 chars

Define the list of cities:

```
d = {"Neapolis", "Yokogama", "Sidney", "Amsterdam", "Madrid", "Lviv", "Viden", "Denver"}

```

Find the path that includes all cities:

```
c = Characters; f = Flatten;
w = Outer[List, d, d]~f~1;
p = Graph[Cases[w, {x_, y_} /;x != y \[And] (ToUpperCase@c[x][[-1]]== c[y][[1]]) :> (x->y)]];
v = f[Cases[{#[[1]], #[[2]], GraphDistance[p, #[[1]], #[[2]]]} & /@  w, {_, _, Length[d] - 1}]];
FindShortestPath[p, v[[1]], v[[2]]]

```

Output:

```
{"Lviv", "Viden", "Neapolis", "Sidney", "Yokogama", "Amsterdam","Madrid", "Denver"}

```

The above approach assumes that the cities can be arranged as a path graph.

---

The graph p is shown below:
> 1 votes

# Answer
# C, 225

```
#define S t=v[c];v[c]=v[i];v[i]=t
#define L(x)for(i=x;i<n;i++)
char*t;f;n=0;main(int c,char**v){int i;if(!n)n=c,c=1;if(c==n-1){f=1;L(2){for(t=v[i-1];t[1];t++);if(v[i][0]+32-*t)f=n;}L(f)puts(v[i]);}else L(c){S;main(c+1,v);S;}}

```

Run with country names as the command line arguments

Note:

* brute force generation of permutations
* for checking it assumes that country names start with an upper case and end in lower case.
* assumes there is only one answer
* In C, assumes that the \**v array of main() is writable
> 1 votes

# Answer
## J, 69 65 60 59 54 characters

Somewhat off the pace.

```
{.l\:+/2=/\|:tolower;"2({.,{:)@>l=.(i.@!@#A.]);:1!:1[1

```

Example:

```
   {.l\:+/2=/\|:tolower;"2({.,{:)@>l=.(i.@!@#A.]);:1!:1[1
Neapolis Yokogama Sydney Amsterdam Madrid Lviv Viden Denwer
+----+-----+--------+------+--------+---------+------+------+
|Lviv|Viden|Neapolis|Sydney|Yokogama|Amsterdam|Madrid|Denwer|
+----+-----+--------+------+--------+---------+------+------+

```
> 1 votes

# Answer
**C#, 398**

And here is C# with Linq 5 cents

```
IEnumerable<string>CityNameGame(string[]input){var cities=new List<string>(input);string lastCity=null;while(cities.Any()){var city=lastCity??cities.First();lastCity=cities.First(name=>string.Equals(city.Substring(city.Length-1),name.Substring(0,1),StringComparison.CurrentCultureIgnoreCase));cities.RemoveAll(name=>name==city||name==lastCity);yield return string.Format("{0}→{1}",city,lastCity);}}

```
> 1 votes

# Answer
# C# (.NET Core), ~~374 bytes~~ 302 bytes

```
using System;using System.Linq;class Program{static void Main(string[] s){Func<char, char>u=(c)=>char.ToUpperInvariant(c);var S="";int I=0,C=s.Count();for(;I<C;I++)S=Array.Find(s,x=>u(s[I][0])==u(x[^1]))==null?s[I]:S;for(I=0;I<C;I++){Console.Write(S+" ");S=C>I?Array.Find(s,x=>u(S[^1])==u(x[0])):"";}}}

```

Try it online!

```
using System;
using System.Linq;

class Program
{
    static void Main(string[] s)
    {
        Func<char, char> u = (c) => char.ToUpperInvariant(c);
        var S = "";
        int I = 0, C = s.Count();

        for (; I < C; I++)
            S = Array.Find(s, x => u(s[I][0]) == u(x[^1])) == null ? s[I] : S;

        for (I = 0; I < C; I++)
        {
            Console.Write(S + " ");
            S = C > I ? Array.Find(s, x => u(S[^1]) == u(x[0])) : "";
        }
    }
}

```

---

Try it online!

```
using System;
using System.Linq;

var S = "";
int I = 0, C = s.Count();
for (; I < C; I++)
    S = Array.Find(
        s, x =>
        s[I].Substring(0, 1).ToUpper() == x.Substring(x.Length - 1).ToUpper()
    ) == null ?
    s[I] :
    S;
for (I = 0; I < C; I++) {
    Console.Write(S + " ");
    S = C > I ? Array.Find(s, x => S.Substring(S.Length - 1).ToUpper() == x.Substring(0, 1).ToUpper()) : "";
}

```
> 1 votes

# Answer
# Japt `-g`, 12 bytes

```
á kÈäÈÌkYÎÃd

```

Try it
> 1 votes

# Answer
# K, 96

```
{m@&{&/(~).'+(,_1_1#'x),,-1_-1#'x}@'$m:{$[x=1;y;,/.z.s[x-1;y]{x,/:{x@&~x in y}[y;x]}\:y]}[#x;x]}

```

.

```
k){m@&{&/(~).'+(,_1_1#'x),,-1_-1#'x}@'$m:{$[x=1;y;,/.z.s[x-1;y]{x,/:{x@&~x in y}[y;x]}\:y]}[#x;x]}`Neapolis`Yokogama`Sidney`Amsterdam`Madrid`Lviv`Viden`Denver
Lviv Viden Neapolis Sidney Yokogama Amsterdam Madrid Denver

```
> 0 votes

---
Tags: code-golf, graph-theory, sorting
---


title: Alphabet Diamond

text:
# Question
Title: Alphabet Diamond
You've seen the amazing alphabet triangle, the revenge of the alphabet triangle and now it's time for the revenge of the revenge of the alphabet triangle!

**Introducing...**

***THE ALPHABET DIAMOND!***

Your task is to output this exact text, lowercase/uppercase does not matter, though newlines do:

```
bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb
cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc
defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed
efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe
fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf
ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg
hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih
ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji
jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj
klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk
lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml
mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm
nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon
opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo
pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp
qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq
rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr
stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts
tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut
uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu
vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv
wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw
xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx
yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy
zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz
yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy
xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx
wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw
vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv
uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu
tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut
stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts
rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr
qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq
pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp
opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo
nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon
mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm
lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml
klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk
jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj
ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji
hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih
ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg
fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf
efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe
defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed
cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc
bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb

```

## This is code-golf, lowest bytecount wins.

**Rules:**

1. Standard loopholes are disallowed.
2. `a` must be the center of the alphabet diamond.

# Answer
> 18 votes
# 05AB1E, ~~13~~ 12 bytes

```
A27FÀDûˆ}¯û»

```

Try it online!

**Explanation**

```
A              # push alphabet
 27F           # 27 times do
    À          # rotate alphabet left
     Dû        # create a palendromized copy
       ˆ       # add to global list
        }      # end loop
         ¯     # push global list
          û    # palendromize list
           »   # merge list on newline
               # implicit output

```

# Answer
> 29 votes
# Vim, ~~62~~, 60 keystrokes

```
:se ri|h<_<cr>jjYZZPqqx$pYpq26@qdjyH:g/^/m0<cr>VP:%norm DPA<C-v><C-r>"<C-v><esc>x<cr>

```

Drawing on inspiration from Lynn's awesome vim answer to take the idea of stealing the alphabet from the help docs.

You can watch it happen in real time as I struggle to remember the right sequence of keystrokes!

Note that this gif is *slightly* outdated because it produces the wrong output, and I haven't gotten around to re-recording it yet.

# Answer
> 8 votes
# MATL, 14 bytes

```
2Y226Zv27Zv!+)

```

Try it online!

```
2Y2     % Push string 'abc...z'
26Zv    % Push symmetric range [1 2 ... 25 26 25 ... 2 1]
27Zv    % Push symmetric range [1 2 ... 25 26 27 26 25 ... 2 1]
!       % Transpose into a column
+       % Addition with broadcast. Gives a matrix of all pairwise additions:
        % [  2  3 ... 26 27 26 ...  3  2
             3  4 ... 27 28 27 ...  4  3
             ...
            27 28 ... 51 52 51 ... 28 27
            28 29 ... 52 53 52 ... 29 28
            27 28 ... 51 52 51 ... 28 27
             ...
             2  3 ... 26 27 26 ...  3  2 ]
)       % Index modularly into the string. Display implicitly

```

# Answer
> 6 votes
# PHP, 129 Bytes

```
for(;++$i<27;)$o.=($s=($f=substr)($r=join(range(a,z)),$i,26-$i)).$t.strrev($s.$t=$f($r,0,$i))."\n";echo$o.$f($o,0,51).strrev($o);

```

# Answer
> 5 votes
## Haskell, 75 bytes

```
g=(++)<*>reverse.init
unlines$g$g.take 26.($cycle['a'..'z']).drop<$>[1..27]

```

How it works:

```
g=(++)<*>reverse.init    -- helper function that takes a list and appends the
                         -- reverse of the list with the first element dropped, e.g.
                         -- g "abc"  -> "abcba"

             <$>[1..27]  -- map over the list [1..27] the function that
           drop          -- drops that many elements from
    ($cycle['a'..'z'])   -- the infinite cycled alphabet and
   take 26               -- keeps the next 26 chars and
  g                      -- appends the reverse of itself

                         -- now we have the first 27 lines

 g                       -- do another g to append the lower half
unlines                  -- join with newlines

```

# Answer
> 5 votes
# Jelly, 13 bytes

```
Øaṙ1ṭṙJ$ŒBŒḄY

```

Try it online!

## Explanation

```
Øaṙ1ṭṙJ$ŒBŒḄY  Main link. No arguments
Øa             Get the lowercase alphabet
  ṙ1           Rotate left by 1
    ṭ          Append to
       $       Monadic chain
      J          Indices of the alphabet [1, 2, ..., 26]
     ṙ           Rotate the alphabet by each
        ŒB     Bounce each rotation
          ŒḄ   Bounce the rotations
            Y  Join with newlines and print implicitly

```

# Answer
> 5 votes
# C, 76 bytes

Function, to be called as below. Prints capital letters.

```
f(i){for(i=2756;--i;)putchar(i%52?90-(abs(i%52-26)+abs(i/52-26)+25)%26:10);}

//call like this
main(){f();}

```

Simple approach, add the x and y distances from the centre of the square, plus an offset of 25 for the `a` in the middle, take modulo 26 and subract from `90`, the ASCII code for `Z`. Where `i%52`==0 a newline ASCII `10` is printed.

# Answer
> 5 votes
# R, 71 bytes

```
cat(letters[outer(c(1:27,26:1),c(0:25,24:0),"+")%%26+1],sep="",fill=53)

```

`outer` creates a matrix with the indices of the letters, `letters[...]` then creates a vector with the correct letters in. `cat(...,sep="",fill=53)` then prints it out with the desired formatting.

# Answer
> 5 votes
# Jelly, 11 bytes

```
27RØaṙŒḄŒBY

```

Explanation:

```
27R          range of 1...27
   Øa        the alphabet
     ṙ       rotate
      ŒḄŒB   bounce in both dimensions
          Y  join on newline

```

# Answer
> 3 votes
# JavaScript (ES6), ~~97~~ 96 bytes

*Saved 1 byte thanks to @user81655*

```
R=(n,s=25,c=(n%26+10).toString(36))=>s?c+R(n+1,s-1)+c:c
C=(n=1,r=R(n))=>n<27?r+`
${C(n+1)}
`+r:r

```

Two recursive functions; `C` is the one that outputs the correct text. Try it here:

```
R=(n,s=25,c=(n%26+10).toString(36))=>s?c+R(n+1,s-1)+c:c
C=(n=1,r=R(n))=>n<27?r+`
${C(n+1)}
`+r:r

console.log(C())
```

# Answer
> 3 votes
# Python 2, ~~96~~ 85 bytes

Printing the uppercase version (saves 1 byte).

```
R=range
for i in R(53):print''.join(chr(90-(abs(j-25)+abs(i-26)-1)%26)for j in R(51))

```

previous solution with help from muddyfish

```
s="abcdefghijklmnopqrstuvwxyz"*3
for i in range(53):j=min(i,52-i);print s[j+1:j+27]+s[j+25:j:-1]

```

# Answer
> 3 votes
## Batch, 255 bytes

```
@echo off
set l=abcdefghijklmnopqrstuvwxyz
set r=yxwvutsrqponmlkjihgfedcba
for /l %%i in (1,1,27)do call:u
for /l %%i in (1,1,25)do call:l
:l
set r=%r:~2%%l:~-1%.
set l=%l:~-2%%l:~0,-2%
:u
set r=%l:~-1%%r:~0,-1%
set l=%l:~1%%l:~0,1%
echo %l%%r%

```

Explanation: The subroutine `u` rotates the alphabet outwards by one letter from the centre, which is the pattern used in the top half of the desired output. The subroutine `l` rotates the alphabet inwards by two letters. It then falls through into the `u` subroutine, achieving an effective single letter inward rotation. Finally the last line is printed by allowing the code to fall through into the `l` subroutine.

# Answer
> 3 votes
## Perl, 77 bytes

Requires `-E` at no extra cost.

Pretty standard approach... I don't like the calls to reverse I think there's likely a more maths based approach to this, will see how I get on!

```
@a=((a..z)x3)[$_..$_+26],$a=pop@a,(say@a,$a,reverse@a)for 1..26,reverse 1..25

```

### Usage

```
perl -E '@a=((a..z)x3)[$_..$_+26],$a=pop@a,(say@a,$a,reverse@a)for 1..26,reverse 1..25'

```

# Answer
> 3 votes
# Python 3, 119 bytes

I tried to exploit the two symmetry axes of the diamond, but this ended up more verbose than Karl Napf's solution.

```
A='abcdefghijklmnopqrstuvwxyz'
D=''
for k in range(1,27):
 D+=A[k:]+A[:k]
 D+=D[-2:-27:-1]+'\n'
print(D+D[:51]+D[::-1])

```

# Answer
> 3 votes
# Haskell, ~~67~~ 66 bytes

```
unlines[[toEnum$mod(-abs j-abs i)26+97|j<-[-25..25]]|i<-[-26..26]]

```

# Answer
> 3 votes
## C, 252 bytes

```
#define j q[y]
#define k(w,v) (v<'z')?(w=v+1):(w=97)
char q[28][52],d;main(){int y,x=1;y=1;j[0]=98;j[50]=98;for(;y<27;y++){for(;x<26;x++){(x<1)?(k(d,q[y-1][50])):(k(d,j[x-1]));j[50-x]=d;j[x]=d;}x=0;j[51]=0;puts(j);}strcpy(j,q[1]);for(;y;y--)puts(j);}

```

Formatted, macro-expanded version, which is hopefully more intelligible:

```
#define j q[y]
#define k(w,v) (v<'z')?(w=v+1):(w=97)
char q[28][52],d;
main(){
int y,x=1;
y=1;
q[1][0]=98;q[1][50]=98;
//98 takes one less byte to type than the equivalent 'b'
for(;y<27;y++){
    for(;x<26;x++){
        (x<1)?
            (k(d,q[y-1][50]))
            :(k(d,q[y][x-1]));
        q[y][50-x]=d;
        q[y][x]=d;
        }
    x=0;
    q[y][51]=0;
    puts(q[y]);
    }
strcpy(q[y],q[1]);
for(;y;y--)puts(q[y]);
}

```

I know this can't win, but I had fun trying. This is my first ever attempt at code golf.

# Answer
> 2 votes
## Pyke, ~~23~~ ~~22~~ 21 bytes

```
GV'th+jj_t+j)K]0n'JOX

```

Try it here!

```
GV          )         - repeat 26 times, initially push alphabet.
  'th+                -  push tos[1:]+tos[0]
      j               -  j = tos
       j              -  push j
        _t+           -  push pop+reversed(pop)[1:]
           j          -  push j
             K        - pop
              ]0      - list(stack)
                n'JOX - print "\n".join(^),
                      - splat ^[:-1]

```

# Answer
> 2 votes
# VBA, <sub>~~109~~ ~~105~~</sub> 78 Bytes

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

```
For i=-26To 26:For j=-25To 25:?Chr(65+(52-(Abs(j)+Abs(i)))Mod 26);:Next:?:Next

```

# Answer
> 2 votes
# Charcoal, ~~24~~ 21 bytes

*-3 bytes thanks to ASCII-only.*

```
Ｆ²⁷«Ｐ✂×β³⊕ι⁺ι²⁷↓»‖Ｂ↓→

```

Try it online! Link is to verbose version.

...I need to work on my Charcoal-fu. :P

# Answer
> 2 votes
## C++, ~~191~~ ~~179~~ ~~166~~ ~~165~~ 139 bytes

-12 bytes thanks to Kevin Cruijssen
-14 bytes thanks to Zacharý -26 bytes thanks to ceilingcat

```
#import<cstdio>
#define C j;)putchar(97+j
main(){for(int i=0,j,d=1;i<53;d+=i++/26?-1:1){for(j=d;26+d>C++%26);for(j--;d<=--C%26);puts("");}}

```

# Answer
> 2 votes
**VBA (Excel) , 116 Bytes**

```
Sub a()
For i=-26To 26
For j=-25To 25
b=b & Chr(65+(52-(Abs(j)+Abs(i))) Mod 26)
Next
Debug.Print b
b=""
Next
End Sub

```

Following Sir Joffan's Logic. :D

# Answer
> 2 votes
# PowerShell, 64 bytes

```
1..27+26..1|%{$y=$_
-join(0..25+24..0|%{[char](97+($_+$y)%26)})}

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), ~~128~~ ~~115~~ 114 bytes

```
a='abcdefghijklmnopqrstuvwxyz'
for(o=[i=27];i--;)o[26-i]=o[26+i]=(a=(p=a.slice(1))+a[0])+[...p].reverse().join``
o

```

# Answer
> 1 votes
# Groovy - 103 97 bytes

I realise there are cleverer ways of doing this but...

```
{t=('a'..'z').join();q={it[-2..0]};c=[];27.times{t=t[1..-1]+t[0];c<<t+q(t)};(c+q(c)).join('\n')}
```

When run the result of the script is the requested answer.

(Thanks to carusocomputing for the tip on saving 7 bytes).

Updated example accordingly on:

See http://ideone.com/MkQeoW

# Answer
> 1 votes
## Racket 293 bytes

```
(let*((ls list->string)(rr reverse)(sr(λ(s)(ls(rr(string->list s))))))(let p((s(ls(for/list((i(range 97 123)))(integer->char i))))
(n 0)(ol'()))(let*((c(string-ref s 0))(ss(substring s 1 26))(s(string-append ss(string c)(sr ss))))(if(< n 53)(p s(+ 1 n)(cons s ol))
(append(rr ol)(cdr ol))))))

```

Ungolfed:

```
(define (f)
  (define (sr s)           ; sub-fn reverse string;
    (list->string
     (reverse
      (string->list s))))
  (let loop ((s
              (list->string
               (for/list
                   ((i
                     (range 97 123)))
                 (integer->char i))))
             (n 0)
             (ol '()))
    (define c (string-ref s 0))
    (define ss (substring s 1 26))
    (set! s (string-append
             ss
             (string c)
             (sr ss)))
    (if (< n 53)
        (loop s (add1 n) (cons s ol))
        (append (reverse ol) (rest ol)))))

```

Testing:

```
(f)

```

Output:

```
'("bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb"
  "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc"
  "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed"
  "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe"
  "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf"
  "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg"
  "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih"
  "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji"
  "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj"
  "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk"
  "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml"
  "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm"
  "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon"
  "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo"
  "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp"
  "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq"
  "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr"
  "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts"
  "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut"
  "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu"
  "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv"
  "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw"
  "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx"
  "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy"
  "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz"
  "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"
  "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb"
  "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc"
  "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed"
  "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe"
  "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf"
  "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg"
  "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih"
  "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji"
  "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj"
  "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk"
  "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml"
  "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm"
  "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon"
  "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo"
  "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp"
  "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq"
  "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr"
  "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts"
  "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut"
  "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu"
  "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv"
  "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw"
  "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx"
  "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy"
  "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz"
  "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"
  "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb"
  "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"
  "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz"
  "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy"
  "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx"
  "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw"
  "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv"
  "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu"
  "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut"
  "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts"
  "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr"
  "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq"
  "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp"
  "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo"
  "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon"
  "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm"
  "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml"
  "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk"
  "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj"
  "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji"
  "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih"
  "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg"
  "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf"
  "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe"
  "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed"
  "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc"
  "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb"
  "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"
  "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz"
  "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy"
  "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx"
  "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw"
  "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv"
  "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu"
  "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut"
  "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts"
  "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr"
  "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq"
  "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp"
  "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo"
  "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon"
  "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm"
  "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml"
  "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk"
  "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj"
  "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji"
  "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih"
  "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg"
  "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf"
  "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe"
  "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed"
  "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc"
  "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb")

```

# Answer
> 1 votes
# Pyth, ~~21~~ 19 bytes

```
j+PKm+PJ.<Gd_JS27_K

```

Try it online!

**Explanation:**

```
j+PKm+PJ.<Gd_JS27_K   expects no input

j                     joins on new line
 +   +                joins two strings
  P   P               prints everything but the last element
   K                  initialize K and implicitly print
    m                 for...in loop, uses d as iterator variable
       J              initialize J and implicitly print
        .<            cyclically rotate
          G           initialized to the lowercase alphabet
           d          iterating variables of m
            _    _    reverse
             J        call J
              S27     indexed range of 27
                  K   call K

```

# Answer
> 1 votes
# SOGL V0.12, 10 bytes

```
zl{«:}«¹╬,

```

Try it Here!

Explanation:

```
z           push the lowercase alphabet
 l{  }      repeat length times
   «          put the 1st letter at the end
    :         duplicate
      «     put the 1st letter at the end (as the last thing called is duplicate)
       ¹    wrap the stack in an array
        ╬,  quad-palindromize with 1 X and Y overlap

```

# Answer
> 1 votes
# Java 10, ~~154~~ ~~153~~ ~~151~~ ~~148~~ ~~147~~ ~~142~~ 141 bytes

```
v->{var r="";for(int i=0,j,d=1;i<53;d+=1-++i/27*2){for(j=d;j<26+d;)r+=(char)(j++%26+97);for(j--;j>d;)r+=(char)(--j%26+97);r+="\n";}return r;}

```

Port of *@HatsuPointerKun* C++ answer, so make sure to upvote him/her as well.
-8 bytes thanks to *@ceilingcat*.
-1 byte thanks to *@Grimmy*.

Try it here.

# Answer
> 1 votes
# Kotlin, 106 bytes

```
{(0..52).map{i->(0..50).map{j->print((90-((Math.abs(j-25)+Math.abs(i-26)-1)+26)%26).toChar())}
println()}}

```

## Beautified

```
{
    (0..52).map {i->
        (0..50).map {j->
            print((90 - ((Math.abs(j - 25) + Math.abs(i - 26) - 1)+26) % 26).toChar())
        }
        println()
    }
}

```

## Test

```
var v:()->Unit =
{(0..52).map{i->(0..50).map{j->print((90-((Math.abs(j-25)+Math.abs(i-26)-1)+26)%26).toChar())}
println()}}

fun main(args: Array<String>) {
    v()
}

```

TryItOnline

Port of @Karl Napf's answer

# Answer
> 1 votes
# uBASIC, 86 bytes

```
0ForI=-26To26:ForJ=-25To25:?Left$(Chr$(65+(52-(Abs(J)+Abs(I)))Mod26),1);:NextJ:?:NextI

```

Try it online!

# Answer
> 1 votes
# MY-BASIC, 89 bytes

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

```
For i=-26 To 26
For j=-25 To 25
Print Chr(65+(52-(Abs(j)+Abs(i)))Mod 26)
Next
Print;
Next

```

Try it online!

# Answer
> 1 votes
# Visual Basic .NET (Mono), 160 bytes

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

```
Module M
Sub Main
Dim S,I,J
For I=-26To 26
S=""
For J=-25To 25
S+=Chr(65+(52-(Math.Abs(j)+Math.Abs(i)))Mod 26)
Next
Console.WriteLine(S)
Next
End Sub
End Module

```

Try it online!

# Answer
> 1 votes
# Yabasic, 74 bytes

Now I'm telling you that this challenge *BASIC*. /sarcasm

```
For i=-26To 26
For j=-25To 25
?Chr$(65+Mod(Abs(j)+Abs(i),26));
Next
?
Next

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
Aā._Ć€ûû»

```

Try it online!

# Answer
> 1 votes
# PowerShell v6+, 59 bytes

```
1..27+26..1|%{-join(('a'..'z'*3)[$_..($_+25)+($_+24)..$_])}

```

Try it online!

Ranges on ranges on ranges.

# Answer
> 1 votes
# FALSE, 137 bytes

```
1c:53 0$d:[65@$0=~\1-\][@@\c;+d;1=[1_c:]?$26=[%0 1d:]?$1_=[%25]?$@+1b:51[$0=~][$26=[1_b:]?\$,b;+[$a:$64=[90a:]?91=[65a:]?a;]!\1-]#%%10,]#

```

Try it online!

# Answer
> 1 votes
# Vyxal `jr`, 11 bytes

```
27ƛkaǓøm;øm

```

Try it Online!

Explanation:

```
27ƛ     ;    # For each number x in range [1..27]:
   ka        #   Lowercase alphabet
     Ǔ       #   Rotate it left x times
      øm     #   Mirror without duplicating middle
         øm  # Mirror without duplicating middle
             # 'j' flag - Join top of stack with newlines and print

```

# Answer
> 0 votes
# J, 48 bytes

```
(}:@|.,])(],.}.@|."1)(1+i._26)|."0 1 a.{~97+i.26

```

Try it online!

# Answer
> 0 votes
# Common Lisp, 221 bytes

```
(let((k 26)a(s"~26{~a~}~25{~a~}~%"))(#4=dotimes(i k)(push(code-char(- 90 i))a))(let*((u(append a a a))(b(reverse u)))(#4#(i 27)(#3=format t s #1=(nthcdr(1+ i)u)#2=(nthcdr(- k i)b)))(rotatef u b)(#4#(i k)(#3#t s #2##1#))))

```

Try it online!

More readable version:

```
(let (a)                             ; variable to hold the alphabet
  (dotimes (i 26)                    ; creation of the alphabet as list
    (push (code-char (- 90 i)) a))
  (let* ((u (append a a a))          ; make three copies of a
         (b (reverse u)))                ; reverse u
    (dotimes (i 27)                  ; first half: form a line with two parts
       (format t "~26{~a~}~25{~a~}~%" (nthcdr (1+ i) u) (nthcdr (- 26 i) b)))
    (rotatef u b)                    ; exchange the role of u and b
    (dotimes (i 26)                  ; second half: exchange the two parts
       (format t "~26{~a~}~25{~a~}~%" (nthcdr (- 26 i) b) (nthcdr (1+ i) u)))))

```

# Answer
> 0 votes
# Japt `-R`, ~~15~~ 12 bytes

```
;26ÆCé´T êÃê

```

Test it

```
;26ÆCé´T êÃê
 26Æ             :Map the range [0,26)
;   C            :  Lowercase alphabet
     é           :  Rotate right by
      ´T         :    T (initially 0) prefix decremented
         ê       :  Palindromise
          Ã      :End map
           ê     :Palindromise
                 :Implicit output joined with newlines

```

# Answer
> 0 votes
# Dyalog APL, 31 bytes

```
{⍵⍪1 0↓⊖⍵}{⍵,0 1↓⌽⍵}↑(⌽∘⎕A)¨⍳27

```

Try it online!

# Answer
> 0 votes
# q/kdb+, 51 bytes

**Solution:**

```
-1 .Q.a t{rotate[y;x]x,1_(|)x}/:(1+t),1,(-)t:(!)26;

```

**Explanation:**

Build the range of `1..26,1,0,-1..-25`, feed this into a lambda that rotates the range 0..25 and indexes in at the range `0..25,24..0`... Then use this to index into the lowercase alphabet.

```
-1 .Q.a t{rotate[y;x]x,1_reverse x}/:(1+t),1,neg t:til 26; / ungolfed
-1                                                       ; / print to stdout and swallow return value
                                                 t:til 26  / store range of 0..25 in variable t
                                             neg           / negate (0..-25)
                                           1,              / prepend 1
                                     (1+t),                / prepend 1+t (1..26)
        t{                        }/:                      / lambda function with parameters t, and each-right
                         reverse x                         / x = t = 0..25, reversed is 25..0
                       1_                                  / 1 drop, so 24..0
                     x,                                    / prepend x, so 0..25,24..0
          rotate[y;x]                                      / rotate x by y (rotate[1;"abc"] -> "bca")
   .Q.a                                                    / index into alphabet at these indices

```

**Notes:**

Feels like it should be able to be golfed further, building the ranges seems clunky.

# Answer
> 0 votes
# Recursiva, ~~44 25 21~~ 19 bytes

```
{p+)'a'"Pp+J''_Q)}}

```

Try it online!

# Explanation:

```
{p+)'a'"Pp+J''_Q)}}
{                     - For each
 p+)'a'               - 'abc..xyzazyx..abc'
       "              - Iteration command begin
        P             - Print
         p            - palindromize 'cde..xyzabazyx..cde'
          +           - concatenate 'cde..xyzab'
           J''        - join with nothing 'cde..xyza'
              _       - reverse ['cde...xyz', 'a']
               Q)}    - split ) at } ['a','cdef..xyz']
                  }   - current element (say 'b' for 2nd iteration)

```

# Answer
> 0 votes
# Retina, 166 bytes

```

bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb____________________________________________________
+(`([a-z]+)_(_+)
$1¶$1$2¶$1
(.)(.{24})(.)(.{24})._
$2$3$1$3$4

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Classic), 21 bytes

```
(⍉⊢⍪1↓⊖)⍣2⍉1↓27 27⍴⎕a
```

Try it online!

With the alphabet (`⎕a`) fill in row-major order a 27x27 matrix (`27 27⍴`), then drop the first row (`1↓`) and transpose ().

Do this twice (`⍣2`): concatenate to the bottom () of this matrix () a vertically reversed copy () without its first row (`1↓`) and transpose () the result.

# Answer
> 0 votes
# Stax, 13 bytes

```
éÑ8╟╘"╧ö↑D☼▓}

```

Run and debug it

# Answer
> 0 votes
# Elixir, 111 bytes

```
import Enum
c=?a..?z
a=map 1..26,&(drop(c,&1)++slice c,0,&1)
map a++[hd a]++reverse(a),&IO.puts&1++tl reverse&1

```

Try it online!

Feel like there are some key savings I'm missing here...

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


title: Draw an alphabet party hat

text:
# Question
Title: Draw an alphabet party hat
Your task is to print this exact text:

```
            z
            yz
           xyz
           wxyz
          vwxyz
          uvwxyz
         tuvwxyz
         stuvwxyz
        rstuvwxyz
        qrstuvwxyz
       pqrstuvwxyz
       opqrstuvwxyz
      nopqrstuvwxyz
      mnopqrstuvwxyz
     lmnopqrstuvwxyz
     klmnopqrstuvwxyz
    jklmnopqrstuvwxyz
    ijklmnopqrstuvwxyz
   hijklmnopqrstuvwxyz
   ghijklmnopqrstuvwxyz
  fghijklmnopqrstuvwxyz
  efghijklmnopqrstuvwxyz
 defghijklmnopqrstuvwxyz
 cdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

```

**Case does not matter.**

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 6 votes
# Cheddar, ~~50~~ ~~45~~ ~~42~~ 37 bytes

```
25|>0=>i->print" "*(i/2|0)+(65+i)@"90

```

Straightforward, but utilizes cheddar's consise ranging syntax (both numerical and alphabetical)

Try it online!

## Explanation

```
25 |> 0 =>    // Map range [0, 26) (i.e. [25, 0] reversed) over....
   i ->
     print    // Prints in it's own line...
     " " * (i/2 |0) +     // Number of spaces is floor(n/2).
                          // `|0` for flooring is hack from JS
     (65 + i) @" 90       // Char code range is this

```

`65` is char code for `A` and `90` for `Z`

# Answer
> 5 votes
# 05AB1E, ~~15~~ 13 bytes

```
A.svy12N;ï-ú,

```

Try it online! (slightly different from above as `ú` isn't on TIO yet)

**Explanation**

1. Push alphabet
2. Compute the suffixes of the alphabet
3. Prepend 12-index/2 spaces
4. Print

# Answer
> 4 votes
# Python 2, 70 bytes

Ported from Emigna's answer, -2 bytes for replacing `-i-1` with `~i`

```
for i in range(26):print' '*(12-i/2)+"abcdefghijklmnopqrstuvwxyz"[~i:]

```

# Answer
> 4 votes
# R, 67 66 59 bytes

EDIT: Saved a couple of bytes thanks to @rturnbull

```
for(i in 25:0)cat(rep(" ",i/2),letters[i:25+1],"\n",sep="")

```

Exploiting the fact that any number passed to the `rep` function is automatically rounded down to the closest integer (e.g. `rep("*",1.99) => "*"`) which means that the actual sequence passed is `floor(13-1:26/2)`:

```
12 12 11 11 10 10  9  9  8  8  7  7  6  6  5  5  4  4  3  3  2  2  1  1  0  0

```

# Answer
> 4 votes
# 05AB1E, 5 bytes

```
A.s.c

```

Try it online!

```
A.s.c
A     Push 'abcdefghijklmnopqrstuvwxyz'
 .s   Push suffixes starting from the shortest one
   .c Centralize focused on the left

```

# Answer
> 3 votes
# JavaScript (ES6), ~~85~~ ~~75~~ ~~69~~ 68 bytes

```
for(s=a='',x=36;--x>9;)s+=` `.repeat(x/2-5)+(a=x.toString(36)+a)+`
`

```

*-1 byte thanks to @l4m2*.

# Answer
> 3 votes
## Python 2, 52 bytes

```
n=26;s=''
while n:n-=1;s=chr(97+n)+s;print n/2*' '+s

```

Accumulates the string `s` to print and updates the number of leading spaces `n/2`. A `while` loop terminating at `0` is a rare numerical loop than beats an `exec` loop (53 bytes):

```
n=26;s=''
exec"n-=1;s=chr(97+n)+s;print n/2*' '+s;"*n

```

Also a 53-byte alternative:

```
s=''
exec"s=chr(122-len(s))+s;print s.center(26);"*26

```

# Answer
> 3 votes
# Pyth, 15 bytes

```
j_m+*/d2\ >GdUG

```

A program that prints the result to STDOUT.

Try it online

**How it works**

```
j_m+*/d2\ >GdUG  Program
             UG  Yield [1, 2, 3, 4, ..., 26]
  m              Map over the range with variable d:
          >Gd      Yield alphabet with first d-1 letters discarded
   +               Prepend
     /d2             d//2
    *   \            spaces
 _               Reverse
j                Join on newlines
                 Implicitly print

```

# Answer
> 2 votes
# Jelly, ~~15~~ 13 bytes

-2 bytes thanks to @miles (formed a niladic chain I suspected existed but did not form)

```
ØaJ’H⁶ẋżṫJ$ṚY

```

**TryItOnline!**

### How?

```
ØaJ’H⁶ẋżṫJ$ṚY - Main link
Øa            - alphabet yield -> ['a', 'b', 'c', ..., 'y', 'z']
  J           -    range(length)      -> [1, 2, 3, ..., 25, 26]
   ’          -    decrement          -> [0, 1, 2, ..., 24, 25]
    H         -    halve              -> [0,.5  1, ..., 12, 12.5]
     ⁶        -    literal [' ']
      ẋ       -    repeat list        -> [[], [], [' '], ..., 12x' ', 12x' ']
          $   - last two links as a monad
         J    -     range(length)     -> [1, 2, 3, ..., 25, 26]
        ṫ     -     tail (vectorises) -> [['a'-'z'], ['b'-'z'], ..., ['y','z'], ['z']]
       ż      - zip
              -> [[[],['a'-'z']], [[],['b'-'z']], ..., [12x' ',['y','z']], [12x' ',['z]]]
           Ṛ  - reverse whole array
            Y - join with line feeds (implicit print)

```

# Answer
> 2 votes
# Brain-Flak, 244 bytes

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

```

Try it online!

---

This should be readable enough as is. If you need it, I have a full explanation:

```
push 122 (z): ((((((()()()()())){}{}){}){}()){})
push 26:      ((((()()()){}){}()){})
loop 26 times (i = 25..0): {
 (
  i--, push to b stack:({}[()]<>)
  <
   put 122 from a stack under i: ({}<(<>({})<>)>)
   i times push letter-1: {({}[()]<(({})[()])>)}
   replace top 0 with 26-i: ({}({})<>[({})]<>(((()()()){}){}){}())
   devide by two: ((<>)<>{<({}[()])><>([{}]())<>}<>[{}]<>{})
   add spaces: {({}[()]<((((()()()()){}){}){})>)}
   push 10 (\n): ((()()()()()){})
  >
  flip stack back: <>
 push i--: )
}
flip to results stack: <>

```

# Answer
> 2 votes
# C, ~~72~~ 68 bytes

```
m(i){for(char*k=&k[i=26];i;printf("%*c%s\n",--i/2+1,0,k))*--k=64+i;}

```

# Answer
> 2 votes
# Stax, 7 bytes

```
ô2òΘé8└

```

Run and debug it

# Answer
> 2 votes
# Vyxal `C`, 4 bytes

```
kz¦R

```

Try it Online!

Explanation:

```
kz    # Lowercase backwards alphabet
  ¦   # Prefixes
   R  # Reverse each
      # 'C' flag - Center top of stack, join on newlines, and print

```

# Answer
> 1 votes
# PHP, 71 Bytes

```
for(;++$i<27;)echo str_pad(substr(join(range(a,z)),-$i),26," ",2)."\n";

```

# Answer
> 1 votes
# Turtlèd, ~~70~~ 68 bytes

note the trailing space

```
#abcdefghijklmnopqrstuvwxyz#' -{ -{ +.r_}' l[ l-]d,(*@!' r)(!@*)_}'

```

### Try it online!

## How it works:

```
#abcdefghijklmnopqrstuvwxyz#              Set string var to this value
                            ' -           write space on first grid cell, string pointer-=1
                               {                                    } While cell is space
                                 -                 decrement string pointer
                                  {     }    While cell is space
                                    +.       increment string pointer, write pointed char
                                      r      move right
                                       _     write non-space if pointed char is last char

                                         '[space]   write space on cell
                                           l        move left
                                            [ l-]   move left, pointer-- until cell's space
                                                 d, move down, write character var \
                                                                           (initially *)

                                                   (*     ) if cell is *
                                                     @!     set char var=!
                                                       ' r  write space over *, move right

                                                           (!    ) if cell is !
                                                             @*    set char var=*
                                                               '[space] write space over !

                                                                 _ (explanation below)
                                               write (*|!) if pointed char is last char

                                                                   '[space]    Write space

```

## Human-readable explanation(?):

It uses the string var to contain the alphabet. Each iteration, it reduces the index by one, until it wraps around, and halts, after getting to the last line. For the alternating indents, it uses the char var. Each iteration it checks the char var and flips it. if it was * it shifts right, so the first character aligns, otherwise not, so the last character aligns.

# Answer
> 1 votes
# Java 7 ,~~128~~ 127 bytes

Saved 1 byte.Thanks to kevin.

```
String c(int n,String s,char v,String d){String c="";for(int j=0;j++<(n-1)/2;c+=" ");return n>0?c(--n,s=v+s,--v,d+c+s+"\n"):d;}

```

# ungolfed

```
  class A {

public static void main(String[] args) {
System.out.print(c(26, "", (char)122, ""));
}
static String c(int n, String s, char v, String d){

    String c = "";

    for (int j = 0; j++ < (n - 1)/2; c += " ");

    return n > 0 ? c(--n, s = v + s, --v, d + c + s + "\n" ) : d;
}
}

```

Without an passing 122 in a function

# 132 bytes

```
String c(String s,int n,String d){String c="";int v=96,j=0;for(;j++<(n-1)/2;c+=" ");return n>0?c(s=(char)(v+n--)+s,n,d+c+s+"\n"):d;}

```

# ungolfed

```
  class A{

public static void main(String[] args) {
System.out.print(c("",26,""));

}
static String c(String s, int n, String d) {
    String c = "";
    int v = 96,j=0;
    for (; j++ < (n - 1)/2; c += " ");
    return n > 0 ? c(s = ( char) (v + n--) + s, n, (d + c + s + "\n")) : d;
     }
  }

```

# Answer
> 1 votes
## Perl, 44 bytes

This is a port of @xnor's answer.

```
$n=26;say$"x($n/2),$@=chr(97+$n).$@while$n--

```

Needs `-E` (or `-M5.010`) to run :

```
perl -E '$n=26;say$"x($n/2),$@=chr(97+$n).$@while$n--';

```

# Answer
> 1 votes
## Ruby, 64 bytes

```
(0..26).each{|x|puts' '*(12-x/2)+('a'..'z').to_a[~x..-1].join()}

```

# Answer
> 1 votes
# Common Lisp, SBCL, ~~83~~ 82 bytes

```
(dotimes(i 27)(format t"~26:@<~a~>
"(subseq"ABCDEFGHIJKLMNOPQRSTUVWXYZ"(- 26 i))))

```

### Explanation

```
(dotimes(i 27) ; loop from i=0 to i=26
(format t"~26:@<~a~>
"(subseq"ABCDEFGHIJKLMNOPQRSTUVWXYZ"(- 26 i))))
;print out part of alphabet starting from character number 26-i (counting from zero)
;using justification (~26:@<~a~>) to center with weight 26 characters

```

*-1 using sugestion by ASCII-only to use `<enter>` instead of `~%`*

# Answer
> 1 votes
# Tcl, 92 bytes

```
set a {}
time {set a [format %c [expr 123-[incr i]]]$a;puts [format %[expr 13+$i/2]s $a]} 26

```

Try it online!

~~tcl, 94
```
set a {}
set i 123
time {set a [format %c [incr i -1]]$a;puts [format %[expr 74-$i/2]s $a]} 26

```
demo
~~

##

In the middle of the process, I accidentaly got the italic version of the hat:

# tcl, 94

```
set a {}
set i 123
time {set a [format %c [incr i -1]]$a;puts [format %[expr $i/2-24]s $a]} 26

```

demo

---

~~tcl, 101
```
set a {}
set i 123
while \$i>97 {set a [format %c [incr i -1]]$a;puts [format %[expr ($i-48)/2]s $a]}

```
demo
In the middle of the process, I accidentaly got the italic version of the hat:
tcl, 99
```
set a {}
set i 123
while \$i>97 {set a [format %c [incr i -1]]$a;puts [format %[expr $i/2-24]s $a]}

```~~

~~demo~~

# Answer
> 1 votes
# Japt, 16 bytes

```
;C¬£SpY/2 +CsYÃw ·

```

Try it online!

### Explanation:

```
;C¬£SpY/2 +CsYÃw ·
;C                  // Alphabet shortcut
  ¬                 // Split into an array of chars
   £          Ã     // Map each item X and index Y by:
    SpY/2           //  " " repeated floor(Y/2) times
          +CsY      //  + alphabet.slice(Y)
               w    // Reverse the array of lines
                 ·  // Join with newlines

```

# Answer
> 1 votes
## REXX, 52 bytes

```
do i=1 to 26
  say centre(right(xrange(a,z),i),26)
  end

```

Output:

```
            Z
            YZ
           XYZ
           WXYZ
          VWXYZ
          UVWXYZ
         TUVWXYZ
         STUVWXYZ
        RSTUVWXYZ
        QRSTUVWXYZ
       PQRSTUVWXYZ
       OPQRSTUVWXYZ
      NOPQRSTUVWXYZ
      MNOPQRSTUVWXYZ
     LMNOPQRSTUVWXYZ
     KLMNOPQRSTUVWXYZ
    JKLMNOPQRSTUVWXYZ
    IJKLMNOPQRSTUVWXYZ
   HIJKLMNOPQRSTUVWXYZ
   GHIJKLMNOPQRSTUVWXYZ
  FGHIJKLMNOPQRSTUVWXYZ
  EFGHIJKLMNOPQRSTUVWXYZ
 DEFGHIJKLMNOPQRSTUVWXYZ
 CDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

# Answer
> 1 votes
# Vim, 25 Keystrokes

```
:h<_␍jjYZZPqqPxYPr Yq12@q

```

Where ␍ is the Enter key, also sometimes notated as `<cr>`.

## Explanation

```
:h<_␍jjYZZ                 " get a-z
          P                " initialize by pasting
           qq              " start record macro @q
             Px            " paste and remove the 1st char
               YPr␣        " yank and paste and replace 1st char with space
                   Y       " yank the whole line again
                    q      " end recording
                     12@q  " call macro 12 @q times

```

I am new to ViM though -- I started in November. Wondering if there is a way to merge the initializing `P` with the one in the macro.

What is the "correct" way to test a golfed ViM sequence? I tested with `\vi -u /dev/null`. However in a VM even `:h<_␍` doesn't work. Also not very sure why my ViM will move to the first non space character haha.

P.S. Before I moved to use OS X, I golfed in Hexagony with great tools... Now on OS X I don't do wine and thus not running the great tools for explanations and debugging. So started my journey with ViM!

# Answer
> 1 votes
# C# (.NET Core), 112 bytes

```
()=>string.Join("\n",new int[26].Select((_,i)=>"".PadLeft(12-i/2)+"abcdefghijklmnopqrstuvwxyz".Substring(25-i)))

```

Try it online!

```
()=>string.Join("\n", // OP doesnt want to output a sequence of string...
    new int[26].Select((_,i)=> // yield range from 0 to 25
        "".PadLeft(12-i/2)+ // add spaces to center
            "abcdefghijklmnopqrstuvwxyz".Substring(25-i)))  // remove letters

```

# Answer
> 1 votes
# Perl 5, ~~40~~ 38 bytes

*-2 bytes thanks to @Dom Hastings*

```
say$"x(13+--$x/2),@a[$x..-1]for@a=a..z

```

Try it online!

# Answer
> 1 votes
# T-SQL, 107 bytes

```
DECLARE @t VARCHAR(99)=SPACE(13),@ INT=27a:SET @t=STUFF(@t,@/2,@%2,CHAR(@+95))PRINT @t
SET @-=1IF @>1GOTO a

```

Modifies the string for each line by cramming in the correct letter at the correct position using the SQL fuction `STUFF()`. Formatted:

```
DECLARE @t VARCHAR(99)=SPACE(13), @ INT=27
a:
    SET @t=STUFF(@t,@/2,@%2,CHAR(@+95))
    PRINT @t
    SET @-=1
IF @>1 GOTO a

```

`@/2` uses integer division (no remainder) to determine the position to insert the letter. `@%2` is the `MODULO` function, and flips between 0 (insert the letter) and 1 (overwrite a space).

If you prefer capitial letters, use `CHAR(@+63)` instead (doesn't change our byte count).

# Answer
> 1 votes
# PowerShell, ~~62~~ ~~51~~ 46 bytes

-11 bytes thanks to mazzy reminding me of a function
-5 bytes thanks to mazzy

```
25..0|%{' '*($_-shr1)+-join('a'..'z')[$_..25]}

```

Try it online!

Uses the ~~`-replace`~~ `-shift-right 1` trick to bypass banker's rounding. Additionally, uses a character range to generate the alphabet.

# Answer
> 0 votes
# Haskell (Lambdabot), 73 bytes

```
unlines[([1..div(26-length x)2]>>" ")++x|x<-reverse.init$tails['a'..'z']]

```

same length:

```
do x<-reverse.init$tails['a'..'z'];([1..div(26-length x)2]>>" ")++x++"\n"

```

I use `init.tails` or `tail.inits` with a possible reverse in front in pretty much every challenge; I wish they would add it to Prelude already.

# Answer
> 0 votes
## Pyke, ~~18~~ 12 bytes

```
26Fed*Gi>+)X

```

Try it here!

```
26F       )  -  for i in range(26):
   ed*       -    (i//2)*" "
         +   -   concatenate ↑ and ↓
      Gi>    -    alphabet[i:]
           X - splat(^) (print list reversed with newlines)

```

### Or 10 bytes noncompetitive

```
26DXF2GR>c

```

Try it here!

# Answer
> 0 votes
## Python 2, ~~66~~ 64 bytes

```
i=91;exec'i-=1;print`map(chr,range(i,91))`[2::5].center(26);'*26

```

# Answer
> 0 votes
## QBIC, 57 bytes

```
[25,0,-1|Y=Z[1,a/2|Y=Y+@ |]X=Z[a,25|X=X+$CHR$(65+|c)]?Y+X

```

This one works surprisingly well with QBIC' FOR loops. Explanation (of previous version - same principle applies):

```
[26,1,-1|          Loops from 26 to 1, decrementing 'a'
                   'a' is used to determine the number of spaces per line and the last letter we want to print
Y=Z                Z is always an empty string in this program,
                   Y will hold the spaces we need to center this line
[1,a/2|Y=Y+@ |]    Add a space to Y equal to half the value of 'a', giving us a center alignment
X=Z                X holds the characters we need on this line, reset it
[a,26|             FOR c = a to 26 --> loop over the last part of the alphabet
X=X+$CHR$(64+|c)]  Convert c+64 to ASCII and append
?Y+X               Print the spaces and the letters

<outer FOR loop is closed by QBIC>

```

Output:

```
            Z
            YZ
           XYZ
           WXYZ
          VWXYZ
          UVWXYZ
         TUVWXYZ
         STUVWXYZ
        RSTUVWXYZ
        QRSTUVWXYZ
       PQRSTUVWXYZ
       OPQRSTUVWXYZ
      NOPQRSTUVWXYZ
      MNOPQRSTUVWXYZ
     LMNOPQRSTUVWXYZ
     KLMNOPQRSTUVWXYZ
    JKLMNOPQRSTUVWXYZ
    IJKLMNOPQRSTUVWXYZ
   HIJKLMNOPQRSTUVWXYZ
   GHIJKLMNOPQRSTUVWXYZ
  FGHIJKLMNOPQRSTUVWXYZ
  EFGHIJKLMNOPQRSTUVWXYZ
 DEFGHIJKLMNOPQRSTUVWXYZ
 CDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

# Answer
> 0 votes
# Groovy, 53 bytes

```
('z'..'a').each{println((it..'z').join().center(26))}

```

# Output:

```
            z
            yz
           xyz
           wxyz
          vwxyz
          uvwxyz
         tuvwxyz
         stuvwxyz
        rstuvwxyz
        qrstuvwxyz
       pqrstuvwxyz
       opqrstuvwxyz
      nopqrstuvwxyz
      mnopqrstuvwxyz
     lmnopqrstuvwxyz
     klmnopqrstuvwxyz
    jklmnopqrstuvwxyz
    ijklmnopqrstuvwxyz
   hijklmnopqrstuvwxyz
   ghijklmnopqrstuvwxyz
  fghijklmnopqrstuvwxyz
  efghijklmnopqrstuvwxyz
 defghijklmnopqrstuvwxyz
 cdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

```

# Answer
> 0 votes
## Racket 137 bytes

```
(for((n(range 122 96 -1)))(for((i(floor(/(- n 97)2))))(display #\space))
(for((i(range n 123)))(display(integer->char i)))(displayln ""))

```

Ungolfed:

```
(define (f)
  (for ((n (range 122 96 -1)))
       (for ((i (floor(/(- n 97)2))))
         (display #\space))
       (for ((i (range n 123)))
         (display (integer->char i)))
    (displayln "")))

```

Testing:

```
(f)

```

Output:

```
            z
            yz
           xyz
           wxyz
          vwxyz
          uvwxyz
         tuvwxyz
         stuvwxyz
        rstuvwxyz
        qrstuvwxyz
       pqrstuvwxyz
       opqrstuvwxyz
      nopqrstuvwxyz
      mnopqrstuvwxyz
     lmnopqrstuvwxyz
     klmnopqrstuvwxyz
    jklmnopqrstuvwxyz
    ijklmnopqrstuvwxyz
   hijklmnopqrstuvwxyz
   ghijklmnopqrstuvwxyz
  fghijklmnopqrstuvwxyz
  efghijklmnopqrstuvwxyz
 defghijklmnopqrstuvwxyz
 cdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

```

# Answer
> 0 votes
# C#, 175 Bytes:

Golfed:

```
string H(){string o="",a="abcdefghijklmnopqrstuvwxyz";int p=12,i=0;for(i=0;i<=26;i++){o+=a.Substring(26-i,i).PadLeft(p+i)+"\n";if(i==0||i==1)continue;p-=i%2==0?1:0;}return o;}

```

Ungolfed:

```
public string H()
{
  string o = "", a = "abcdefghijklmnopqrstuvwxyz";
  int p = 12, i=0;
  for (i = 0; i <= 26; i++)
  {
    o += a.Substring(26 - i, i).PadLeft(p+i)+ "\n";
    if (i == 0 || i == 1) continue;
    p -= i % 2 == 0 ? 1 : 0;
  }
  return o;
}

```

Test:

```
Console.Write(new DrawAnAlphabetHat().H());

```

Output:

```
            z
            yz
           xyz
           wxyz
          vwxyz
          uvwxyz
         tuvwxyz
         stuvwxyz
        rstuvwxyz
        qrstuvwxyz
       pqrstuvwxyz
       opqrstuvwxyz
      nopqrstuvwxyz
      mnopqrstuvwxyz
     lmnopqrstuvwxyz
     klmnopqrstuvwxyz
    jklmnopqrstuvwxyz
    ijklmnopqrstuvwxyz
   hijklmnopqrstuvwxyz
   ghijklmnopqrstuvwxyz
  fghijklmnopqrstuvwxyz
  efghijklmnopqrstuvwxyz
 defghijklmnopqrstuvwxyz
 cdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

```

# Answer
> 0 votes
# Javascript, 133 Bytes

```
for(i=26,s="";i>0;i--){for(k=26-i+Math.floor((i+1)/2),l=34+Math.floor((i+1)/2);k>0;k--,l--)k>27-i?s+=" ":s+=l.toString(36);s+="<br>"}

```

Try it here

# Answer
> 0 votes
# SOGL V0.12, 8 bytes

```
z{Xf}¹№╚

```

Try it Here!

Explanation:

```
z         push the lowercase alphabet
 {  }     for each, pushing current character
  X         remove the character from the stack as it's not needed
   f        push the remaining string, including the current character, what the loop has to traverse
     ¹    wrap all that in an array
      №   reverse vertically
       ╚  center horizontally - this centers it exactly as required :D

```

# Answer
> 0 votes
# VBA, ~~68~~ 66 Bytes

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

```
For i=1To 26:?:?Spc(13-i/2);:For j=27-i To 26:?Chr(j+96);:Next j,i

```

# Answer
> 0 votes
# C# (Visual C# Compiler), 125 bytes

```
()=>{var s="";for(var c='z';c>'`';c--){for(var i='a';i<'{';i++)s+=i<c?' ':i;s+="\n";}Console.WriteLine(s.Replace("  "," "));}

```

Try it online!

Highlights: seen how char is a numeric datatype, let's use it for the loop. The value ranges from 'a' to 'z', which is awesome! We can just add a char to a string, so that's another back-curling - but now convenient - feature.

The outer counter counts from z to a, the inner counter from a to z. The inner loop checks if the inner counter is more than the outer, if so print a space, else print the counter character. After every outer iteration we print a newline, after the function completes we print it to the console after replacing a double space with a single one (very, very wasteful line, but included in character count).

I couldn't think of any more abuse in a language specification than this.

EDIT: added lambda function specification and call in accordance to alois' remark.

# Answer
> 0 votes
# F# (.NET Core), 101 bytes

```
[0..25]|>Seq.map(fun i->"".PadLeft(12-i/2)+"abcdefghijklmnopqrstuvwxyz".[25-i..])|>String.concat "\n"

```

Try it online!

A naive port of my C# answer

# Answer
> 0 votes
# Ruby, 54 bytes

```
puts (0..25).map{|c|[*(90-c).chr..'Z'].join.center 26}

```

Try it online!

# Answer
> 0 votes
# Charcoal, 16 bytes

```
Ｆ²⁷«Ｐ⮌…⮌βι¿﹪ι²↓↙

```

Try it online!

Link is to the verbose version of the code. I'm sure there must be a shorter way to do this in Charcoal.

# Answer
> 0 votes
# , 39 bytes

```
echo(' '<@#"0~2#i._13),&><@|.\u:90-i.26

```

Try it online!

I see capital letters in some submissions so I assume it's OK to use them. If not, then add a byte to convert to lowercase.

### Explanation

See my (almost identical) answer to this (duplicate) question.

The only difference is in generating the alphabet, where I generate `ZYX...CBA` and then reverse each prefix of that string to give the desired parts. I feel like there is a way to avoid that but I'm tired right now and this is the best way of fixing it that I could think of.

# Answer
> 0 votes
# Yabasic, 82 bytes

A jolly solution that takes no input and outputs to the console.

```
For i=1To 26
For j=1To 13-i/2
?" ";
Next
For j=27-i To 26
?Chr$(j+96);
Next
?
Next

```

Try it online!

# Answer
> 0 votes
# uBASIC, 75 bytes

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

Slightly different approach than other BASIC answers as uBASIC's integer division functions differently - (`25/2` equals `12` rather than `13`)

```
0ForI=2To27:?Tab(13-I/2);:ForJ=28-ITo26:?Left$(Chr$(J+96),1);:NextJ:?:NextI

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Classic), 20 bytes

```
(⌈13-.5×⍳26)⌽⌽↑,\⌽⎕a
```

Try it online!

uses `⎕io←1`

# Answer
> 0 votes
# PHP, ~~68 58~~ 57 bytes

edit #1: a different approach with left padding and string concatenation + uppercase
edit #2: shorter padding expression

```
while($i++<26)printf("
%".($i+26>>1).s,$s=chr(91-$i).$s);

```

Add two bytes if a leading newline is disallowed:

```
while($i++<26)printf("%".($i+26>>1)."s
",$s=chr(91-$i).$s);

```

Run with `-nr` or try them online.

# Answer
> 0 votes
# Gol\>\<\>, 22 bytes

```
asFa`z9sL-F:M|L2,R` |H

```

Try it online!

### How it works

```
asFa`z9sL-F:M|L2,R` |H

asF                 |   Repeat 26 times...
   a                      Push 10 (\n)
    `z                    Push z
      9sL-F  |            Repeat (25 - loop counter(L)) times...
           :M               Clone the top and decrement
              L2,R        Repeat (L / 2) times...
                  `         Push 32 (space)
                     H  Output the entire content (top to bottom) and halt

```

Basically, this constructs the entire output backwards.

There are two division operators in `Gol><>`, namely `,` (floating division) and `S,` (integer division). Luckily `R` (repeat X times) floors its argument, so I could save a byte.

# Answer
> 0 votes
**Java 10: 136 bytes**

**GOLFED**

```
for(int i=25;i>=0;i--){for(int j=0;j<i/2;j++){System.out.print("
");}System.out.println("abcdefghijklmnopqrstuvwxyz".substring(i,26));}}

```

**UNGOLFED**

```
class a {
    public static void main(String[] args) {
        for (int i = 25; i >= 0; i--) {
            for (int j = 0; j < i/2; j++) {
                System.out.print(" ");
            }
            System.out.println("abcdefghijklmnopqrstuvwxyz".substring(i,26));
        }
    }
}

```

**RESULTS**

```
            z
            yz
           xyz
           wxyz
          vwxyz
          uvwxyz
         tuvwxyz
         stuvwxyz
        rstuvwxyz
        qrstuvwxyz
       pqrstuvwxyz
       opqrstuvwxyz
      nopqrstuvwxyz
      mnopqrstuvwxyz
     lmnopqrstuvwxyz
     klmnopqrstuvwxyz
    jklmnopqrstuvwxyz
    ijklmnopqrstuvwxyz
   hijklmnopqrstuvwxyz
   ghijklmnopqrstuvwxyz
  fghijklmnopqrstuvwxyz
  efghijklmnopqrstuvwxyz
 defghijklmnopqrstuvwxyz
 cdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

```

# Answer
> 0 votes
# Canvas, 6 bytes

```
ｚ±［±］ｒ

```

Try it here!

# Answer
> 0 votes
# Japt `-R`, 7 bytes

```
;CÔåi û

```

Test it

# Answer
> 0 votes
# Elixir, 99 bytes

```
import Enum
reduce 25..0,'            ',&(IO.puts(&2++slice(?a..?z,&1,26))&&rem(&1,2)>0&& &2||tl&2)

```

Try it online!

Trying to find another way to generate the space string but can't make anything shorter...

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


title: Sliding Dice in a Dish

text:
# Question
Title: Sliding Dice in a Dish
We have 3 dice in a square dish. The dish is 8 units wide and tall and each die is 3 units wide and tall. The dice are facing up each with a different number on their top face.

```
111..222
111..222
111..222
........
........
333.....
333.....
333.....

```

Then we play a game. At each step we can slide any 1 die in any cardinal direction until it meets either another die or a boundary. We are not allowed to stop sliding it before it hits an obstacle, we must go all the way.

For example from the position above the following are valid next moves:

```
111222..  111.....
111222..  111.....
111222..  111.....
........  ........
........  ........
333.....  333..222
333.....  333..222
333.....  333..222

```

but these are not:

```
111.222.  111.....
111.222.  111.....
111.222.  111.....
........  .....222
........  .....222
333.....  333..222
333.....  333.....
333.....  333.....

```

The goal of the game is to choose a potential position and see if you can get to it from the starting position.

For example, if our goal is:

```
........
........
..111222
..111222
..111222
..333...
..333...
..333...

```

We can do these moves:

```
111..222  111.....  111.....  ........  .....222  ...222..  ........  ........  ........
111..222  111.....  111.....  ........  .....222  ...222..  ........  ........  ........
111..222  111.....  111.....  111.....  111..222  111222..  111222..  111..222  ..111222
........  ........  ........  111.....  111.....  111.....  111222..  111..222  ..111222
........  ........  ........  111.....  111.....  111.....  111222..  111..222  ..111222
333.....  333..222  ..333222  ..333222  ..333...  ..333...  ..333...  ..333...  ..333...
333.....  333..222  ..333222  ..333222  ..333...  ..333...  ..333...  ..333...  ..333...
333.....  333..222  ..333222  ..333222  ..333...  ..333...  ..333...  ..333...  ..333...

```

Not every game is winnable though, for example:

```
222..111
222..111
222..111
........
........
333.....
333.....
333.....

```

## Task

You will take as input a board, and you should output whether that board can be reached from the above starting position using these moves.

This is answers will be scored in bytes with fewer bytes being better.

## IO

You can take input as an 2D array containing 4 distinct symbols representing the 3 dice and the background. You can also take it as a list of a specified corner (e.g. upper left corner) of each of the dice.

You should give output as 1 of two distinct values with both corresponding to either true and false.

# Answer
> 12 votes
# PHP, ~~157~~ ~~123~~ ~~111~~ 89 bytes

```
function f($b){$o=$c=9;foreach($b as$p){$o*=$p%3-1;$c^=$p>2;$c*=2;}return$o&&$c%46%14<5;}

```

Try it online!

### Some deductions

I've first noted that, on each axes, if we consider the *shorter* distance of a dice from a wall, it can never be \\$1\\$.

Each movement aims towards a wall or a dice:

* hitting a wall we reset the dice shorter distance to \\$0\\$.
* hitting a dice we set the dice shortest distance to either \\$1\\$ or \\$2\\$.
    + \\$2\\$ iff the dice we hit has distance \\$0\\$ from the wall
    + \\$1\\$ iff the dice we hit has distance \\$1\\$ from the wall

Hence why, since in the starting configuration there are no dices at distance \\$1\\$ from a wall, *they can never pop up*.

***Putting momentarily aside the dices labeling***, we want to know if any configuration having no dice at distance \\$1\\$ from a wall is reachable. Note that if one particular configuration is reachable so do all its rotations and reflections since the starting one can be easily rotated (or reflected).
Now I don't have yet any simple argument so I've checked them all.
Unlabeled, net of symmetries, ***there are 21 configurations*** and I've grouped them in this way:

* **1** dice with shortest distances from the walls \\$\\{2,2\\}\\$ (there can't be more than one)

* **3** dices with shortest distances from the walls \\$\\{0,0\\}\\$ (the starting configuration)

* **2** dices with shortest distances from the walls \\$\\{0,0\\}\\$

* **1** dice with shortest distances from the walls \\$\\{0,0\\}\\$

* **0** dices with shortest distances from the walls \\$\\{0,0\\}\\$

And here's an Hamiltonian cycle through all of them! <sub>*thin air*</sub>

So as wished... Yes:

\\$A)\\$ Assuming the correct dice labeling, any configuration having no dice at distance \\$1\\$ from a wall is reachable.

Speaking of dices labeling... The board is small enough to keep the dices from permutating one another, they can only rotate like a nano version of the 15 puzzle.
Furthermore *from every configuration we can always scatter the dices to their nearest corner* and using these as dices clips we can say:

\\$B)\\$ The "clockwise order" is always retained.

### Former approach digression

Check for \\$A)\\$ is quite straightforward, but check for \\$B)\\$ can be fancy.

My former approach *(≥ 111 bytes answers)* was to calculate the two vectors connecting respectively dices `1->2` and `2->3` using their nearest corners as points.
For example in the starting position these vectors would be `(0,0)->(1,0), (1,0)->(1,1)`, read as binary numbers `0010, 1011 = 2, 11`

```
(0,0)________(1,0)
    |     <  |      Out of 12 possible vectors only 4 violate the clockwise order
    |v       |      they form the numbers 1, 7, 8, 14
    |      ^ |      all satisfying v%7<2
    |__>_____|
(0,1)        (1,1)

```

Fun fact: **former code was blundered**, it put together correctly only the first vector.
Good news I was already thinking of a way to collapse this operation into a single check instead of two.

### How

There are 24 sets (4 choose 3) of corners, 12 in clockwise order, 12 in counterclockwise order.
Combining them into one single binary number (instead of analyzing two vectors) give us the opportunity to execute a single check.
*Inspired by this answer* I wrote a C program to brute-force the decision problem out of these numbers.

```
 corners  c |   (9*32^c)*2  | c%46 | c%14 |  <5           Examples
------------+---------------+------+------+-------
 000110   6 |      588      |  36  |   8  |   no
 000111   7 |      590      |  38  |  10  |   no        3 ________ 2
 001001   9 |      594      |  42  |   0  |  yes         |        |
 001011  11 |      598      |   0  |   0  |  yes         | 011000 |
 001101  13 |      602      |   4  |   4  |  yes         |        |
 001110  14 |      604      |   6  |   6  |   no         |________|
 010010  18 |      612      |  14  |   0  |  yes        1
 010011  19 |      614      |  16  |   2  |  yes
 011000  24 |      624      |  26  |  12  |   no
 011011  27 |      630      |  32  |   4  |  yes          ________ 1
 011100  28 |      632      |  34  |   6  |   no         |        |
 011110  30 |      636      |  38  |  10  |   no         | 101101 |
 100001  33 |      514      |   8  |   8  |   no         |        |
 100011  35 |      518      |  12  |  12  |   no         |________|
 100100  36 |      520      |  14  |   0  |  yes        3          2
 100111  39 |      526      |  20  |   6  |   no
 101100  44 |      536      |  30  |   2  |  yes
 101101  45 |      538      |  32  |   4  |  yes        3 ________
 110001  49 |      546      |  40  |  12  |   no         |        |
 110010  50 |      548      |  42  |   0  |  yes         | 011100 |
 110100  52 |      552      |   0  |   0  |  yes         |        |
 110110  54 |      556      |   4  |   4  |  yes         |________|
 111000  56 |      560      |   8  |   8  |   no        1          2
 111001  57 |      562      |  10  |  10  |   no

```

# Answer
> 4 votes
# Python 3, 209 bytes

```
B=[[0,0,5,0,0,5]];exec("B+=[b[:D]+[d*min([-5*~d/2]+[b[x]*d-3 for x in((D+2)%6,(D-2)%6)if d*b[x]>d*b[D]and-3<b[D+1-D%2*2]-b[x+1-D%2*2]<3])]+b[D+1:]for D in range(6)for d in(-1,1)for b in B];"*12)
B.__contains__

```

Takes a list of six numbers, where the 1st and 2nd numbers are the x and y coordinates (0-indexed) of the upper left corner of the first dice, etc.

**Explanation**

This is *extremely* inefficient as `B` will theoretically be a list of length 9.7e12

The brute force code

```
def overlap(corner1, corner2):
    return -3 < corner1 - corner2 < 3

def move(board, direction, dice):
    other_dice_pos = [board[i] for i in [0, 1, 2] if i != dice]
    dice_x, dice_y = board[dice]
    new_board = board.copy()
    if direction in "EW":
        if direction == "E":
            new_pos = 5
            for (x, y) in other_dice_pos:
                if overlap(y, dice_y) and x > dice_x:
                    new_pos = min(new_pos, x - 3)
        else:
            new_pos = 0
            for (x, y) in other_dice_pos:
                if overlap(y, dice_y) and x < dice_x:
                    new_pos = max(new_pos, x + 3)
        new_board[dice] = (new_pos, dice_y)
    else:
        if direction == "S":
            new_pos = 5
            for (x, y) in other_dice_pos:
                if overlap(x, dice_x) and y > dice_y:
                    new_pos = min(new_pos, y - 3)
        else:
            new_pos = 0
            for (x, y) in other_dice_pos:
                if overlap(x, dice_x) and y < dice_y:
                    new_pos = max(new_pos, y + 3)
        new_board[dice] = (dice_x, new_pos)
    return new_board

initial_board = [(0, 0), (5, 0), (0, 5)]
possible_boards = [initial_board]
previous_length = 0
iteration = 0

while len(possible_boards) > previous_length:
    previous_length = len(possible_boards)
    new_boards = []
    for board in possible_boards:
        for dice in (0, 1, 2):
            for direction in "ENSW":
                new_board = move(board, direction, dice)
                if new_board not in possible_boards:
                    new_boards.append(new_board)
    possible_boards += new_boards
    iteration += 1

print(iteration)

```

shows that every reachable board is at most 12 steps away. In the code, we use six numbers to represent each board state and each move changes exactly one of them. To unify the four cases in the `move` function, we encoded the moves slightly differently.

`D` represents the index of the changing number and `d` is `-1` if the move is towards the top or the left and is `1` otherwise.

Then `(D+2)%6` and `(D-2)%6` are the indices of the coordinates in the moving direction for the stationary dice. moves from the index. Adding `1-D%2*2` shifts to the coordinates for the stationary direction. We also use the fact that `max(a,b,c)=-min(-a,-b,-c)` and `a>b` iff `-a<-b`. (The implementation has been checked to agree with `move` function up to a difference in encoding the move for all possible board positions)

The rest of the code is just simply generating all board states reachable in 12 steps and checking if the given one is one of those.

# Answer
> 2 votes
# Jelly, ~~75~~ 65 bytes

```
ÄṪ€µŒcạ/€<3¬aÆi%7Ȧ
⁴Dp`ṖÆịW,þ@⁹¦ı*Ɱ4¤¹WŒḊ?€ŒpÄÇ¿Ṫ€$€ʋⱮ3$€ẎẎQƲƬẎQċ

```

Try it online!

A pair of links that takes a list of three complex numbers as its argument (indicating upper left position of the dice, with the top left of the grid being `(1+1i)`) and returns `1` for valid final positions and `0` for invalid positions. Brute force is used to find all possible reachable positions and then the list of positions is checked. The first 7 bytes of the main link are spent constructing the initial position - removing this would allow this pair of links to be supplied with two arguments, an initial and final position, and would determine if you can reach one from the other.

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


title: Write a time machine quine

text:
# Question
Title: Write a time machine quine
Write a program that takes as input a string and an integer `n`, and outputs:

1. The string that was passed to the program `n` times ago;
2. A new program that will be used for the next invocation.

You cannot store any data outside of the program, and your program cannot call previous programs in the chain. If the string does not exist, output an empty string (but still output the next program).

Example run, where I use the notation `program_n` for each successive program (Of course, `[This text is the nth program]` would be replaced with actual code.)

```
$ program_1 "One" 1
[This text is the second program]
$ program_2 "Two" 1
One
[This text is the third program]
$ program_3 "Three" 2
One
[This text is the fourth program]
$ program_4 "Four" 2
Two
[This text is the fifth program]
$ program_5 "Five" 1
Four
[This text is the sixth program]

```

# Answer
> 4 votes
# CJam, 25

```
L{\_l~(>1<lN+a@+`@"_~"}_~

```

Try it online

**Explanation:**

```
L      push an empty array (this is the array of previous strings)
{…}    push this block
_      duplicate the block
~      execute the 2nd copy (the stack contains the array and the block)

```

The block:

```
\      swap the array with the block
_      duplicate the array
l      read a line from the input (containing the integer n)
~(     evaluate n and decrement it
>      slice the array starting at that position
1<     slice the resulting array to keep only the first string (if any)
l      read the 2nd line from the input (containing the string)
N+     append a newline
a      wrap in an array
@      bring the previous array to the top
+      concatenate the arrays, thus prepending the new string
`      convert the array to its string representation
@      bring the block to the top
"_~"   push this string

```

At the end, the requested string (if any), the array's representation, the block and the string "\_~" are printed automatically.

# Answer
> 2 votes
## Python, 221 bytes

```
import sys
o,p=[''],r'import sys;a,o,p=int(sys.argv[2]),[{2},{0}],{1};print o[a] if len(o)>a else "","\n",p.format(`sys.argv[1]`,`p`,",".join(`s`for s in o))'
print '\n',p.format(`sys.argv[1]`,`p`,','.join(`s`for s in o))

```

To test this easily, use `./thisgolf.py "yourfirststring" | python -c "import sys;exec(sys.stdin.read().split('\n')[1])" "your second string" <N>`, repeating the last bit as many times as you'd like.

# Answer
> 2 votes
# Python 2, 207 bytes

```
def r(O,R):import sys,marshal as m;a=sys.argv;b=int(a[2]);O.extend(["",""]*b);O[b]=a[1];print"%s\nfrom marshal import*;c=%r;i=lambda:0;i.__code__=loads(c);i(%r,i)"%(O[0],m.dumps(R.__code__),O[1:])
r([""],r)

```

Built on my other quine but changes program, this task is simpler so I was able to golf this further. If I was able to take the input to stdin, this should be much shorter.

# Answer
> 2 votes
# Python 3, 90 bytes

```
a=["a+=input(),;print(*a[1:-int(input())][-1:],'a=%r;exec(a[0])'%a,sep='\\n')"];exec(a[0])

```

Try it online!

## How it works:

* `a` store `[<code>, <first call>, ..., <last call>]`
* `a[1:-int(input())]` gives the sublist `[<first call>, ..., <wanted call>]` (or the empty list if the wanted call doesn't exist). Then `[-1:]` gives the singleton of the last element of that sublist if it exists (the empty list otherwise). `*` then unpack the sublist.
* The quine part is based on the quine `a="print('a=%r;exec(a)'%a)";exec(a)`

# Answer
> 0 votes
# Javascript ES6, ~~130~~ ~~128~~ ~~121~~ ~~120~~ 113 bytes

```
a=[];b=_=>{a.push(prompt());console.log((a[a.length-prompt()-1]||"")+`
a=`+JSON.stringify(a)+";b="+b+";b()")};b()

```

# Answer
> 0 votes
# Julia 1.0, 87 bytes

```
(a=:(a=[ARGS[1];a];print("(a=(println($a[parse(Int,ARGS[2])]);$a))[end]|>eval")))|>eval

```

Try it online!

smilar approach than Jakque's answer but reversing the history order:

* `a` stores `[<last string>, ..., <first string>, <code>]`
* based on this quine by Dennis
* the code is stored as a `quote`, which adds some ugly formatting but is equivalent

---
Tags: code-golf, quine
---