title: Element names above 118

text:
# Question
Title: Element names above 118
IUPAC in their insufferable wisdom have created a systematic element name for any newly created element. This is the temporary name of an element until they finally make up their minds about an actual name. It works like so: each digit of an element number is assigned a prefix based on its value. The prefixes are concatenated with ‘ium’ at the end. When this is done and if you get double i’s (ii) or triple n’s (nnn), replace them with single i’s and double n’s. The symbol for the element is the first letter of each prefix used concatenated and result capitalized. The prefixes used are below.

```
0 nil       5 pent
1 un        6 hex
2 bi        7 sept
3 tri       8 oct
4 quad      9 enn

```

So for this golf, your code needs to generate both the element name and its symbol for a given positive integer. So if your code was given 137, it should print to stdout or return both `untriseptium` and `Uts`. It should be valid from at least 118 to 558. Any higher is valid if it doesn't increase your code's length.

Python example showing the method:

```
def elename(n):
    '''Return name and symbol of new element for given element number.'''
    prefixes=['nil','un','bi','tri','quad','pent','hex','sept','oct','enn']
    nmeFixes, symFixes = [], []

    while n:  # each digit of element number is assigned a prefix
        n, i = divmod(n, 10)
        pf = prefixes[i]

        symFixes.append(pf[0])  # symbol uses only first letter of prefix
        nmeFixes.append(pf)

    # loop assembled prefixes in reverse order
    nmeFixes.reverse()
    symFixes.reverse()

    nmeFixes.append('ium')  # suffix
    name = ''.join(nmeFixes)
    symb = ''.join(symFixes).capitalize()

    # apply rule about too many n's or i's
    name = name.replace('nnn','nn')  # can happen with -90-
    name = name.replace('ii','i')  # -2ium or -3ium

    return name, symb

```

---

Eric Towers wins with cadmium bytes!

# Answer
> 23 votes
## Mathematica 10.1, indium (49) cadmium (48)

This solution uses a built-in library of element properties, including IUPAC names and abbreviations. (I haven't seen this as a technique to be avoided in Golf. It seems to be encouraged. But this might be on (perhaps over) the edge of acceptable -- Mathematica implements this library (and many others) by downloading data from Wolfram's servers the first time you use it (and I presume checks for updates occasionally).)

```
f=ElementData@@@{{#,"Abbreviation"},{#,"Name"}}&
(*
Improved by @user5254 from
f[n_]:=ElementData[n,#]&/@{"Abbreviation","Name"}
*)

f[48]
(* {"Cd", "cadmium"} *)

f[118]
(* {"Uuo", "ununoctium"} *)

f[122]
(* {"Ubb", "unbibium"} *)

f[190]
(* {"Uen", "unennilium"} *)

f[558]
(* {"Ppo", "pentpentoctium"} *)

f[10^100-1]
(* {"Eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "ennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennium"} *)

```

How would this compare to using elements.py or periodictable.py in Python?

Edit: Months later: Noticed I had typo'ed the abbreviation output for 122. I've re-run the code and verified that I made this error, not Mathematica.

# Answer
> 26 votes
# Python 3, Unhexseptium (167) bytes

```
h=x='';r=str.replace
for i in input():s=r('nubtqphsoeinirueeecnl  ianxptn    dt t'[int(i)::10],' ','');h+=s;x+=s[0]
print(r(r(h+'ium\n','ii','i'),'nnn','nn')+x.title())

```

These are the results when the program is run on every number from 1 to 999 (inclusive)

# Answer
> 15 votes
# Pip, ~~Thorium~~ ~~Actinium~~ Radon (86)

<sup>*(Don't inhale this entry, it'll give you lung cancer.)*</sup>

```
P(aR,tY"nil un bi tri quad pent hex sept oct enn"^s)."ium"R`ii|nnn`_@>1Yy@_@0MaUC:y@0y

```

Takes the element number as a command-line argument and outputs the name & abbreviation on separate lines.

Explanation (somewhat ungolfed):

```
Y"nil un bi tri quad pent hex sept oct enn"^s  Build list of prefixes & store in y

    ,t                                         Range(10)
 (aR  y)                                       Replace each digit in input with
                                                 corresponding element in prefix list
        ."ium"                                 Append "ium"
              R`ii|nnn`_@>1                    Reduce too-long runs of letters
P                                              Print

 {y@a@0}Ma                                     For each digit in input, get first character
                                                 of corresponding prefix
Y                                              Store that list in y
          UC:y@0                               Uppercase the first item of y in place
                y                              Print y (items concatenated)

```

The `ii` and `nnn` handling uses a regex replacement with a callback function (added in the most recent version of Pip): for every match of `ii|nnn`, take all but the first character and use as a replacement.

# Answer
> 14 votes
# GNU sed, 171 (unseptunium)

```
s/0/Nil/g
s/1/Un/g
s/2/Bi/g
s/3/Tri/g
s/4/Quad/g
s/5/Pent/g
s/6/Hex/g
s/7/Sept/g
s/8/Oct/g
s/9/Enn/g
s/$/ium/
h
s/[a-z]//g
G
s/./\L&/g
s/./\U&/
s/\n/ /
s/ii/i/g
s/nnn/nn/g

```

I assume it doesn't matter what order the name and symbol are returned in. Here, symbol comes first:

```
$ seq 180 190 | sed -f iupac.sed
Uon unoctnilium
Uou unoctunium
Uob unoctbium
Uot unocttrium
Uoq unoctquadium
Uop unoctpentium
Uoh unocthexium
Uos unoctseptium
Uoo unoctoctium
Uoe unoctennium
Uen unennilium
$

```

# Answer
> 8 votes
# JavaScript (ES6) 164 (unhexquadium) ~~171~~

The capitalization is the tricky part. (Test in FireFox)

**Edit** 3 bytes saved thx user2786485

```
f=n=>[([...n+(l='')].map(c=>(c='nil,un,bi,tri,quad,pent,hex,sept,oct,enn'.split`,`[c],n=l?n+c[0]:c[0].toUpperCase(),l+=c)),l+'ium').replace(/i(i)|n(nn)/g,'$1$2'),n]

function test() { O.innerHTML=f(+I.value) }

test()

for(o='',i=99;i++<999;)o+=i+' '+f(i)+'\n';P.innerHTML=o
```

```
<input id=I onchange="test()" value="164"><span id=O></span><pre id=P></pre>
```

# Answer
> 8 votes
## Mathematica, unhexunium ~~163~~ 161 bytes

*now capitalises symbol*

This is Mathematica without the built-in `ElementData`.

```
f=StringReplace[##<>"ium, "<>{ToUpperCase@#1,##2}~StringTake~1&@@ToString/@nil[un,bi,tri,quad,pent,hex,sept,oct,enn][[IntegerDigits@#]],{"ii"->"i","nnn"->"nn"}]&

```

Test on 10 random numbers:

```
# -> f[#]& /@ RandomInteger[{118, 558}, 10] // ColumnForm

155->unpentpentium, Upp
338->tritrioctium, Tto
477->quadseptseptium, Qss
261->bihexunium, Bhu
158->unpentoctium, Upo
164->unhexquadium, Uhq
266->bihexhexium, Bhh
331->tritriunium, Ttu
404->quadnilquadium, Qnq
389->trioctennium, Toe

```

# Answer
> 7 votes
# Ruby - ~~163~~ ~~156~~ ~~147~~ ~~143~~ 134 (Untriquadium) bytes

```
o=u='';gets.bytes{|c|k=%w[Nil un bI trI quad pent hex sept oct enN Ium][c%48];o+=k;u+=k[0]};puts o.tr_s('IN','in'),u[0..-2].capitalize

```

I'm hoping to golf this way down

Edit: Thanks for @steveverrill for shaving off 9 bytes!

Edit2: Thanks for @steveverrill again for another 4 bytes! (Really clever solution!)

# Answer
> 7 votes
# CJam, ~~74~~ ~~72~~ ~~71~~ ~~70~~ 69 bytes (Thulium)

```
r:i"Ø¾aÈÁaÎE<Ä+&:¬úD±"380b24b'af+)/f=_:c(euoS@s'n3*/"nn"*)"ium"|

```

Note that the code contains unprintable characters.

*Thanks to @Sp3000 for pointing out an error in my initial revision and suggesting the `)/` approach.*

Try it online in the CJam interpreter:.

### How it works

```
r:i     e# Read a token and push the array of its character codes.
"…"     e# Push a string of unprintable characters.
380b24b e# Convert it from base 380 to base 24.
'af+    e# Add the character 'a' to each base-24 digit.
        e# This pushes "bijtrijquadjpentjhexjseptjoctjennjniljunj".
)/      e# Pop the last character and split the string at the remaining occurrences.
f=      e# For each character code in the input, select the correspoding chunk.
_:c     e# Push a copy and cast each string to character.
(euo    e# Shift out the first character, convert to uppercase, and print.
S@      e# Push a space and rotate the array of string on top of it.
s       e# Flatten the array of string.
'n3*/   e# Split at occurrences of "nnn".
"nn"*   e# Join, using "nn" as separator.
)"ium"| e# Pop the last character and perform setwise union with "ium".
        e# If the last character is, e.g., 't', this pushes "tium".
        e# If the last character is 'i', this pushes "ium".

```

# Answer
> 7 votes
# Pyth, 67 bytes (Holmium)

```
rshMJ@Lcs@LGjC"]ß!âÿeóÑiSÑA¼R¬HE"24\fjQT3-"ium"epj"nn"csJ*\n3

```

Try it online in the Pyth Compiler/Executor.

### How it works

```
            jC"…"24       Convert the string from base 256 to base 24.
        s@LG              Select the letter that corresponds to each digit.
       c           \f     Split at 'f'.
     @L              jQT  Select the chunk that corresponds to each input digit.
    J                     Save in J.
 shM                      Form a string of the first letters of the chunks.
r                       3 Capitalize the first character.
                          Print. (implicit)

             csJ*\n3      Split the flattened J at "nnn".
        j"nn"             Join, separating by "nn".
       p                  Print.
-"ium"e                   Remove the last character ('i'?) from "ium".
                          Print. (implicit)

```

# Answer
> 6 votes
# JavaScript (ES6), ~~210~~ 202 Bytes (~~Biunnilium~~ Binilbium)

Minus octium (8) bytes, thanks to @edc65!

~~130 159 147 Bytes (Untrinilium Unpentennium Unquadseptium)~~

```
f=z=>(c=(b=(z+"").split``.map(x=>"nil.un.bi.tri.quad.pent.hex.sept.oct.enn".split`.`[+x])).join``.replace(/nnn/g,"n"))+(c[c.length-1]!="i"?"i":"")+"um,"+(a=b.map(x=>x[0])).shift().toUpperCase()+a.join``

```

Input like `f(324)`. Ugh, I felt so golf-y.

# Answer
> 5 votes
# TI-BASIC, ~~223~~ 218 bytes

```
Input N
"nil un  bi  tri quadpenthex septoct enn→Str4
"int(10fPart(N/10^(X→Y₁
"sub(Str4,1+4Y₁,int(3fPart(e^(Y₁)1.5154)+2^not(X=2 and .9=fPart(N%) or X=1 and 1=int(5fPart(.1N→Y₂
"ium,"+sub("UBTQP",int(N%),1
For(X,1,3
Y₂+Ans+sub(Y₂(3-X),1,1
End
sub(Ans,1,length(Ans)-1

```

Element number N can only have a triple "n" if it ends in 90, and can only have a double-"i" if the last digit is 2 or 3. We use math to check those cases.

The magic number `1.5154`, which stores the length of each prefix, was found using a Python script to search all decimals of length ≤7 using the functions `cosh(`, `cos(`, and `e^(`.

Not done golfing yet, but TI-BASIC's two-byte lowercase letters and lack of string manipulation commands, as always, will hurt this program's score.

# Answer
> 4 votes
# Matlab, 170 (Unseptnilium)

Works on all inputs you can throw at it, from `nilium` up to, well as far as you care to go. I got to `ennennennennennennennennennennennennennennennennennennennennennennium` before I gave up with pressing the 9 key.

```
l=['nubtqphsoe';'inirueeecn';'l  ianxptn';'    dt t  '];i=input('','s')-47;s=l(1,i);s(1)=s(1)-32;a=l(:,i);disp([strrep(strrep([a(a>32)' 'ium '],'nnn','nn'),'ii','i') s]);

```

And an explanation:

```
%Create a 2D array of the prefixes transposed
l=['nubtqphsoe';'inirueeecn';'l  ianxptn';'    dt t  '];
%Grab the input number
i=input('','s')     %Request the input and convert to string
               -47; %Convert from ASCII into an array of indecies (1 indexed)
%Generate the short form
s=l(1,i);
%Capitalise first letter in short form
s(1)=s(1)-32;
%Extract required prefixes for long form
a=l(:,i);
%Now the fun bit:
                     a(a>32)'                                    %Combine the prefixes removing spaces and transpose into a string
                    [         'ium ']                            %Append 'ium ' to the string (the space is to separate the short form)
             strrep(                 ,'nnn','nn')                %Replace 'nnn' with 'nn'
      strrep(                                    ,'ii','i')      %Replace 'ii' with 'i'
disp([                                                     s]); %And display both full and short form strings together

```

# Answer
> 3 votes
# CJam, 95 bytes

```
liAbA,"nil un bi tri quad pent hex sept oct enn"S/er_:c(eu\+_1>"en"={\W"il"t\}&S@:+)_'i=!*"ium"

```

Try it online

This competes in the category "languages without regex, and only using printable characters." ;) Didn't really expect it to be as short as some of the already posted solutions, but I was curious how long it would end up anyway. And since I got it now, I might as well post it.

Explanation:

```
li      Get input and convert to int.
Ab      Encode in decimal.
A,      Build list [0 .. 9].
"..."   String with prefixes.
S/      Split at spaces.
er      Transliterate. We now have a list of the prefix for each digit.
_:c     Copy and take first character of each, for short form.
(       Pop off first character.
eu      Convert it to upper case.
\+      Put it back in place. Done with short form.
_1>     Remove first character.
"en"=   Compare with "en", corresponding to the 90 special case.
{       Handle 90 case, replace
  \       Swap full prefix list to top.
  W"il"t  Replace "nil" by "il" to avoid "nnn".
  \       Swap short form back to top.
}&      End of 90 case.
S       Push space between short form and full name.
@       Swap prefix list to top.
:+      Concatenate all the prefixes.
)       Pop off the last letter.
_'i=    Compare it with 'i.
!*      Multiply letter with comparison result. This gets rid of letter if it's 'i.
"ium"   Add the final part of the output.

```

# Answer
> 3 votes
# Retina, ~~206~~ ~~196~~ ~~186~~ 179 (Unseptennium) bytes (Try it online)

Thanks to @MartinBüttner (https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for teaching me this language.

Thanks to @FryAmTheEggman for chopping off 7 bytes.

```
T`d`nubtq\p\hs\oe
.+
$&, $&
(?<=,.*n)
il
(?<=,.*e)n?
nn
(?<=,.*u)
n
(?<=,.*b)
i
(?<=,.*t)
ri
(?<=,.*q)
uad
(?<=,.*p)
ent
(?<=,.*h)
ex
(?<=,.*s)
ept
(?<=,.*o)
ct
r`i?$
ium
T`l`L`^.

```

Ueh-byte version: here

Bnh-byte version: here

# Answer
> 2 votes
# Python 3, unpentquadium (~~156~~ ~~155~~ 154) bytes

```
n=e=""
for c in input():s="nil un bi tri quad pent hex sept oct enn".split()[int(c)];n+=s[c<"1"<"nn"==n[-2:]:];e+=s[0]
print(n.strip("i")+"ium",e.title())

```

Instead of replacing `ii` with `i` we rstrip any `i`s before we tack on the `ium`, since that's the only possible source of double `i`s. Similarly, we strip `n`s by checking for an `enn/nil` case.

# Answer
> 2 votes
# PHP, 152  ~~153~~ ~~163~~ bytes, unpentbium

Well, at least PHP is somewhere around average this time.

```
while(null!=$x=$argv[1][$i++]){$a.=$y=[nil,un,bi,tri,quad,pent,hex,sept,oct,enn][$x];$b.=$y[0];}echo str_replace([ii,nnn],[i,nn],$a.'ium ').ucfirst($b);

```

Runs form command line like:

```
pentium.php 163

```

Output:

```
unhextrium Uht

```

---

**Ungolfed**

```
$y = array('nil','un','bi','tri','quad','pent','hex','sept','oct','enn');

while (null != ($x = $argv[1][$i++])) {
    $a .= $y[$x];
    $b .= $y[$x][0];
}

echo str_replace(
        array('ii','nnn'),
        array('i','nn'),
        $a . 'ium ')
     .ucfirst($b);

```

---

**Edit**

* saved 10 bytes by replacing all (not only one, *duh*) `array()`-initializer with `[]`
* saved 1 byte by adding the whitespace along with `'ium '` instead using an extra concatenation `.' '.`

# Answer
> 1 votes
# Go, 322 Bytes (tribibium)

```
package main
import("os"
"strings"
"fmt")
func main(){p,n,s:="nil un  bi  tri quadpenthex septoct enn ","",make([]byte,0)
b:=make([]byte,3)
os.Stdin.Read(b)
var d byte=32
for _,r:=range b{i:=r-48
n+=p[4*i:4*i+4]
s,d=append(s,p[4*i]-d),0}
fmt.Printf("%sium %s",strings.NewReplacer(" ","","ii","i","nnn","nn").Replace(n),s)}

```

Reads three characters from STDIN, more are ignored, less result in a crash. So it works for every number between `unnilnilium` and `ennennennium`.

# Answer
> 1 votes
# Haskell, bipentbium (305 271 269 265 261 259 253 252 bytes)

```
import Data.Char
main=getLine>>=putStr.a
m=map toLower
a n=(r.m$p)++(k.filter isUpper$p)where p=(n>>=(words"Nil Un Bi Tri Quad Pent Hex Sept Oct Enn"!!).digitToInt)++"ium "
r('n':'n':'n':x)="nn"++r x
r('i':'i':x)='i':r x
r(x:z)=x:r z
r x=x
k(h:t)=h:m t

```

Shaved 34 bytes off thanks to nimi.

# Answer
> 1 votes
## PowerShell, ~~170~~ ~~168~~ 165 (Unhexpentium)

```
-join($a="$input"[0..9]|%{(($x=(-split'Nil Un Bi Tri Quad Pent Hex Sept Oct Enn')["$_"]).ToLower(),$x)[!($y++)]})+'ium'-replace'(nn)n|(i)i','$1$2'
-join($a|%{$_[0]})

```

Fairly straightforward and no surprises here. Except maybe that I solved the capitalization issue by lower-casing everything but the first part and having the individual parts already in title-case. Agrressively inlined by now to avoid losing characters for bare variable assignments.

Bonus after the last change: Now works for longer element numbers as well:

```
> echo 1337| powershell -noprofile -file "element.ps1"
Untritriseptium
Utts

```

# Answer
> 1 votes
# C on x86, 192 (Unennbium)

```
int c,s,a[8],x,main(){while((c=getchar()-48)>=0)x="nil\0un\0\0bi\0\0tri\0quadpenthex\0septoct\0enn"+4*c,strncat(a,x+(c<s-8),4),strncat(a+5,x,1),s=c;printf("%s%s %s",a,"ium"+((s&14)==2),a+5);}

```

Reads digits from `stdin` and prints the results to `stdout`. Relies on `sizeof(char*) == sizeof(int)`.

Ungolfed version:

```
int c, s, // Current and last digit, initially zero (0-9, not '0'-'9')
    a[8], // Buffer to write to (type doesn't matter when passed by pointer)
    x; // Int-pointer into lookup table

main() {
    while ((c = getchar() - 48) >= 0) { // 48 == '0'
        x = "nil\0un\0\0bi\0\0tri\0quadpenthex\0septoct\0enn" + 4*c;
        strncat(a, x+(c<s-8), 4); // Write digit, skip first char if c==0 && s==9
        strncat(a+5, x, 1); // Write first digit character somewhere else
        s = c;
    }
    printf("%s%s %s", a, "ium"+((s&14)==2), a+5); // Append "ium" (or "um" if s==2||s==3)
}

```

# Answer
> 1 votes
# GNU sed, unhexunium (161 bytes)

```
h
y/0123456789/nubtqphsoe/
s/./\u&/
x
s/$/ium/
:
s/0/nil/
s/1/un/
s/2/bi/
s/3/tri/
s/4/quad/
s/5/pent/
s/6/hex/
s/7/sept/
s/8/oct/
s/9/enn/
s/nnn/nn/
s/ii/i/
t
G

```

I generate the symbol first, then stash that into hold space and create the name. A loop is golfier than using `/g` for four or more replacements (we can have only one `ii` and/or one `nnn`, so they don't need to be inside the loop, but it doesn't hurt). Finally, retrieve and append the held symbol.

(N.B. I hadn't seen the existing sed answer when I wrote this)

### Test cases

These exercise the `ii` and `nnn` special rules:

```
$ seq 100 89 1000 | ./60208.sed
unnilnilium
Unn
unoctennium
Uoe
biseptoctium
Bso
trihexseptium
Ths
quadpenthexium
Qph
pentquadpentium
Pqp
hextriquadium
Htq
septbitrium
Sbt
octunbium
Oub
ennilunium
Enu
ennennilium
Een

```

And a ridiculous one, showing how much more this code gives, compared to the physical world:

```
$ ./60208.sed <<<281039817
bioctunniltriennoctunseptium
Bounteous

```

# Answer
> 1 votes
**T-SQL 329 bytes**

```
creat proc x(@a char(3))as select replace(replace((select a.b as[text()]from(select left(@a,1)a union select substring(@a,2,1)union select right(@a,1))z join(values(0,'nil'),(1,'un'),(2,'bi'),(3,'tri'),(4,'quad'),(5,'pent'),(6,'hex'),(7,'sept'),(8,'oct'),(9,'enn'))a(a,b)on z.a=a.a for xml path(''))+'ium','ii','i'),'nnn','nn')

```

Formatted:

```
create proc x(@a char(3))as
select replace(replace(
(select a.b as[text()]from
    (
    select left(@a,1)a
    union select substring(@a,2,1)
    union select right(@a,1))z
join(values(0,'nil'),(1,'un'),(2,'bi'),(3,'tri'),(4,'quad'),(5,'pent'),(6,'hex'),(7,'sept'),(8,'oct'),(9,'enn')
    )a(a,b)on z.a=a.a
for xml path('')
)+'ium','ii','i'),'nnn','nn')

```

# Answer
> 1 votes
# R, 278 bytes

```
g<-function(x){k<-data.frame(c("nil","un","bi","tri","quad","pent","hex","sept","oct","enn"));row.names(k)<-0:9;n<-unlist(strsplit(as.character(x),""));return(sub("nnn","nn",sub("ii","i",paste(c(as.vector(k[n,]),"ium"," ",sapply(k[n,],function(x)substr(x,1,1))),collapse=""))))}

```

Not the best... but I'm still learning R so I thought I'd post my attempt. Any suggestions to make it better? Now that I think about it it's probably possible to subset on the nth-1 row rather than wasting space creating row names.

### Example usage

```
> g(118)
[1] "ununoctium uuo"
> g(999)
[1] "ennennennium eee"
> g(558)
[1] "pentpentoctium ppo"
> g(118)
[1] "ununoctium uuo"
> g(90)
[1] "ennilium en"
> g(2)
[1] "bium b"

```

### Ungolfed

```
g <- function(x) {
    k <- data.frame(c("nil","un","bi","tri","quad","pent","hex","sept","oct","enn"))
    row.names(k) <- 0:9
    n <- unlist(strsplit(as.character(x),""))
    return(
        sub("nnn", "nn", sub("ii", "i", paste(c(as.vector(k[n,]),"ium"," ", sapply(k[n, ],function(x)substr(x,1,1))), collapse = ""))))
}

```
1. Create a key, convert to data frame, and set as the variable `k`
2. Set the row names as `0-9` for easy identification
3. Take the input `x`, convert to character, split it up (e.g. 137 to "1" "3" "7")
4. Subset `k` based on the split number input and return the entries
5. Concatenate them together and add `-ium`
6. Also subset `k` using substring to pull the first letter of the matches. This is concatenated to the output of step 5 with a blank space between them
7. Use `sub()` to replace the `nnn` and `ii` patterns

# Answer
> 1 votes
# Javascript - 169 bytes

```
n=>eval(`q='nil0un0bi0tri0quad0pent0hex0sept0oct0enn'.split(0);for(b of (_=$='')+n){c=q[b];$+=q[b];_+=(_?c:c.toUpperCase())[0]}$.replace(/i$()|n(nn)/g,'$1$2')+'ium '+_`)

```

Bizarrely, my attempts to use map were *longer* than the for loop.

**EDIT:** Oops, forgot to check the date.

# Answer
> 1 votes
# PHP, 131+1 bytes (untriunium)

still awfully long:

```
for(;~$c=$argn[$i];print$i++?$n[0]:$n&_)$r.=$n=[nil,un,bi,tri,quad,pent,hex,sept,oct,enn][$c];echo strtr(_.$r.ium,[ii=>i,nnn=>nn]);

```

Run as pipe with `-nR` or try it online.

# Answer
> 0 votes
# Perl, 109 (Unnilennium) bytes

108 code + 1 switch

```
perl -pe 's!.!qw{Nil Un Bi Tri Quad Pent Hex Sept Oct Enn}[$&]!ge;s!nnN!nN!g;s!i?$!ium!;$_=lc$_.y!a-z!!dr;s!\b.!\U$&!g'

```

Takes input from STDIN as one number per line.

# Answer
> 0 votes
## C# ~~229 (Bibiennium)~~ 198 unennoctium bytes

The "n-'0'" trick is a way to convert from ascii to int. Char 9 = ASCII 57. Char 0 = ASCII 48, so 57-48 = 9.

~~static private string ToText(int v) { return (string.Join("",v.ToString().Select((char n)=\>"nil un bi tri quad pent hex sept oct enn".Split()\[n-'0'\]))+"ium").Replace("nnn","nn").Replace("ii","i")+" "+string.Join("",v.ToString().Select((char n)=\>"nubtqphsoe"\[n-'0'\])); }~~

```
    static private string ToText(int  v)
    {
        string u,r="",t="";
        return v.ToString().Select((char n)=>{u="nil un bi tri quad pent hex sept oct enn".Split()[n-48];r+=u;t+=u[0];return r;}).Last()+"ium".Replace("nnn","nn").Replace("ii","i")+" "+t;
    }

```

This approach takes the int, converts to a string, then performs a LINQ select of characters that fires off a lambda.

The lambda generates an array on the fly (less characters than defining it) by splitting the string of prefixes. It then pulls the index of the prefix to use by looking at the current character's int value (the n-'0' trick mentioned above).

All that is wrapped in a string.Join which concatenates all of the LINQ results together. Tack on the "ium", then a couple of .Replace statements at the end to clean up the nnn' and ii's.

Added the missing symbol output. I think there's a more efficient way by merging the two LINQs, but it's way to late to keep poking at it.

# Answer
> 0 votes
**Java 8 216Bytes**

```
String f(int i){
String[] s = {"nil","un","bi","tri","quad","pent","hex","sept","oct","enn"};
return ((""+i).chars().mapToObj(y->s[y-48]).collect(Collectors.joining())+"ium").replace("ii","i").replace("nnn","n");
}

```

# Answer
> 0 votes
# C, ~~210~~ ~~204~~ unennennium (199) bytes

This requires ASCII as the runtime character set.

```
f(char*n,char*s){char*c="NilUnBiTriQuadPentHexSeptOctEnn",*p,*o=n,i,j;for(;*n;){for(j=i=*n-48,p=c;*p&32||i--;++p);for(*s++=*n=*p+32;*++p&32;)*s++=*p;s-=*n++-j==39||j/2-*n==1;}*o-=32;strcpy(s,"ium");}

```

I did try a recursive solution (which avoids the need for `p` and `o`) but that turned out longer.

I'm particularly proud/ashamed of the matcher for the regexp `90|[23]$`, which relies on `9` and `0` being the furthest separated digits (and therefore the only pair that differ by 9 - the `39` in the code is a consequence of `j` being an integer value and `*n` still an ASCII character) and that `2` and `3` differ only in the last bit, so dividing by 2 conflates them.

### Expanded code:

```
void f(char *n,                 /* input number / output symbol */
       char *s)                 /* output name */
{
    char *c = "NilUnBiTriQuadPentHexSeptOctEnn", /* digit names */
        *p,
        *o = n,                 /* first char of input */
        i, j;                   /* current digit value */
    for (;*n;) {
        j = i = *n-48;
        for (p=c;  *p&32 || i--;  ++p) /* Find the i'th capital letter in c */
                ;
        for (*s++ = *n++ = *p++ + 32;  *p&32;  ) /* Downcase and copy following lowercase */
            *s++ = *p++;
        s -= *n-j==39 || j/2-*n==1;   /* backup one if 9 is followed by 0, or if 2 or 3 is at end of input */
    }
    *o -= 32;                   /* Capitalise symbol */
    strcpy(s,"ium");            /* Finish name */
}

```

### Test harness:

```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char buf[1024];
    while (*++argv) {
        f(*argv, buf);
        printf("%s %s\n", *argv, buf);
    }
    return EXIT_SUCCESS;
}

```

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


title: Print the British Flag!

text:
# Question
Title: Print the British Flag!
Inspired by Print the American Flag! this is a direct copy but with the British flag as it has some symmetries but is still quite complex!

Your challenge is to produce the following ASCII-Art in as few bytes as possible! Turn your head/screen (not both!) by 90 degrees to view it properly.

```
 __________________________________________
|\  \XXXXXXXXXXXX  000000  XXXXXXXXXXXX//0/|
|0\  \XXXXXXXXXXX  000000  XXXXXXXXXXX//0/ |
|\0\  \XXXXXXXXXX  000000  XXXXXXXXXX//0/  |
|\\0\  \XXXXXXXXX  000000  XXXXXXXXX//0/  /|
|X\\0\  \XXXXXXXX  000000  XXXXXXXX//0/  /X|
|XX\\0\  \XXXXXXX  000000  XXXXXXX//0/  /XX|
|XXX\\0\  \XXXXXX  000000  XXXXXX//0/  /XXX|
|XXXX\\0\  \XXXXX  000000  XXXXX//0/  /XXXX|
|XXXXX\\0\  \XXXX  000000  XXXX//0/  /XXXXX|
|XXXXXX\\0\  \XXX  000000  XXX//0/  /XXXXXX|
|XXXXXXX\\0\  \XX  000000  XX//0/  /XXXXXXX|
|XXXXXXXX\\0\  \X  000000  X//0/  /XXXXXXXX|
|XXXXXXXXX\\0\  \  000000  //0/  /XXXXXXXXX|
|XXXXXXXXXX\\0\    000000  /0/  /XXXXXXXXXX|
|XXXXXXXXXXX\\0\   000000  0/  /XXXXXXXXXXX|
|XXXXXXXXXXXX\\0\  000000  /  /XXXXXXXXXXXX|
|XXXXXXXXXXXXX\\0  000000    /XXXXXXXXXXXXX|
|XXXXXXXXXXXXXX\\  000000   /XXXXXXXXXXXXXX|
|                  000000                  |
|000000000000000000000000000000000000000000|
|000000000000000000000000000000000000000000|
|000000000000000000000000000000000000000000|
|                  000000                  |
|XXXXXXXXXXXXXX/   000000  \\XXXXXXXXXXXXXX|
|XXXXXXXXXXXXX/    000000  0\\XXXXXXXXXXXXX|
|XXXXXXXXXXXX/  /  000000  \0\\XXXXXXXXXXXX|
|XXXXXXXXXXX/  /0  000000   \0\\XXXXXXXXXXX|
|XXXXXXXXXX/  /0/  000000    \0\\XXXXXXXXXX|
|XXXXXXXXX/  /0//  000000  \  \0\\XXXXXXXXX|
|XXXXXXXX/  /0//X  000000  X\  \0\\XXXXXXXX|
|XXXXXXX/  /0//XX  000000  XX\  \0\\XXXXXXX|
|XXXXXX/  /0//XXX  000000  XXX\  \0\\XXXXXX|
|XXXXX/  /0//XXXX  000000  XXXX\  \0\\XXXXX|
|XXXX/  /0//XXXXX  000000  XXXXX\  \0\\XXXX|
|XXX/  /0//XXXXXX  000000  XXXXXX\  \0\\XXX|
|XX/  /0//XXXXXXX  000000  XXXXXXX\  \0\\XX|
|X/  /0//XXXXXXXX  000000  XXXXXXXX\  \0\\X|
|/  /0//XXXXXXXXX  000000  XXXXXXXXX\  \0\\|
|  /0//XXXXXXXXXX  000000  XXXXXXXXXX\  \0\|
| /0//XXXXXXXXXXX  000000  XXXXXXXXXXX\  \0|
|/0//XXXXXXXXXXXX__000000__XXXXXXXXXXXX\__\|

```

The block is 44 x 42 characters. Note that the first line ends with a single space! No other trailing spaces are allowed but a trailing new line is allowed on the last line.

I'm not aware of any date significance for the UK at the moment!

# Answer
> 10 votes
# SpecBAS - 1137 bytes

Absolutely no hope of winning on characters, but the output is in colour...

```
1 PAPER 15: CLS
2 PRINT AT 1,2;("_"*42): FOR y=2 TO 42: PRINT AT y,1;"|";AT y,44;"|": NEXT y
3 FOR y=4 TO 18: PRINT AT y,y-2;"\";AT y+1,y-2;"\": NEXT y: PRINT AT 19,17;"\"
4 FOR y=2 TO 14: PRINT AT y,y;"\  \";AT y+28,y+26;"\  \": NEXT y: FOR y=15 TO 17: PRINT AT y,y;"\";AT y+12,y+13;"\": NEXT y
5 FOR y=25 TO 39: PRINT AT y,y+3;"\\": NEXT y: PRINT AT 40,43;"\"
6 FOR y=2 TO 14: PRINT AT y,42-y;"/";AT y+1,42-y;"/": NEXT y: PRINT AT 2,41;"/"
7 FOR y=2 TO 17: PRINT AT y,45-y;"/";AT y+3,45-y;"/": NEXT y
8 FOR y=2 TO 16: PRINT AT y+23,18-y;"/";AT y+26,18-y;"/": NEXT y: PRINT AT 27,17;"/"
9 FOR y=1 TO 13: PRINT AT y+29,17-y;"//": NEXT y: PRINT AT 29,17;"/"
10 PRINT AT 42,18;"__";AT 42,26;"__";AT 42,41;"__"
11 INK 2
12 FOR y=2 TO 42: PRINT AT y,20;"0"*6: NEXT y
13 FOR y=21 TO 23: PRINT AT y,2;"0"*42: NEXT y
14 FOR y=3 TO 18: PRINT AT y,y-1;"0";AT y+23,y+25;"0": NEXT y
15 FOR y=2 TO 16: PRINT AT y,44-y;"0";AT y+26,19-y;"0": NEXT y
16 INK 1
17 FOR y=2 TO 13: LET l$="x"*(14-y): PRINT AT y,4+y;l$;AT y,28;l$;AT 44-y,4+y;l$;AT 44-y,28;l$: NEXT y
18 FOR y=6 TO 19: LET l$="x"*(y-5): PRINT AT y,2;l$;AT y,49-y;l$;AT 44-y,2;l$;AT 44-y,44-LEN l$;l$: NEXT y

```

# Answer
> 4 votes
# Python 2, 223 bytes

```
o=""
x="X"*15
s=x+r"\  \0\\%s//0/  /"%x
exec'o+="|%s  000000  %s|\\n"%(s[18:2:-1],s[25:41]);s=s[1:]+s[0];'*18
print" "+"_"*42+" \n"+o+"\n".join("|%s000000%s|"%(c*18,c*18)for c in" 000 ")+o[:43:-1]+o[43::-1].replace(" ","_")

```

Still much to golf.

Despite its looks, the back half is the same as the front half reversed (barring the underscores), which is unusually nice for a pattern with slashes.

# Answer
> 2 votes
# Python 3 ~~361~~ 331

```
p=print
p("","_"*42,"")
r='|'
w="X"*16
s="\\  \\0\\\\"
z="//0/  /"
O=" 000000 "
m=r+" "*18+"0"*3
o=w+s+w
e=w+z+w
T=e[::-1]
f=o[::-1]
R=range(18)
for i in R:p(r+o[i+19:i+3:-1],O,e[i+4:i+20]+r)
B="p(m+m[::-1]);"
exec(B+"p(r+'0'*42+r);"*3+B)
for i in R[1:]:p(r+T[i+1:i+17],O,f[i+16:i:-1]+r)
p(r+T[19:35]+"__000000__"+o[4:17]+"__\\|")

```

This program makes use of python's awesome string slicing capabilities to create a string that represents the stripes:

```
o = "XXXXXXXXXXXXXXX\  \0\\XXXXXXXXXXXXXXX"

```

Then repeatedly print it backwards while shifting it to the right by increasing the start and end of the string slice to get this:

```
\  \XXXXXXXXXXX
0\  \XXXXXXXXXX
\0\  \XXXXXXXXX
\\0\  \XXXXXXXX
X\\0\  \XXXXXXX
XX\\0\  \XXXXXX
XXX\\0\  \XXXXX
XXXX\\0\  \XXXX
XXXXX\\0\  \XXX
XXXXXX\\0\  \XX
XXXXXXX\\0\  \X
XXXXXXXX\\0\  \
XXXXXXXXX\\0\
XXXXXXXXXX\\0\
XXXXXXXXXXX\\0\
XXXXXXXXXXXX\\0
XXXXXXXXXXXXX\\

```

This is the top left corner.

I repeat this four times with variants on the original string (like reversing the bit in the middle) to get the other four corners.

# Answer
> 2 votes
# CJam, ~~131~~ ~~126~~ ~~102~~ 99 bytes

```
S'_42*SK,'XE*"//0/  /"+2*f>Gf<_2>
\W%2>.{"\/"_W%er" 000 ":_@}" 0 0"
[I6I63].*+s_W%+42/{N"||"@*}/S'_er

```

The two linefeeds are included to prevent horizontal scrolling. Try it online in the CJam interpreter.

### Idea

We start by modifying the string

```
XXXXXXXXXXXXXX//0/  /XXXXXXXXXXXXXX

```

by pushing 19 copies, discarding the first **n** characters for the **n**th copy and cutting off each results after the 16th character.

```
XXXXXXXXXXXXXX//
XXXXXXXXXXXXX//0
XXXXXXXXXXXX//0/
XXXXXXXXXXX//0/
XXXXXXXXXX//0/
XXXXXXXXX//0/  /
XXXXXXXX//0/  /X
XXXXXXX//0/  /XX
XXXXXX//0/  /XXX
XXXXX//0/  /XXXX
XXXX//0/  /XXXXX
XXX//0/  /XXXXXX
XX//0/  /XXXXXXX
X//0/  /XXXXXXXX
//0/  /XXXXXXXXX
/0/  /XXXXXXXXXX
0/  /XXXXXXXXXXX
/  /XXXXXXXXXXXX
  /XXXXXXXXXXXXX
 /XXXXXXXXXXXXXX

```

By discarding the first two strings, we obtain the upper right quadrant of the flag.

Now, if we reverse the order of the strings, once again discard the first two and swap the inclinations of the slashes, we obtain the upper left quadrant.

By concatenating the corresponding strings, with `" 000000 "` in the middle and appending a few runs of spaces and zeroes, we obtain

```
\  \XXXXXXXXXXXX  000000  XXXXXXXXXXXX//0/
0\  \XXXXXXXXXXX  000000  XXXXXXXXXXX//0/
\0\  \XXXXXXXXXX  000000  XXXXXXXXXX//0/
\\0\  \XXXXXXXXX  000000  XXXXXXXXX//0/  /
X\\0\  \XXXXXXXX  000000  XXXXXXXX//0/  /X
XX\\0\  \XXXXXXX  000000  XXXXXXX//0/  /XX
XXX\\0\  \XXXXXX  000000  XXXXXX//0/  /XXX
XXXX\\0\  \XXXXX  000000  XXXXX//0/  /XXXX
XXXXX\\0\  \XXXX  000000  XXXX//0/  /XXXXX
XXXXXX\\0\  \XXX  000000  XXX//0/  /XXXXXX
XXXXXXX\\0\  \XX  000000  XX//0/  /XXXXXXX
XXXXXXXX\\0\  \X  000000  X//0/  /XXXXXXXX
XXXXXXXXX\\0\  \  000000  //0/  /XXXXXXXXX
XXXXXXXXXX\\0\    000000  /0/  /XXXXXXXXXX
XXXXXXXXXXX\\0\   000000  0/  /XXXXXXXXXXX
XXXXXXXXXXXX\\0\  000000  /  /XXXXXXXXXXXX
XXXXXXXXXXXXX\\0  000000    /XXXXXXXXXXXXX
XXXXXXXXXXXXXX\\  000000   /XXXXXXXXXXXXXX
                  000000
000000000000000000000000000000000000000000
000000000000000000000

```

The second half of the flag contains almost exactly the same character, in inverted reading order (right to left, bottom to top).

All that's left to do to complete the entire flag is to push the first line, replace spaces with underscores in the last and introducing the vertical bars and actual linefeeds.

### Code

```
S'_42*S   e# Push a space, a string of 42 underscores and another space.
K,        e# Push [0 ... 19].
'XE*      e# Push a string of 14 X's.
"//0/  /" e# Push that string.
+2*       e# Concatenate and repeat the result twice.
f>        e# Push copies with 0, ..., 19 character removed from the left.
Gf<       e# Truncate each result after 16 characters.
_2>       e# Copy the array and discard its first two elements.
\W%2>     e# Reverse the original array and discard its first two elements.

.{        e# For each pair of corresponding strings in the arrays:
  "\/"    e#   Push "\/".
  _W%     e#   Reverse a copy to push "/\\".
  er      e#   Perform transliteration on the string from the right array..
  " 000 " e#   Push that string.
  :_      e#   Duplicate each charcter to push "  000000  ".
  @       e#   Rotate the string from the left array on top.
}         e#

" 0 0"    e# Push that string.
[I6I63]   e# Push [18 6 18 63].
.*        e# Vectorized repetition.
+s        e# Concatenate ad flatten.
_W%+      e# Push a reversed copy and concatenate.
42/       e# Split into chunks of length 42.
{         e# For each chunk:
  N       e#   Push a linefeed.
  "||"@*  e#   Join the string "||", using the chunk as separator.
}/        e#
S'_er     e# Replace spaces with underscores in the last string.

```

# Answer
> 1 votes
# Javascript ES6, ~~726~~ ~~725~~ ~~655~~ ~~647~~ 643 bytes

```
a="__";l=" ";b=l+l;c=`|
|`;d="X";e="0";f=b+e[r="repeat"](6)+b;g="\\  \\";h="//0/";i="/  /";Z="\\";A=Z+Z;j=A+0;k=d[r].bind(d);y=c+l[r](16)+f+l[r](16);z=c+e[r](42);B="/";C="\\0";D="0//";E=B+D;q=n=>k(n)+f+k(n);F=n=>g+q(n)+h;G=n=>c+k(n)+j+F(9-n)+k(3+n);H=n=>A+k(n+1)+c+k(n);I=n=>q(n)+g+e+H(8-n)+i+D;console.log(l+a[r](21)+`
|`+F(12)+c+e+F(11)+d+c+C+F(10)+d+d+c+j+F(9)+k(3)+c+d+j+F(8)+k(4)+G(2)+G(3)+G(4)+G(5)+G(6)+G(7)+G(8)+y+z+z+z+y+c+k(14)+B+l+f+H(13)+B+b+f+e+H(12)+i+f+C+H(11)+i+e+f+l+C+H(10)+i+"0/"+f+b+C+H(9)+i+D+I(0)+I(1)+I(2)+I(3)+I(4)+I(5)+I(6)+I(7)+I(8)+q(9)+g+e+A+c+b+E+q(10)+g+e+Z+c+l+E+q(11)+g+e+c+E+k(12)+a+e[r](6)+a+k(12)+Z+a+Z+"|")

```

# Answer
> 1 votes
# PHP, 240 bytes

```
 <?=str_pad(_,42,_)." ";for($o=18;$o--;)$r.="
".($s="|".substr("XXXXXXXXXXXXXX\\\\0\  \\XXXXXXXXXXXX//0/",$o,16)."  000").($v=strrev)(strtr($s,"\\","/"));echo$r;for(;$i<5;)echo"
",$s=str_pad("|",19,$i++%4?0:" ")."000",$v($s);echo"
",$v($r);

```

Note the space before the opening tag! Try it online.

# Answer
> 0 votes
# SpecBAS again - 507 Bytes

Here's a similar version to Brian's above (I don't have enough reputation to comment yet) but without the colour. It uses a very different method to generate the display.

```
10 DEF FN rr$(r$)=r$(2 TO)+r$(1): DEF FN rl$(r$)=r$(LEN r$)+r$( TO LEN r$-1)
20 a$="\  \"+"x"*14+"\\0",b$="x"*12+"//0/  /xx",c$="x"*14+"/  /0//",d$="\\"+"x"*14+"\  \0",e$="  000000  ": ?" ";"_"*42: DO 18: ?"|";a$( TO 16);e$;b$( TO 16);"|": a$=FN rl$(a$),b$=FN rr$(b$): LOOP: ?"|";TAB 17;e$;TAB 43;"|"'("|"+("0"*42)+"|"+#13)*3;"|";TAB 17;e$;TAB 43;"|": DO 18: ?"|";c$( TO 16);e$;d$( TO 16);"|": c$=FN rr$(c$),d$=FN rl$(d$): LOOP: ?#11;TAB 17;"__";TAB 25;"__";TAB 40;"__"

```

# Answer
> 0 votes
# Bubblegum, 213 bytes

```
00000000: b5d3 0106 4421 1080 6100 de29 e606 759c  ....D!..a..)..u.
00000010: 105d a4c3 6fdb 461f 030f f607 f019 994c  .]..o.F........L
00000020: 8cd7 c533 7b44 6f14 5177 118d 4aa9 653e  ...3{Do.Qw..J.e>
00000030: b3a2 13d6 c6c2 1d9d b076 6375 c2d8 b270  .........vcu...p
00000040: 5327 8c6d 5fac 4e18 bbb1 3a61 ecc1 6ab1  S'.m_.N...:a..j.
00000050: f662 b518 0b46 83b1 6034 180b 5683 b162  .b...F..`4..V..b
00000060: f5c5 58b1 1a8c 05a3 c158 b1fa 62ac 587d  ..X......X..b.X}
00000070: 3156 ac06 630f 8ed4 c1a9 85eb ebfe 8adf  1V..c...........
00000080: bf39 6da3 803b 67cc eab0 e08a 0663 0b93  .9m..;g......c..
00000090: d160 2c3f 8806 6b99 8c06 6bc1 1d0d c67a  .`,?..k...k....z
000000a0: 2968 3056 8c06 63c5 6830 568c 0663 c5e8  )h0V..c.h0V..c..
000000b0: 8bb5 62f5 c1d8 8cd1 1b6b 3346 2fac cd58  ..b......k3F/..X
000000c0: bdb0 3663 f4c6 da8c d10b 6f4b 63fc f018  ..6c......oKc...
000000d0: 4d3d 469f 1f                             M=F..

```

Try it online!

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


title: Sum the Vertex Connections

text:
# Question
Title: Sum the Vertex Connections
Let's say you have a positive integer *N*. First, build a **regular** polygon, that has *N* vertices, with the distance between neighbouring vertices being 1. Then connect lines from every vertex, to every other vertex. Lastly, calculate the length of all lines summed up together.

# Example

Given the input ***N = 6***, build a **hexagon** with lines connecting every vertex with the other vertices.

As you can see, there are a total of 6 border lines (length=1), 3 lines that have double the border length (length=2) and 6 other lines that we, by using the Pythagoras Theorem, can calculate the length for, which is

If we add the lengths of the lines together we get *(6 * 1) + (3 * 2) + (6 * 1.732) = **22.392***.

## Additional Information

As structures with 2 or less vertices are not being considered polygons, output 0 (or `NaN`, since distance between a single vertex doesn't make much sense) for N = 1, since a single vertice cannot be connected to other vertices, and 1 for N = 2, since two vertices are connected by a single line.

## Input

An integer N, in any reasonable format.

## Output

The length of all the lines summed up together, accurate to at least 3 decimal places, either as a function return or directly printed to `stdout`.

## Rules

* Standard loopholes are forbidden.
* This is , so the shortest code in bytes, in any language, wins.

## Good luck!

# Test Cases

```
(Input) -> (Output)
1 -> 0 or NaN
2 -> 1
3 -> 3
5 -> 13.091
6 -> 22.392

```

# Answer
> 13 votes
# Python 3 ~~(with sympy)~~,  ~~61 60 58 54~~  48 bytes

-6 (maybe even -10 if we do not need to handle `n=1`) thanks to xnor (further trigonometric simplification plus further golfing to handle edge case of 1 and save parentheses by moving a (now unnecessary) `float` cast).

<sup>~~Hopefully~~ beatable with no ~~3rd party~~ libraries? Yes!! ~~but~~ Lets get things rolling...</sup>

```
lambda n:1%n*n/2/(1-cos(pi/n))
from math import*

```

**Try it online!**

This uses a formula for the sum of the lengths if a polygon is inscribed inside a unit circle, `n*cot(pi/2/n)/2` and adjusts the result to one for the side length being one by dividing by the sin of that cord length `sin(pi/n)`.

The first formula is acquired by considering the `n-1` cord lengths of all the diagonals emanating from one corner which are of lengths `sin(pi/n)` (again), `sin(2*pi/n)`, ..., `sin((n-1)pi/n)`. The sum of this is `cot(pi/2/n)`, there are `n` corners so we multiply by `n`, but then we've double counted all the cords, so we divide by two.

The resulting `n*cot(pi/2/n)/2/sin(pi/n)` was then simplified by xnor to `n/2/(1-cos(pi/n))` (holding for `n>1`)

...this (so long as the accuracy is acceptable) now no longer requires `sympy` over the built-in `math` module (`math.pi=3.141592653589793`).

# Answer
> 7 votes
# Python, 34 bytes

```
lambda n:1%n*n/abs(1-1j**(2/n))**2

```

Try it online!

Uses the formula `n/2/(1-cos(pi/n))` simplified from Jonathan Allan. Neil saved 10 bytes by noting that Python can compute roots of unity as fractional powers of `1j`.

Python without imports doesn't have built-in trigonometric functions, `pi`, or `e`. To make `n=1` give `0` rather than `0.25`, we prepend `1%n*`.

A longer version using only natural-number powers:

```
lambda n:1%n*n/abs(1-(1+1e-8j/n)**314159265)**2

```

Try it online!

# Answer
> 6 votes
# MATL, ~~16~~ 15 bytes

```
t:=ZF&-|Rst2)/s

```

Try it online! Or verify all test cases.

This uses a commit which introduced the FFT (Fast Fourier Transform) function, and which predates the challenge by 8 days.

### Explanation

The code uses this trick (adapted to MATL) to generate the roots of unity. These give the positions of the vertices as complex numbers, except that the distance between consecutive vertices is not normalized to 1. To solve that, after computing all pairwise distances, the program divides them by the distance between consecutive vertices.

```
t       % Implicit input, n. Duplicate
:       % Range: [1 2 ... n-1 n]
=       % Isequal, element-wise. Gives [0 0 ... 0 1]
ZF      % FFT. Gives the n complex n-th roots of unity
&-|     % Matrix of pairwise absolute differences
R       % Upper triangular matrix. This avoids counting each line twice.
s       % Sum of each column. The second entry gives the distance between
        % consecutive vertices
t2)/    % Divide all entries by the second entry
s       % Sum. Implicit display

```

# Answer
> 5 votes
# Grasshopper, 25 primitives (11 components, 14 wires)

I read a meta post about programs in GH and LabVIEW, and follow similar instructions to measure a visual language.

Print `<null>` for N = `0, 1, 2`,because `Polygon Primitive` cannot generate a polygon with 2 or fewer edges and you will get an empty list of lines.

Components from left to right:

* `Side count` slider: input
* Polygon Primitive: draw a polygon on canvas
* Explode: Explode a polyline into segements and vertices
* Cross reference: build holistic cross reference between all vertices
* Line: draw a line between all pairs
* Delete Duplicate Lines
* Length of curve
* (upper) Sum
* (lower) Division: because `Polygon Primitive` draws polygon based on radius, we need to scale the shape
* Multipication
* Panel: output

# Answer
> 4 votes
# Mathematica, 26 bytes

uses @Jonathan Allan's formula

```
N@Cot[Pi/2/#]/2Csc[Pi/#]#&

```

Try it online!

-1 byte junghwan min

# Answer
> 2 votes
# Haskell, 27 bytes

```
f 1=0
f n=n/2/(1-cos(pi/n))

```

Try it online!

I just dove into Haskell, so this turns out to be a fair beginner golf (that is, copying the formula from other answers).

I've also tried hard to put `$` somewhere but the compiler keeps yelling at me, so this is the best I've got. :P

# Answer
> 2 votes
# Jelly, ~~13~~ ~~12~~ 11 bytes

Uses Jonathan Allan's formula (and thanks to him for saving 2 bytes)

```
ØP÷ÆẠCḤɓ’ȧ÷

```

Try it online!

I've always been pretty fascinated with Jelly, but haven't used it much, so this might not be the simplest form.

# Answer
> 1 votes
# Javascript (ES6), 36 bytes

```
n=>1%n*n/2/(1-Math.cos(Math.PI/n))

```

Port of @JonathanAllan's Python 3 answer

```
f=n=>1%n*n/2/(1-Math.cos(Math.PI/n))
```

```
<input id=i type=number oninput="o.innerText=f(i.value)" /><pre id=o>
```

---
Tags: code-golf, math, geometry
---


title: Oscillation equality

text:
# Question
Title: Oscillation equality
We have objects that oscillate between two integer points, `[l, r]`, at the speed of one unit per time unit, starting at `l` on `t=0`. You may assume `l < r`. For example, if an object oscillates on `[3, 6]`, then we have:

```
t=0 -> 3
t=1 -> 4
t=2 -> 5
t=3 -> 6
t=4 -> 5
t=6 -> 4
t=7 -> 3
t=8 -> 4

```

Etc. But objects oscillate continuously, so we also have `t=0.5 -> 3.5` and `t=3.7 -> 5.3`.

Given two objects oscillating between `[l1, r1]`, `[l2, r2]`, determine if there is ever a time `t` such that the two objects share the same position. You make take `l1, r1, l2, r2` in any convenient format, and output any truthy/falsy values.

---

Truthy inputs:

```
[[3, 6], [3, 6]]
[[3, 6], [4, 8]]
[[0, 2], [2, 3]]
[[0, 3], [2, 4]]
[[7, 9], [8, 9]]

```

Falsy inputs:

```
[[0, 3], [3, 5]]
[[0, 2], [2, 4]]
[[5, 8], [9, 10]]
[[6, 9], [1, 2]]
[[1, 3], [2, 6]]

```

# Answer
# Python 2, 69 bytes

```
l,r,L,R=input()
d=r-l;k=1
while(R-L)*k%d:k+=1
print r-L>=k%2*d/k<=R-l

```

Try it online!
> 8 votes

# Answer
# Husk, 13 bytes

```
VEΣUẊeTmȯ…¢mD

```

Takes input in format `[[l,r],[L,R]]`. Returns `0` for falsy instances and a positive integer for truthy instances. Try it online!

## Explanation

The main ideas are

1. A collision can only happen at an integer or half-integer coordinate.
2. It's enough to simulate the system until a repetition of two consecutive states is encountered.

Here's the code annotated.

```
VEΣUẊeTmȯ…¢mD  Implicit input, say [[0,2],[2,3]]
       mȯ      For both pairs do:
           mD   Double each: [[0,4],[4,6]]
          ¢     Cycle: [[0,4,0,4..],[4,6,4,6..]]
         …      Rangify: [[0,1,2,3,4,3,2,1,0,1,2..],[4,5,6,5,4,5,6..]]
      T        Transpose: [[0,4],[1,5],[2,6],[3,5],[4,4],[3,5],[2,6]..
    Ẋe         Adjacent pairs: [[[0,4],[1,5]],[[1,5],[2,6]],[[2,6],[3,5]],[[3,5],[4,4]]..
   U           Prefix of unique elements: [[[0,4],[1,5]],[[1,5],[2,6]],[[2,6],[3,5]],[[3,5],[4,4]]..[[1,5],[0,4]]]
  Σ            Concatenate: [[0,4],[1,5],[1,5],[2,6],[2,6],[3,5],[3,5],[4,4]..[1,5],[0,4]]
VE             Index of first pair whose elements are equal (or 0 if not found): 8

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~77~~ ~~69~~ 61 bytes

```
If[#>#3,#0[##3,#,#2],(z=GCD[x=#-#2,#3-#4])Mod[x/z,2]<=#2-#3]&

```

A pure function taking the four arguments `l1, r1, l2, r2` as input: e.g., `[0,3,2,4]` when the intervals are `[0,3]` and `[2,4]`.

Try it online!

### How it works

To get a point in `[a,b]` close to a point in `[c,d]`, assuming `a<c<b<d`, we want an odd multiple of `b-a` within `b-c` of an even multiple of `d-c`. If `b-a` has more factors of `2` than `d-c`, we can make this happen exactly: there will be a time when the first point is at `b` and the second point is at `c`, and then we're in good shape. If not, then the best we can do is the GCD of `b-a` and `d-c`.
> 2 votes

# Answer
# JavaScript (ES6), ~~104~~ 100 bytes

A naive implementation that just runs the simulation. Takes **(a, b, c, d)** as 4 distinct variables.

```
(a,b,c,d)=>(g=(X,Y)=>x==y|x+X==y&(y+=Y)==x||(x+=X)-a|y-c&&g(x>a&x<b?X:-X,y>c&y<d?Y:-Y))(1,1,x=a,y=c)

```

### Test cases

```
let f =

(a,b,c,d)=>(g=(X,Y)=>x==y|x+X==y&(y+=Y)==x||(x+=X)-a|y-c&&g(x>a&x<b?X:-X,y>c&y<d?Y:-Y))(1,1,x=a,y=c)

console.log('Truthy')
console.log(f(3, 6, 3, 6))
console.log(f(3, 6, 4, 8))
console.log(f(0, 2, 2, 3))
console.log(f(0, 3, 2, 4))
console.log(f(7, 9, 8, 9))

console.log('Falsy')
console.log(f(0, 3, 3, 5))
console.log(f(0, 2, 2, 4))
console.log(f(5, 8, 9, 10))
console.log(f(6, 9, 1, 2))
```
> 2 votes

# Answer
## JavaScript (ES6), 89 bytes

```
(a,b,c,d)=>[...Array((b-=a)*(d-=c)*4)].some((g=e=>i/e&2?e-i/2%e:i/2%e,i)=>a+g(b)==c+g(d))

```

Takes `l1,r1,l2,r2` as separate arguments. Explanation: The simulation is guaranteed to repeat after `(r1-l1)*(r2-l2)*2` time units (or a factor thereof); `g` calculates the offset of the appropriate object after `i/2` time units, so `i` needs to range up to `(r1-l1)*(r2-l2)*4`.
> 1 votes

# Answer
# 05AB1E, ~~12~~ ~~10~~ 14 bytes

*+4 bytes to handle negative ranges*

Return 0 if falsy, or a positive integer otherwise

Use Zgarb's idea of doubling values to make same position detection easier

Thanks to @Zacharý for pointing out my mistakes

```
ÄZU\·εXиŸ}øüQO

```

Try it online!

**Explanations:**

```
ÄZU\·εXиŸ}øüQO
ÄZU\            Store in X the largest absolute number in the lists
    ·           Double lists ([3,6],[4,8] => [6,12],[8,16])
     ε   }      For each...
      X             Push X
       и            List-repeat that much times ([6,12]*12 => [6,12,6,12,6,...])
        Ÿ           Rangify ([6,12,6,...] => [6,7,8,9,10,11,12,11,...])
          ø     Zip lists ([6,7,8,...],[8,9,10,...] => [6,8],[7,9],[8,10],...)
           üQ   1 if both elements of a pair are equal, 0 otherwise
             O  Sum result list (=0 if the same position is never shared)
                Implicit output

```
> 1 votes

# Answer
# Java (OpenJDK 8), 81 bytes

```
(l,r,L,R)->{int d=r-l,k=0;for(;(R-L)*++k%d>0;);return(r-L<R-l?r-L:R-l)>=k%2*d/k;}

```

Try it online!

Reusing xnor's Python algorithm.
> 0 votes

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


title: Draw an ASCII art phone keypad

text:
# Question
Title: Draw an ASCII art phone keypad
Draw the following in the fewest bytes possible:

```
-------------------------
|       |  ABC  |  DEF  |
|   1   |   2   |   3   |
-------------------------
|  GHI  |  JKL  |  MNO  |
|   4   |   5   |   6   |
-------------------------
| PQRS  |  TUV  | WXYZ  |
|   7   |   8   |   9   |
-------------------------
|       |       |       |
|   *   |   0   |   #   |
-------------------------

```

# Answer
> 6 votes
# pb, 240 bytes

```
<[8]^w[Y!14]{w[X!24]{>[8]b[124]^b[124]v}vw[X!-8]{b[45]<}vv}>[12]^[12]b[49]>[12]w[T!8]{<[4]b[T+50]^<w[X%8!6]{b[65+T*3+X%8%3]>}>[10]vw[B!124]{<[24]vvv}t[T+1]}<[4]b[42]>[8]b[48]>[8]b[35]^[4]>w[B!0]{b[B+2]<}b[87]w[X!2]{<[5]w[B!0]{b[B+1]<}}b[80]

```

(This program will prompt for input in the current version of pbi, because it goes to Y=-1 and the `B` variable tries to update itself. Even if you do enter input, nothing will break. It's annoying but it's better than the old version that prompted for input no matter what.)

pb is a language all about treating the terminal as a 2D canvas. To output, you have to move the "brush" (a point represented by the current values of the X and Y variables) to where you want that character to go and put it there. It's cumbersome for things like printing out a word but for art it's often convenient.

This program doesn't actually draw exactly what the question specifies. (Wait, don't downvote me yet! Let me explain!)

Drawing boxes with loops is pretty easy, but there's a catch. If you repeat the following shape:

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

```

You do get boxes, but the right and bottom ones will be open. You can manually draw the extra sides, but that costs bytes. To get around this, my program actually draws this, with the open edges on the left and top:

```
        |       |       |       |
        |       |       |       |
 --------------------------------
        |       |  ABC  |  DEF  |
        |   1   |   2   |   3   |
 --------------------------------
        |  GHI  |  JKL  |  MNO  |
        |   4   |   5   |   6   |
 --------------------------------
        | PQRS  |  TUV  | WXYZ  |
        |   7   |   8   |   9   |
 --------------------------------
        |       |       |       |
        |   *   |   0   |   #   |
 --------------------------------

```

> But monorail! That's not what the spec says! You can't just draw something else because it's easier and you feel like it! Also, while I have your attention, you are very smart and cute.

Shh, shh, it's okay. pb allows you to "write" to a point on the canvas with one or more negative values in its coordinates. The value is stored while the program runs, but only points where X and Y are both \>= 0 are actually written to the screen. This program positions the brush so that areas that are tinted in this image have a negative X or Y:

Although extra lines are "drawn", they're never printed.

After looping through and creating the grid, this program fills in the top nine boxes. The first is hardcoded, a 1 is written and the program moves on. The other eight are generated programmatically. Ignoring code for moving to the next box, noticing when the row is empty, etc (assume the brush always starts on the bottom row of the box and in the middle column), this is what is run eight times:

```
b[T+50]
^<w[X%8!6]{b[65+T*3+X%8%3]>}
t[T+1]

```

Even knowing that `b` is the command to write a character, `^v<>` move the brush and `w[a!b]{}` runs the code in curly braces until `a != b`, this is hard to follow. The first important thing to note is that you can't define variables in pb. There are six in every program and you have to learn to live with them. Second, `T` is the only variable that you can actually use the way you're used to using variables; assigning a value and then reading it later. Every other variable either can't be set and just tells you something about the point in the canvas you're on or can only be set indirectly and with side effects (`^v<>` change `X` and `Y`, which also changes the brush location. `c` sets `P` to `(P+1)%8`, which also changes the output colour). Keeping a counter for what number needs to be written and which letters is simply impossible. Instead, this code only keeps track of the number and figures out the letters based on it. Here's how:

```
b[T+50]                       # We start printing at box 2 with T==0, 0+50=='2'
^<                            # Go up and to the left of the number
w[X%8!6]{                     # Take the X coordinate mod 8 so it's like we're in
                              # the leftmost box. Until hitting the sixth cell:
    b[                          # Write this character:
      65                          # 'A'
      + T * 3                     # Number of current box - 2 (letters start at
                                  # 2) * 3 (3 letters per box)
      + X % 8 % 3                 # X % 8 makes every box behave like it's on the
                                  # left, % 3 puts 0 at the point where the first
                                  # letter goes, then 1, then 2. This is how each
                                  # letter is made different in a box.
    ]
    >                           # Move to the right
}
t[T+1]                        # Box is done, increase counter

```

This is imperfect, as only 3 letters are put into boxes 7 and 9. So, after filling the bottom row (simple hardcoding), each letter in box 9 is increased by 2 and the W is placed manually. Similarly, every letter in boxes 7 and 8 are increased by 1 and the P is placed manually.

**Ungolfed:**

```
<[8]^                         # Go to (-8, -1)
w[Y!14]{                      # While the brush is not on Y=14:
    w[X!24]{                      # While the brush is not on X=24:
        >[8]                          # Go right 8
        b[124]^b[124]v                # Draw a pipe at the current location and above it
    }
    vw[X!-8]{b[45]<}              # Go down and draw hyphens all the way until X=-8
    vv                            # Go down by 2 to start drawing next row
}
>[12]^[12]b[49]               # Write a 1 in the first box
>[12]                          # Go to the bottom pipe on the right of box 2
w[T!8]{                       # While T is not 8:
    <[4]                          # Go to center cell of the box
    b[T+50]                       # Write the number that belongs there
    ^<w[X%8!6]{b[65+T*3+X%8%3]>}  # Write the letters
    >[10]v                        # Go to the next box
    w[B!124]{                     # If the next box isn't there:
        <[24]vvv                      # Go down a row
    }
    t[T+1]                        # Increase counter
}
<[4]b[42]>[8]b[48]>[8]b[35]   # Put the asterisk, 0 and hash in their boxes
^[4]>w[B!0]{b[B+2]<}          # Increase all letters in the 9th box by 2
b[87]                         # Put a W in the 9th box
w[X!2]{<[5]w[B!0]{b[B+1]<}}   # Increase all letters in the 7th/8th box by 1
b[80]                         # Put a P in the 7th box

```

# Answer
> 6 votes
# Brainfuck, 565 characters (212 bytes)

```
 1 +++++[>+++++>>>>+++++++++>>>>+++++++++++++<<<<<<<<<-]    //initialize
 2 >[->>+++++>>>>+++++<<<<<<]                               //initialize
 3 >>>++++++++[-<<<++++++>++++>>>>>>++++<<<<]               //initialize
 4 ++++++++++<->>>>-<<                                      //initialize
 5
 6 //print first block (123)
 7 >+++++[-<.....>]<<.>>>.>.......<.<++[->>..>.+.+.+<..<.<]<<.<.>>>+++[-<<<<...<+.>...>.>>>]<<.
 8 //print second block (456)
 9 >>+++++[-<.....>]<<.>>>.<+++[->>..>.+.+.+<..<.<]<<.<.>>>+++[-<<<<...<+.>...>.>>>]<<.
10 //print third block (789)
11 >>+++++[-<.....>]<<.>>>.>.>.+.+.+.+<..<.>..>.+.+.+<..<.>.>.+.+.+.+<..<.<<<.<.>>>+++[-<<<<...<+.>...>.>>>]<<.
12 //print fourth block (*0#)
13 >>+++++[-<.....>]<<.>>>.<+++[->>.......<.<]<<.<.<...<---------------.>...>.<...<++++++.>...>.<...<-------------.>...>.>>><<.
14 //print last block (the remaining dashes)
15 >>+++++[-<.....>]

```

Plain code:

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

```

# Answer
> 3 votes
## Bubblegum, 103 bytes

Hexdump:

```
00000000: d3d5 c501 b86a 1420 0048 3b3a 3983 6917  .....j. .H;:9.i.
00000010: 5737 200d 9631 84c8 2818 4169 6310 cd85  W7 ..1..(.Aic...
00000020: cb30 b069 ee1e 9e60 b55e de3e 60da d7cf  .0.i...`.^.>`...
00000030: 1f66 9a09 d414 5328 6d46 d0b4 80c0 a060  .f....S(mF.....`
00000040: b0da 90d0 3010 1d1e 1119 0533 cd1c 6a8a  ....0......3..j.
00000050: 0594 b624 ec36 984f 5169 b08c 1654 c400  ...$.6.OQi...T..
00000060: 4a2b e337 0d00 04                        J+.7...

```

Boring and practical.

# Answer
> 2 votes
## Python 2, 147 bytes

```
print(("|%s"*3+"|\n")*2).join(["-"*25+"\n"]*5)%tuple(x.center(7)for x in" ABC DEF 1 2 3 GHI JKL MNO 4 5 6 PQRS TUV WXYZ 7 8 9    * 0 #".split(' '))

```

A quick draft of a basic strategy. Uses string formatting to insert the labels, which are hardcoded in a long string.

# Answer
> 2 votes
# C,160 bytes

```
j,k,l,m,n=65;main(i){for(i=325;i--;i%25||puts(""))l=i-139,putchar((k=i/25%3)?(j=i%25%8)?k-2?j-4?32:"123456789*0#"[m++]:j/3-1&&l*l!=64||i%290<75?32:n++:'|':45);}

```

It makes sense to take avantage of the fact that the letters are in sequence. This code runs through the 325 characters of the keypad, and prints either a space or the next letter as needed.

**Ungolfed**

```
i,    //main loop variable
j,    //x position within key
k,    //y position within key
l,    //distance from character 139 (the space immediately left of T)
m,    //symbol counter
n='A';//letter counter

main(){
  for(i=325;i--;i%25||puts(""))             //loop through 325 characters. puts() adds a newline at the end of each line of 25
    l=i-139,                                //calculate l. if it is 8, we need to print P or W
    putchar((k=i/25%3)?                     //if row not divisible by 3
      (j=i%25%8)?                             //if position on row not a |
         k-2?                                   //if row mod 3 = 1
           j-4?' ':"123456789*0#"[m++]            //print a space or a character from the string (increment m for next time)
         :                                      //else row mod 3 must = 2
           j/3-1&&l*l!=64||i%290<75?' ':n++       //print a space or a letter according to formula (increment n to the next letter)
      :'|'                                    //else print |
    :
    '-')                                    //else print -
;}

// j/3-1 returns a 0 when in any of the three columns where letters are generally found
// l*l!=64 returns a 0 at the correct place fo P and W
// i%290<75 returns a 1 for keys 1,*,0,#, supressing the printing of letters/symbols

```

# Answer
> 2 votes
# Java, 296 bytes

Golfed:

```
class a{static void main(String[]a){System.out.println("-\n|&|  ABC  |  DEF  |\n|$1$|$2$|$3$|\n-\n|  GHI  |  JKL  |  MNO  |\n|$4$|$5$|$6$|\n-\n| PQRS  |  TUV  | WXYZ  |\n|$7$|$8$|$9$|\n-\n|&|&|&|\n|$*$|$0$|$#$|\n-".replace("&","       ").replace("$","   ").replace("-","--------------------"));}}

```

Ungolfed:

```
public class AsciiPhoneKeypad{
    public static void main(String []args){
        // - for twenty-five dashes
        // $ for three spaces
        // & for seven spaces
        System.out.println("-\n|&|  ABC  |  DEF  |\n|$1$|$2$|$3$|\n-\n|  GHI  |  JKL  |  MNO  |\n|$4$|$5$|$6$|\n-\n| PQRS  |  TUV  | WXYZ  |\n|$7$|$8$|$9$|\n-\n|&|&|&|\n|$*$|$0$|$#$|\n-"
        .replace("&","       ").replace("$","   ").replace("-","--------------------"));
     }
}

```

# Answer
> 1 votes
## JavaScript (ES6), ~~184~~ 182 bytes

```
f=
_=>`-
! |  ABC  |  DEF  |
!1!2!3|
-
|  GHI  |  JKL  |  MNO  |
!4!5!6|
-
| PQRS  |  TUV  | WXYZ  |
!7!8!9|
-
! ! ! |
!*!0!#|
-`.replace(/-|!./g,s=>s<`-`?`|   ${s[1]}   `:s.repeat(25))
;document.write('<pre>'+f());
```

The rows of dashes are obviously compressible and the digits were too but I couldn't do anything with the letters. Edit: Saved 1 of 2 bytes thanks to @Shaggy.

# Answer
> 1 votes
# Lua, 209 bytes

Golfed:

```
a=("-\n|&|  ABC  |  DEF  |\n123|\n-\n|  GHI  |  JKL  |  MNO  |\n456|\n-\n| PQRS  |  TUV  | WXYZ  |\n789|\n-\n|&|&|&|\n*0#|\n-"):gsub("&","       "):gsub("([0-9*#])","|   %1   "):gsub("-",("-"):rep(25))print(a)

```

Ungolfed:

```
-- "&" for seven spaces
-- "1" -> "|   1   "
-- "-" -> twenty-five dashes

a="-\n|&|  ABC  |  DEF  |\n123|\n-\n|  GHI  |  JKL  |  MNO  |\n456|\n-\n| PQRS  |  TUV  | WXYZ  |\n789|\n-\n|&|&|&|\n*0#|\n-"

a = a:gsub("&","       ")

a = a:gsub("([0-9*#])","|   %1   ")

a = a:gsub("-",("-"):rep(25))

print(a)

```

# Answer
> 0 votes
## Python 2, 168 bytes

A straightforward method using no built-in compression:

```
for i in range(13):print['-'*25,'|'+'|'.join(["123456789*0#"," ABC DEF GHI JKL MNO PQRS TUV WXYZ   ".split(' ')][i%3%2][i/3%4*3+m].center(7)for m in[0,1,2])+'|'][i%3>0]

```

# Answer
> 0 votes
## CJam, 128 bytes

```
'-25*N+:A" ABC DEF GHI JKL MNO PQRS TUV WXYZ   "S/3/{['|\{_,5\-S*\"  |"}%N]:+:+}%"123456789*0#"1/3/{['|\{S3*_@@'|}%N]:+:+}%.+A*A

```

Try it online.

# Answer
> 0 votes
## Perl, 142+1 = 143 bytes

```
$ perl -MCompress::Zlib x.pl
$ cat x.pl
print uncompress(<DATA>)
__DATA__
x<9c><d3><d5><c5>^A<b8>j^T ^@H;:9<83>i^WW7 ^M<96>1<84><c8>(^XAic<10><cb>0<b0>i<ee>^^<9e>`<b5>^<de>>`<da><d7><cf>^_f<9a> <d4>^TS(mFд<80> `<b0>ڐ<d0>0^P^]^^^Q^Y^E3<cd>^\j<8a>^E<94><b6>$<ec>6<98>OQi<b0><8c>^VT<c4>^@J+<e3>7^M^@^D:@k

```

Unprintable characters, so uuencoded version is below.

```
$ cat x.pl.uue
begin 664 x.pl
M<')I;G1?=6YC;VUP<F5S<R@\1$%403XI"E]?1$%405]?"GB<T]7%`;AJ%"``
M2#LZ.8-I%U<W(`V6,83(*!A!:6,0S87+,+!I[AZ>8+5>WCY@VM?/'V::"=04
M4RAM1M"T@,"@8+#:D-`P$!T>$1D%,\T<:HH%E+8D[#:83U%IL(P65,0`2BOC
(-PT`!#I`:PH`
`
end
$

```

# Answer
> 0 votes
# Python 3.5 - 240 bytes:

```
k=' ABC DEF 1 2 3 GHI JKL MNO 4 5 6 PQRS TUV WXYZ 7 8 9    * 0 #'.split(' ')
for _ in range(8):
 print('\n',end='')
 if _%2==0:print("-"*27+'\n',end='')
 [print('|{}|'.format(g.center(7)),end='')for g in k[:3:1]];del k[:3:1]
print('\n'+"-"*27)

```

Prints just what the OP wants, although it may be a bit long.

# Answer
> 0 votes
# Python 2, 200

```
r=str.replace;print r(r(r(r(r("""-.|  ABC`DEF`
,1=,2=,3 `-|  GHI`JKL`MNO`
,4=,5=,6 `-| PQRS`TUV`WXYZ |
,7=,8=,9 `-...|
,*=,0=,# `-""","-","\n"+"-"*25+"\n"),".",",= "),",","|="),"`","  |  "),"=","   ")

```

Simple replacing strategy.

# Answer
> 0 votes
# ///, 154 characters

```
/%/=====//=/-----//?/ ! //!/}  //{/ }//}/  |//(/|   /%
(  !ABC!DEF}
(1?2?3{
%
|  GHI!JKL!MNO}
(4?5?6{
%
| PQRS!TUV} WXYZ}
(7?8?9{
%
(  !   !   }
(*?0?#{
%

```

# Answer
> 0 votes
# GML (Game Maker Language) 8.0, 269 bytes

```
a='-------------------------'b='   |   'c='  |#|   'draw_text(0,0,a+"#|       |  ABC  |  DEF"+c+"1"+b+"2"+b+"3   |#"+a+"#|  GHI  |  JKL  |  MNO"+c+"4"+b+"5"+b+"6   |#"+a+"#| PQRS  |  TUV  | WXYZ"+c+"7"+b+"8"+b+"9   |#"+a+"#|    "+b+" "+b+"  "+c+"*"+b+"0"+b+"\#   |#"+a)

```

In Game Maker, `#` is the newline character and it can be escaped by `\#`

# Answer
> 0 votes
# Python 2, 134 bytes

This source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`.

```
00000000: efbb bf70 7269 6e74 2778 01d3 c505 b86a  ...print'x.....j
00000010: 1420 5c30 483b 3a39 8369 1757 3720 5c72  . \0H;:9.i.W7 \r
00000020: 9631 84c8 2818 4169 6310 cd85 d734 770f  .1..(.Aic....4w.
00000030: 4fb0 5a2f 6f1f 30ed ebe7 0f33 cd04 6a8a  O.Z/o.0....3..j.
00000040: 2994 3623 685a 4060 5030 586d 4868 1888  ).6#hZ@`P0XmHh..
00000050: 0e8f 888c 8299 660e 35c5 024a 5b12 345c  ......f.5..J[.4\
00000060: 7202 3068 b08c 1654 c45c 304a 2be3 375c  r.0h...T.\0J+.7\
00000070: 725c 3004 3a40 6b27 2e64 6563 6f64 6528  r\0.:@k'.decode(
00000080: 277a 6970 2729                           'zip')

```

# Answer
> 0 votes
# 05AB1E, 91 bytes

```
•O«ò•3B7ô'-7×.ø'|ìε3×}'|«D¦Ð)˜»A3ô5£ðý"pqrs tuvwxyz"‚J5úR12úRv0y.;}1ð:2'A:9LJ"*0#"«v'Ay.;}u

```

Try it online!

# Answer
> 0 votes
# , ~~105~~ 103 bytes

```
9!:7'|'9}11#'-'
echo'PW'(7 2;7 18)}":_3;/\(12{.'',8 3$65{26-.&'PW'\a.),:&(5|.7{.])"1' ',.'123456789*0#'

```

Try it online!

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


title: Print NxN spiral of ascending numbers

text:
# Question
Title: Print NxN spiral of ascending numbers
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

```
4

```

Output:

```
01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07

```

I am interested in the algorithm and the cleanliness of the implementation. So, the white space does not count and the upper limit for N is 42.

# Answer
> 6 votes
## Python

```
n=input()

matrix=[[j+1]*n for j in range(n)]

x=y=0
for i in range(n)[::-2]:
    x+=i*4;y+=1

    for j in range(i):
        matrix[j+y-1][y]=x+j

    matrix[y-1][y:y+i]=range(x,x-i,-1)

    R=matrix[n-y][y-1]+1
    matrix[n-y][y:n-y+1]=range(R,R+i)

    for j in range(y,y+i-1):
        matrix[j][n-y]=matrix[j-1][n-y]-1

for row in matrix:
    print ' '.join(`r`.zfill(len(`n*n`)) for r in row)

```
* An approach that precalculate corner numbers. Eg, for 9x box, 32 56 72 80, which is (n-1)\*4 where n is box sizes (9,7,5,3) in this case.
* Right side of those numbers are 1-, and top to bottom is 1+, so basically generate from left to right, top to bottom, bottom to right, right to top side.

```
$ echo 9 | python codegolf-769-me.py
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17

```

Other tests

```
$ echo 2 | python codegolf-769-me.py
1 4
2 3

$ echo 5 | python codegolf-769-me.py
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

$ echo 10 | python codegolf-769-me.py
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019

```

# Answer
> 5 votes
In Ruby:

```
N=gets.to_i

index = -N
width = N
result = []
n = 0
dir=-1

while n < N*N
        dir = (dir + 1) % 4
        dir_x, dir_y = [[0,1],[1,0],[0,-1],[-1,0]][dir]
        width -= 1 if [1,3].include?(dir)

        1.upto(width) { |m|
                n += 1
                index += dir_y * N + dir_x
                result[index] = n
        }
end

width = (N*N).to_s.size
result.each_slice(N) { |l|
        print l.map {|n| "%0#{width}d" % n }.join(" "), "\n"
}

```

Test:

```
$ ruby1.9 769.rb <<< 9
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17

```

An other solution using calculations from here :

```
N=gets.to_i
r=[]

tr=->x,y{ x+(N-1)/2 + (y+(N-1)/2+(N-1)%2)*N }

r[tr[0,0]] = N*N

1.upto(N*N-1) { |n|
        shell = ((Math.sqrt(n)+1)/2).to_i
        leg = (n-(2*shell-1)**2)/(2*shell)
        element = (n-(2*shell-1)**2)-2*shell*leg-shell+1
        x,y = [[element,-shell],[shell,element],[-element,shell],[-shell,-element]][leg]
        r[tr[x,y]] = N*N-n
}

r.each_slice(N) {|l|
        puts l.map { |n|
                "%0#{(N*N).to_s.size}d" % (n or 0)
        }.join(" ")
}

```

Test:

```
$ ruby1.9 769-2.rb <<< 5
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

```

# Answer
> 5 votes
In Python3:

```
n=int(input())
results = {}
val = 1
location = (0,0)
direction = (0,1)

def nxt():
    return (location[0]+direction[0], location[1]+direction[1])

while val<=n*n:
    if set([-1,n]).intersection(nxt()) or nxt() in results:
        direction = (direction[1],direction[0]*-1)

    results[location], location, val = str(val), nxt(), val+1

slen = len(str(n*n))
for y in range(n):
    print( *[results[(x,y)].rjust(slen,'0') for x in range(n)] )

```

Sample Output for 7:

```
01 24 23 22 21 20 19
02 25 40 39 38 37 18
03 26 41 48 47 36 17
04 27 42 49 46 35 16
05 28 43 44 45 34 15
06 29 30 31 32 33 14
07 08 09 10 11 12 13

```

**edit: A recursive solution - 263 Bytes**

```
def a(m,s):
 b,r,t=m-s*s+1,s-1,range
 return[[[]],[[m]]][s]if s<2 else[[b]+list(t(b+4*r-1,b+3*r-1,-1))]+[[b+y+1]+a(m,s-2)[y]+[b+3*r-y-1]for y in t(s-2)]+[list(t(b+r,b+2*r+1))]
n=int(input())
for r in a(n*n,n):
 print(*[str(x).zfill(len(str(n*n)))for x in r])

```

# Answer
> 4 votes
Java Solution

```
public static void main(String[] args) {
        int INPUT = 5;
        String[][] grid = new String[INPUT][INPUT];
        int xDirection = 0;
        int yDirection = 0;
        int flag = 1;
        for (int i = 0; i < INPUT * INPUT; i++) {
            String temp = "";
            for (int k = 0; k < (""+INPUT*INPUT).length() - ("" + (i + 1)).length(); k++) {
                temp += "" + 0;
            }
            temp += (i + 1);

            if (xDirection > INPUT-1)
                {flag=2; yDirection++; xDirection--; i--; continue;}
            else if (yDirection > INPUT -1)
                {flag=3; yDirection--; xDirection--; i--; continue;}
            else if (xDirection < 0)
                {flag=4; xDirection++; yDirection--; i--; continue;}

            if ( grid[xDirection][yDirection]==null ){
                    grid[xDirection][yDirection] = ""+temp;
            }
                else{
                if (flag ==1 ) {
                    flag=2;
                    xDirection--;
                }
                else if (flag ==2){
                    flag=3;
                    yDirection--;
                }
                else if (flag==3){
                    flag=4;
                    xDirection++;
                }
                else{
                    flag=1;
                    yDirection++;
                }
                i--;
            }
            switch(flag){
            case 1: xDirection++;break;
            case 2: yDirection++;break;
            case 3: xDirection--;break;
            case 4: yDirection--; break;
            }
        }
        for (int i = 0; i < INPUT; i++) {
            for (int k = 0; k < INPUT; k++)
                System.out.print(grid[i][k] + " ");
            System.out.println();
        }
    }

```

sample output for input 10

```
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019

```

# Answer
> 4 votes
# Perl, 178 chars

Uses Math::Complex and maintains the current direction in a complex variable (1/i/-1/.i). Run with:

```
$ perl -MMath::Complex spiral.pl

```

Put `N` in `$l`.

```
# $l = shift;
$d=i;
$x=0;
until($s{$x}){
    $s{$x}=++$n;
    $x+=$d;
    $d*=-i if
        Re($x)==Im($x)+(Re($x)<$l/2)
        ||Re($x)==$l-1-Im($x)
}
for$y(0..$l-1){
    printf'%0'.length($l**2).'d ',$s{$_+i*$y}for 0..$l-1;
    print"\n"
}

```

# Answer
> 3 votes
C

```
#include<stdio.h>
#include<math.h>

int main() {
    int A[42][42],i,j,N,c=1,k;
    scanf("%d",&N);
    for (i = 0, j = N - 1 ; j >= 0 ; i++, j--) {
            for(k = i ; k < j; k++)A[i][k]=c++;
            for(k = i ; k < j; k++)A[k][j]=c++;
            for(k = j ; k > i; k--)A[j][k]=c++;
            for(k = j ; k > i; k--)A[k][i]=c++;
    }
    if (N%2)
       A[N/2][N/2]=c;
    for (i=0;i<N;i++) {
        for (j=0;j<N;j++)
            printf("%0*d ",((int)log10(N*N)+1),A[j][i]);
        printf("\n");
    }
}

```

# Answer
> 3 votes
## Python 2.7:

```
def spiral(n):
   rows = [[n * n]]
   current = n * n - 1

   while current:
      rows = zip(*([range(current, current - len(rows[0]), -1)] + rows))[::-1]
      current -= len(rows)

   digits = len(str(n * n))
   for row in rows:
      print" ".join(str(cell).zfill(digits) for cell in row)

spiral(5)

```

# Answer
> 3 votes
## PHP, 272 chars including comment

Func-based, recursive version - more interesting for me as it better expresses intention. It works for distinct width and height too.

```
<?php

$n = $argv[1];

for($y = 0; $y<$n; $y++){
    for($x = 0; $x<$n; $x++)
        printf("%02d ", f($n, $n, $x, $y));

    echo "\n";
}

function f($w, $h, $x, $y){
    return ($y)
        ?$w + f($h - 1, $w, $y - 1, $w - $x - 1) //strip-off first row and "rotate"
        :$x;
}

```

Output:

```
C:\www>php -f golfed_spiral.php 8
00 01 02 03 04 05 06 07
27 28 29 30 31 32 33 08
26 47 48 49 50 51 34 09
25 46 59 60 61 52 35 10
24 45 58 63 62 53 36 11
23 44 57 56 55 54 37 12
22 43 42 41 40 39 38 13
21 20 19 18 17 16 15 14

```

# Answer
> 2 votes
## C#, 380-ish golfed

I didn't bother pasting in the golfed version as I was pretty confident this wasn't going to break any records. But I wanted to give it a shot thinking about it a bit differently. Rather than write out each line or position as I come to it, I'm moving the cursor into position, writing out the starting center number, and spiraling out from there (which illustrated an interesting pattern of positions-to-move per direction change).

There's a fair amount of character space wasted getting the console buffer to accept the larger values as well calculating the position for the upper left corner (which I'm sure can be improved).

At any rate, it was an interesting exercise.

```
    static void Main(string[] p)
    {
        int squareSize = 4;
        Console.BufferHeight = 300;
        Console.BufferWidth = 300;

        int maxTravel = 0;
        int currentTravel = 0;
        int travelCounter = 0;
        var a = squareSize % 2 == 0;
        int direction = a ? 2 : 0;
        int pad = squareSize * squareSize;
        int padLength = (pad + "").Length;

        int y = a ? (squareSize / 2) - 1 : (squareSize - 1) / 2;
        int x = a ? y + 1 : y;
        x = x + (x * padLength);

        for (int i = pad; i > 0; i--)
        {
            Console.SetCursorPosition(x, y);
            Console.Write((i + "").PadLeft(padLength, '0') + " ");

            switch (direction)
            {
                case 0:
                    y--;
                    break;

                case 1:
                    x += padLength + 1;
                    break;

                case 2:
                    y++;
                    break;

                case 3:
                    x -= padLength + 1;
                    break;
            }

            if (++currentTravel > maxTravel)
            {
                currentTravel = 0;
                direction = ++direction % 4;

                if (++travelCounter == 2)
                {
                    travelCounter = 0;
                    maxTravel++;
                }
            }

        }
    }

```

# Answer
> 2 votes
### Ruby

This isn't a particularly good golfable solution, but it might be of algorithmic interest.

I've always been fascinated by a similar problem, namely, finding the clockwise spiral path through an NxM matrix. One really intuitive way of solving that problem is to keep rotating the matrix counterclockwise and peel it like an orange. I use a similar — albeit not as elegant — method to do the reverse:

```
def spiral_matrix(n)
  matrix = Array.new(n) { Array.new(n) }
  path = [*1..n*n]
  padding = (n*n).to_s.size
  layer = 0
  until path.empty?
    matrix[layer].map! { |l| l || path.shift }
    matrix = matrix.transpose.reverse
    layer += 1 unless matrix[layer].include?(nil)
  end
  matrix = matrix.transpose.reverse until matrix[0][0] == 1
  matrix.transpose.each do |row|
    row.each do |l|
      print "%0#{padding}d" % l, ' '
    end
    puts
  end
end

```

# Answer
> 1 votes
## Racket

Just wanted to try it with a solution using close to 0 memory. No array, no nothing. The value can be generated for any position anytime. We could ask a spiral of any size (if what receives the output stream can handle it). In hope that someone ever needs gigantic spirals.

Here's the code

```
; number of chars required to write x in base 10
; defined for x > 0
(define log10
  (λ (x)
    (inexact->exact
     (+ 1 (floor (/ (log x) (log 10)))))))

; tells the square number
; works for squares of both even and odd sizes
; outer square # = 0
(define square#
  (λ (x y size) ; x and y begin at 0
    (min x y
         (- size 1 x)
         (- size 1 y))))

; tells the number of values in a square
(define square-val-qty
  (λ (sqr# size) ; size is the whole spiral size
    (let ((res (* 4 (- size (* 2 sqr#) 1))))
      (cond
        ((zero? res) 1)
        (else res)))))

; at which value a square starts
; works for odd/even spirals
(define square-1st-val
  (λ (sqr# size)
    (+ (* 4 sqr# (- size sqr#)) 1)))

; square size from spiral size
(define square-side
  (λ (sqr# size)
    (- size (* 2 sqr#))))

(define 1+
  (λ (n)
    (+ n 1)))

(define 1-
  (λ (n)
    (- n 1)))

; calculates the position on the square (from 0)
(define position-on-square
  (λ (x y size)
    (let* ((sqr#     (square# x y size))
           (sqr-x    (- x sqr#))
           (sqr-y    (- y sqr#))
           (sqr-side (square-side sqr# size)))
      (cond
        ((and (zero? sqr-x) (< sqr-y (1- sqr-side))) ; left part
         sqr-y)
        ((and (eq? sqr-y (1- sqr-side)) (< sqr-x (1- sqr-side))) ; bottom
         (+ (1- sqr-side) sqr-x))
        ((and (not (eq? sqr-y 0)) (eq? sqr-x (1- sqr-side))) ; right
         (+ (* 2 (1- sqr-side)) (- sqr-side sqr-y 1)))
        (else ; top
         (+ (* 3 (1- sqr-side)) (- sqr-side sqr-x 1)))))))

; returns the spiral value at the given position
(define spiral-value
  (λ (x y size)
    (+ (square-1st-val (square# x y size) size)
       (position-on-square x y size))))

; pads a string with char
(define left-pad
  (λ (str char width)
    (cond
      ((< (string-length str) width)
       (left-pad (string-append (string char) str) char width))
      (else
       str))))

; draws a spiral!
(define draw-spiral
  (λ (size)
    (let ((x 0)
          (y 0)
          (width (log10 (* size size))))
      (letrec ((draw
                (λ ()
                  (printf "~a " (left-pad (number->string (spiral-value x y size)) #\0 width))
                  (cond
                    ((and (eq? x (1- size)) (eq? y (1- size)))
                     (printf "~n~n"))
                    ((eq? x (1- size))
                     (set! x 0)
                     (set! y (1+ y))
                     (printf "~n")
                     (draw))
                    (else
                     (set! x (1+ x))
                     (draw))))))
        (draw)))))

```

Testing with this

```
(draw-spiral 1)
(draw-spiral 2)
(draw-spiral 3)
(draw-spiral 4)
(draw-spiral 5)
(draw-spiral 15)
(draw-spiral 16)

```

Results in output

```
1

1 4
2 3

1 8 7
2 9 6
3 4 5

01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07

01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

001 056 055 054 053 052 051 050 049 048 047 046 045 044 043
002 057 104 103 102 101 100 099 098 097 096 095 094 093 042
003 058 105 144 143 142 141 140 139 138 137 136 135 092 041
004 059 106 145 176 175 174 173 172 171 170 169 134 091 040
005 060 107 146 177 200 199 198 197 196 195 168 133 090 039
006 061 108 147 178 201 216 215 214 213 194 167 132 089 038
007 062 109 148 179 202 217 224 223 212 193 166 131 088 037
008 063 110 149 180 203 218 225 222 211 192 165 130 087 036
009 064 111 150 181 204 219 220 221 210 191 164 129 086 035
010 065 112 151 182 205 206 207 208 209 190 163 128 085 034
011 066 113 152 183 184 185 186 187 188 189 162 127 084 033
012 067 114 153 154 155 156 157 158 159 160 161 126 083 032
013 068 115 116 117 118 119 120 121 122 123 124 125 082 031
014 069 070 071 072 073 074 075 076 077 078 079 080 081 030
015 016 017 018 019 020 021 022 023 024 025 026 027 028 029

001 060 059 058 057 056 055 054 053 052 051 050 049 048 047 046
002 061 112 111 110 109 108 107 106 105 104 103 102 101 100 045
003 062 113 156 155 154 153 152 151 150 149 148 147 146 099 044
004 063 114 157 192 191 190 189 188 187 186 185 184 145 098 043
005 064 115 158 193 220 219 218 217 216 215 214 183 144 097 042
006 065 116 159 194 221 240 239 238 237 236 213 182 143 096 041
007 066 117 160 195 222 241 252 251 250 235 212 181 142 095 040
008 067 118 161 196 223 242 253 256 249 234 211 180 141 094 039
009 068 119 162 197 224 243 254 255 248 233 210 179 140 093 038
010 069 120 163 198 225 244 245 246 247 232 209 178 139 092 037
011 070 121 164 199 226 227 228 229 230 231 208 177 138 091 036
012 071 122 165 200 201 202 203 204 205 206 207 176 137 090 035
013 072 123 166 167 168 169 170 171 172 173 174 175 136 089 034
014 073 124 125 126 127 128 129 130 131 132 133 134 135 088 033
015 074 075 076 077 078 079 080 081 082 083 084 085 086 087 032
016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031

```

Quite CPU intensive compared to precalculated matrices if you need the whole spiral, but might be useful. Who knows! E.g.:

```
(spiral-value 1234567 7654321 234567890)  ->  1152262488724319

```

Didn't golf it... It's quite small despite the appearance. I used long names and comments.

# Answer
> 1 votes
# Python 2, 800 bytes

```
from collections import namedtuple
Crd = namedtuple('Crd',['row','col','val'])
C1 = Crd(1,1,1)
def add(c1, c2):
    return Crd(c1.row + c2.row, c1.col + c2.col, c1.val + c2.val)
def deltas(l):
    for i in xrange(1,l): yield Crd(0,1,1)
    for i in xrange(1,l): yield Crd(1,0,1)
    for i in xrange(1,l): yield Crd(0,-1,1)
    for i in xrange(1,l-1): yield Crd(-1,0,1)
def ring(c, l):
    yield c
    for d in deltas(l):
        c = add(c, d)
        yield c
def spiral(n):
    cur = C1
    while n > 0:
        for c in ring(cur, n):
            yield c
            cur = c
        cur = add(cur, Crd(0,1,1))
        n -= 2
n    = input()
fmt  = '%' + str(len(str(long(n*n)))) + 'd'
crds = sorted(list(spiral(n)))
for r in xrange(1,n+1):
    print ' '.join([fmt % c.val for c in crds if c.row == r])

```

Try it online!

A few years back a friend of mine was asked this question in an interview. They told me about it at our family's Thanksgiving dinner so I think of this as the "Thanksgiving problem".

# Answer
> 1 votes
# PHP, ~~172~~ 171+1 bytes, 24 operations

creates an array walking the indexes through a spiral; then prints the result.

```
// 1) input squared -> 2) string length -> 3) $e = length of maximum number
for($e=strlen($argn**2);
    // 4) decrement input (line length) every second iteration; 5) loop while input>0
    $argn-=$i%2;
    // 24) post-increment iteration counter $i
    $i++)
    // 6,7,8) loop through current line
    for($p=$argn;$p--;)$r
        // 9) $i=$i modulo 4; 10,11) (1-$i)%2 == [1,0,-1,0][$i] -> 12) increment/decrement $y coordinate3
        [$y+=(1-$i%=4)%2]
        // 13,14) (2-$i)%2 == [0,1,0,-1][$i] -> 15) increment/decrement $x coordinate
        [$x+=(2-$i)%2]
        // 16) print formatted to string; 17) assign to field [$y,$x] in $r
        =sprintf("%0{$e}d ",++$n);
// 18) pre-increment row counter $z; 19) loop while row exists
for(;$r[++$z];
    // 21) join row; 22) append newline; 23) print
    print join($r[$z])."\n")
    // 20) sort row by indexes
    ksort($r[$z]);

```

Run as pipe with `-nR` or try it online.

Add one assignment to save five bytes: replace the final loop with

```
for(;$s=$r[++$z];print join($s)."\n")ksort($s);

```

# Answer
> 0 votes
Sample code : This works for 4x5 but failing 3x5

while (k \< m && l \< n) { /\* Print the first row from the remaining rows \*/ for (i = l; i \< n; ++i) { printf("%d ", a\[k\]\[i\]); } k++;

```
    /* Print the last column from the remaining columns */
    for (i = k; i < m; ++i)
    {
        printf("%d ", a[i][n-1]);
    }
    n--;

    /* Print the last row from the remaining rows */
    if ( k < m)
    {
        for (i = n-1; i >= l; --i)
        {
            printf("%d ", a[m-1][i]);
        }
        m--;
    }

    /* Print the first column from the remaining columns */
    if (l < n)
    {
        for (i = m-1; i >= k; --i)
        {
            printf("%d ", a[i][l]);
        }
        l++;
    }
}

```

---
Tags: atomic-code-golf
---