title: Scrolling Marquee

text:
# Question
Title: Scrolling Marquee
Following my entry to the Obfuscated Hello World I thought it might be fun to share the underlying code. But why just show the code, lets make it a golf too!

**Challenge**

Write a script that scrolls a string across the terminal, from right to left, settling on the left side.

**Input**

Takes a string as an argument.

**Result**

Prints the scrolling marquee to STDOUT. Max width of ~50 chars. Starts with 0 or 1 char showing. Some space between letters while scrolling. Stops when settled (having no extra space between word chars). Slow scroll, but not too slow (\< 1s per iteration).

**Example**

Running script with arg `'Hello World'`

```
                                                   H

```

later

```
                H    e    l    l    o         W    o

```

later

```
H    e    l    l    o          W    o    r    l    d

```

later

```
Hell    o         W    o    r    l    d

```

finally

```
Hello World

```

For a running example, try my code from the "Hello World" challenge. ~~Eventually I will post mine. It currently is 202 chars in Perl.~~ Now that there are some competitors, I have posted mine in the answers.

**Winner**

I don't want the restrictions to be absolute, that's why I left them a little vague. The shortest script which follows the spirit of my original will win.

**Notes**

This game assumes `xterm` environment. Should another environment prove useful, only similar environments will be compared and a separate winner may be declared for each.

**Addendum (April 25, 2012)**

To address some budding issues, I'm making a ruling. Your character count must include code needed to:

1. Flush STDOUT (Looking at you Ruby)
2. Implement `sleep` with time delay of \<1s (Looking at you Perl)

This may be done as command line switches to an interpreter, but those characters count in the total (sans surrounding whitespace).

# Answer
## python 2 - 146 chars

edit: made it a function instead of input through stdin. first argument is the string, and the second argument is the length you want it to be. so invocation would be `f('Hello World', 50)`. I also made it much smoother; when each character 'landed' there was an awkward pause

```
import os,time
def f(x,n):
 y=' '*n+'  '.join(x);z=0
 while y:w=y[0]==x[z];y=y[1+w:];z+=w;os.system('cls');print((x[:z]+y)[:n]);time.sleep(0.1)

```

old, 158 chars:

```
import os,time,sys
x=' '.join(sys.argv[1:])
y=' '*50+'  '.join(x)
z=0
while y:z+=y[0]==x[z];y=y[1:];os.system('cls');print((x[:z]+y)[:50]);time.sleep(0.1)

```
> 5 votes

# Answer
### Ruby, 93 91 89 chars

```
u="\1";s=u*50+[*$*[0].chars]*(u*3);$><<s.tr(u," ")[0,50]+" \r"while s.sub!u,""*sleep(0.1)

```

The text to be displayed must be given as command line argument, e.g.

```
ruby marquee.rb "Hello World"

```

for the example shown above. Unfortunately I cannot show the animation here, so you have to try out the code yourself.

*Previous version:*

```
s=" "*67+[*$*[0].chars]*"   ";(s.size*3/4).times{|j|s[j/3]='';$><<s[16,50]+" \r";sleep 0.1}

```
> 4 votes

# Answer
## C, 94 83 80 173 chars

EDIT: Added lots of code, implements all the requested functionality now. The constant `1e8` can be tweaked to control the speed. On my machine, it's quite fast as it is.
Some characters can surely be saved here. `l` can be static (saves initialization), `c` can become a pointer (replacing `b+c`).

```
char b[99],c=1;
main(a,t,w,i,l)char**t;{
    for(l=0;b[l++]=*t[1]++;b[l++]=32);
    for(w=80;i--||
        printf("\033[F\033[K%*.*s\n",w-=l<a,a++,b,i=1e8)>l+6||
        b[++c]&&memmove(b+c-1,b+c,l););
}

```

Old version (80 chars), with partial functionality:
Saved a couple of chars by replacing `char**t` with `int*t`. Works fine in 32-bit (`int**t` would support 64-bit).

```
main(i,t,w)
    int*t;
{
    for(w=80;i--||printf("\033[F\033[K%*s\n",w,t[1],i=1e8)*--w;);
}

```
> 3 votes

# Answer
## K&R C -- ~~431~~ 416 characters

Respects the standard to a high degree. Uses ncurses so it should be largely terminal independent. There is a slight stuttering when the text hits the side due to some trickery played to preserve the intended whitespace in the string.

The string to use should be passed as the first argument on the command line (and should be escaped if it contains spaces, more so if it contains a `!` as my test string (`Hello, World!`) did).

```
#include <ncurses.h>
#include <unistd.h>
#define T usleep(1e5),S(l)
#define U mvprintw(23,0,"%s",l),refresh()
char l[63],*p,*q,r;
S(char*s){r=0;if(*s==32)q=s++;else{for(;*s-32||*(s+1)-32;s++);
for(q=s;*s==32;s++);(s-q)&1?s--:usleep(1e5);}
for(r=0;*s;*q++=*s++){*s-32?r=1:0;}return r;}
main(int c,char**v){initscr();curs_set(0);for(c=0;c<62;l[c++]=32);
for(p=*++v;*p;){l[52]=*p++;U;T;U;T;U;T;}for(;T;U);getch();endwin();}

```

In a more readable and commented form:

```
#include <ncurses.h>
#include <unistd.h>

char l[63] /* take advantage of 0 initialization */,
  *p,*q, r;

/* Remove the first unwanted space. Unwanted means at the begining of
 * the line, all of even length blocks between non-spaces, and
 * all-bu-one of odd length blocks between non-spaces.
 *
 * Return true if the removed space occurs before a non-space character.
 */
S/*lide marquee*/(char*s){
  r=0; /* initialize the return value */
  if(*s==' '){
    q=s++;
  } else {
    /* Find the start of first block of contiguous spaces */
    for(;*s-' '||*(s+1)-' ';s++);
    for(q=s;*s==' ';s++); /* q holds the start, s finds it's end */
    /* if this block is even length remove all, if odd, all but one */
    if( (s-q)%2 )s--; else usleep(1e5);
  }
  /* copy from s to q all the way to the end */
  for(r=0;*s;*q++=*s++){
    if(*s-' ')r=1; /* note if we pass a non-space */
  }
  return r;
}

main(int c,char**v){
  initscr();curs_set(0); /* setup ncurses with invisible cursor */
  for(c=0;c<62;l[c++]=' '); /* initialize l */
  for(p=*++v;*p;){ /* load the message into the marque, skipping space */
    l[52]=*p++;
    mvprintw(23,0,"%s",l),
    refresh();
    usleep(1e5),
    S(l);
    usleep(1e5),
    S(l);
    usleep(1e5),
    S(l);
  }
  for(;usleep(1e5),S(l);mvprintw(23,0,"%s",l),refresh()); /* keeping sliding until we're done. */
  getch();
  endwin();
}

```
> 2 votes

# Answer
# Perl 5.13.2, 96

```
$_=join$;x4,$;x46,split//,pop;print substr(s/$;/ /gr,0,50)." \r"while$|=s/$;//+select'','','',.1

```

Stealing a lot from @Kevin Reid's answer, especially the `/r` trick available in newer Perls.

## Perl, 115

Like @Joel Berger's answer, this would become much shorter if I could use `sleep 1` and be slow, or pass `-MTime::HiRes=sleep` on the command line to enable `sleep.1`. Otherwise the only built-in way to get short sleeps is `select'','','',.1` which is pretty long.

```
$|=@_=(($")x45,map{($")x4,$_}split//,pop);for(0..$#_){print@_," \r";splice@_,($_-=45)<0?0:$_/4,1;select'','','',.1}

```

### ~~Perl, 128~~

```
$_=$"x9 .pop;s/./    $&/g;$.=-46;$\=" \r";while($|=/./g){print substr($_,0,50);pos=++$.<0?0:$./4;s/\G.//;select'','','',.1}print

```

### ~~Perl, 133~~

```
$|=@_=split//,pop;for$i(reverse-$#_..50){for(@_){print$"x($j||$i),$_;($i+=$j=($i++>0)*4)>50&&last}print"    \r";$j=select'','','',.1}

```
> 2 votes

# Answer
## bash 234

```
w=$1
p(){
i=$1
s=$2
p=$((50+s*3-i))
((p<s+1)) && p=$((s+1));
((p<50)) && echo -en "\e[20;"${p}H$3"  ";
}
clear
for i in {0..99}
do
for s in $(seq 0 ${#w})
do
p $i $s ${w:s:1}
done
sleep .1
echo -en "\e[20;1H  "
done
echo -en "\b\b$w\n"

```

Usage:

```
./marquee.sh "Hello, fine marquee world"

```

ungolfed:

```
#!/bin/bash
w=$1
p(){
    #si String index
    it=$1
    #it=iteration
    si=$2
    pos=$((50+(si*3)-it))
    ((pos<si+1 )) && pos=$((si+1));
    ((pos<50)) && echo -en "\e[20;"${pos}H$3"  ";
}
clear
for it in {0..99}
do
    for si in $(seq 0 ${#w})
    do
        p $it $si ${w:si:1}
    done
    sleep .1
    echo -en "\e[20;1H   "
done
echo -en "\e[22;1H"

```
> 2 votes

# Answer
## JavaScript ~~180~~ 218 chars

Production Version:

```
function f(){i--&&(i>50?h=h.substr(1):h=h.replace(" ",i==16?" ":""),document.body.innerHTML="<pre>"+h.substr(0,50)+"</pre>",setTimeout(f,99))}h=(new Array(50)).join(" ")+"HelloWorld".split("").join("   "),i=80,f()

```

Ungolfed Version:

```
h=new Array(50).join(" ")+("HelloWorld".split("").join("   "));
i=80;

function f(){
        if(i--){
            if(i>50){
                h=h.substr(1);
            }else{
                h=h.replace(" ",(i==16)?" ":"");
            }
            document.body.innerHTML="<pre>"+h.substr(0,50)+"</pre>";
            setTimeout(f,99);
        }
}
f();

```

Here is a jsFiddle Demo

**Note:** if you try to reproduce it, make sure the code is below the body
> 1 votes

# Answer
**Perl**: ~~144~~ 133

```
$|=@s=(($")x50,map{$_,($")x4}@i=split//,pop);{$n=0;$s[$n]ne$_?last:$n++for@i;splice@s,$n,1;print"\r",@s[0..50];sleep.1;$n!=@i&&redo}

```

In order to get the sleep of \<1s though you need to run as:

```
perl -MTime::HiRes=sleep scriptname 'string to print'

```

Since I won't declare myself winner I won't argue myself over what counts there or not (but I really can't have Ruby win this ;-) )
> 1 votes

# Answer
## Perl 5.13.2, 115 characters

```
$_=$"x9 .pop=~y/ /\0/r;s/./    $&/g;print(y/\0/ /r=~/(.{50})/,"\r"),select$.,$.,$.,.02while$|=s/ (\S)/$1 /g;print$/

```
* Warning-clean.
* Can be squeezed a bit by reducing the space between characters or the initial whitespace.
* Requires Perl 5.13.2 or newer due to use of `/r`.
* The substitution to NUL to preserve spaces is unambiguous since POSIX argv is not NUL-clean. However, the loop substitution will turn any other whitespace into nothing (eventually).

Credits:
> 1 votes

# Answer
## R, 319 characters

Following the philosophy of @Blazer example (d is the delay in sec):

```
f=function(x,n=50,d=0.2){
    s=strsplit(x,"")[[1]];i=1;l=length
    while (i<(n+l(s)-1)){
        if(i<=l(s))cat(rep(" ", n-i),s[1:i])
        else if((i<=n)&&(i>l(s)))cat(rep(" ", n-i),s[1:l(s)])
        else cat(paste(s[1:(i-n+1)],collapse=""),s[(i-n+2):l(s)])
        Sys.sleep(d);system("clear");i=i+1
    }
    cat(paste(s[1:l(s)],collapse=""))
}

```

Usage:

```
f("Hello World",n=20,d=0.2)

```
> 1 votes

# Answer
# Q,145

Doesn't exactly meet the requirements because the final line removes all the spaces that were in the original input string.

```
{c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}

```

It takes two arguments, input string and scroll speed

```
q){c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}["hello";0.05]
             h
            h
           h
          h  e
         h  e
        h  e
       h  e  l
      h  e  l
     h  e  l
    h  e  l  l
   h  e  l  l
  h  e  l  l
 h  e  l  l  o
h  e  l  l  o
h e  l  l  o
he  l  l  o
he l  l  o
hel  l  o
hel l  o
hell  o
hell o
hello

```
> 0 votes

# Answer
### PowerShell, 135

Not very golfed and probably a horrible approach, but I'm sick and can't really think ...

```
for($x="`r"+' '*50;$y-ne$x){$y=$x
write-host($x=$x-replace' ([^ ])','$1 ')-n
if(!($t++%5)){$x=$x-replace'.$',"$args"[$i++]}sleep -m 99}

```
> 0 votes

# Answer
## J (116)

```
s(echo@((50#LF)&,)@([[i.@]&2e7)@(50&{.)@;@:(([,~#&' '@])&.>))"1([-=&0@/:@\:@:~:&0)^:(i.>:+/k)k=.50,3#~<:#s=.>2{ARGV

```

Takes the input string on the command line, i.e. `jconsole marquee.ijs 'Hello, world!'`

If it doesn't need to clear the screen, i.e. output like this:

```
H  e  l  l  o
H e  l  l  o
He  l  l  o
He l  l  o
...

```

is allowed, it would be 12 characters shorter.

Explanation:

* `s.=>2{ARGV`: get the string from the command line
* `k.=50,3#~<:#s`: the starting amount of whitespace added before each character, 50 before the first one and 3 before all the others. (gives an array, '50 3 3 3...')
* `([-=&0@/:@\:@~:&0)`: given an array, decrements the first nonzero item in the array
* `^:(i.>:+/k)`: this function applied N times, where N is 0 upto the sum of the amount of added whitespace. (gives a matrix: `50 3 3 3; 49 3 3 3; 48 3 3 3; ... 0 0 0 1; 0 0 0 0)`.
* `"1`: run following function on each row of the matrix
* `;@:(([,~#&' '@])@.>)`: add the given amount of spaces before each character in the string
* `(50&{.)`: take the first 50 characters of the string
* `([[i.@]&2e7)`: a function that generates the list from 0 to 2\*10^7, and then throws it away. This takes about a third of a second on my machine, this causes the delay.
* `((50#LF)&,)`: add 50 newlines before the string, to clear the screen
* `echo`: output the string
* `s (...)`: give the string as the left argument to the function
> 0 votes

# Answer
## APL (70)

```
{⎕SM∘←1,⍨1,⍨,/D{⍺,⍨⍵⍴⍕⍬}¨P←⍵-{⍵×~×⍺}\×⍵⊣⎕DL÷8⋄0∨.≠P:∇P}1↓⎕SD,1↓3⍴⍨⍴D←⍞

```

Takes input from the keyboard, the output is in the `⎕SM` window (which would be the terminal if you had a text-based APL I guess). The window size is detected automatically, if you really want it to be 50 change the `1↓⎕SD` to `50`.

Explanation:

* `1↓⎕SD,1↓3⍴⍨⍴D←⍞`: read the string and store in `D`. Generate a vector describing how much whitespace to add before each character, which is the screen width before the first character (`1↓⎕SD`), and 3 before the others (`1↓3⍴⍨⍴D`).
* `⎕DL÷8`: wait 1/8th of a second
* `P←⍵-{⍵×~×⍺}\×⍵`: in the vector in the right argument, subtract 1 from the leftmost nonzero item, and store the new vector in P.
* `,/D{⍺,⍨⍵⍴⍕⍬}¨P`: for each character in D, prefix the amount of whitespace given in P.
* `⎕SM∘←1,⍨1,⍨`: display on the screen, in the leftmost column of the top row
* `0∨.≠P:∇P`: if there is a nonzero element in P, repeat with P.
> 0 votes

# Answer
# PowerShell, 129 bytes

```
for($x=' '*52+(($args|% t*y)-join' '*4);$x-match'  '){write-host "`r$(-join($x=$x-replace'(?<!  .*)  ')[0..50])  "-n
sleep -m 99}

```

Try it online!

This script does not remove spaces from the arguments in contrast to Joey's script.

`TIO` does not display the output correctly. With Powershell console, you get the scrolling marqueeline.
> 0 votes

# Answer
# 05AB1E, 42 bytes

```
ð¶:S3úJ46ú[D50£¶ð:D?IQ#ðõ.;“…¢('\r')“.eт.W

```

Try it online (without the sleep). NOTE: I don't have 05AB1E installed locally, so I'm not 100% sure if the `\r` trick works (in theory it should work, however). In TIO the `\r` are interpret as newlines instead. Also, the TIO uses the legacy version, because `.e` is disabled in the new TIO version (program is the same in both the legacy and new version of 05AB1E, though).

**Explanation:**

```
ð¶:            # Replace all spaces in the (implicit) input-string with newlines
   S           # Split the string to a list of characters
    3ú         # Pad each character with 3 leading spaces
      J        # Join the characters together again
       46ú     # And pad the entire string with an additional 46 leading spaces
[              # Now start an infinite loop:
 D             #  Duplicate the string
  50£          #  And leave only the first 50 characters of this copy as substring
     ¶ð:       #  Replace the newlines back to spaces
        D?     #  Duplicate the string, and print it without trailing newline
 IQ            #  If the current string is equal to the input:
   #           #   Stop the infinite loop
 ðõ.;          #  Replace the first space with an empty string to remove it
 “…¢('\r')“    #  Push dictionary string "print('\r')"
           .e  #  Evaluate it as Python code
 т.W           #  Sleep for 100 ms

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“…¢('\r')“` is `"print('\r')"`.
> 0 votes

# Answer
# Python, 139 bytes

```
import os;P='\n'
def f(x,w):
 v=k=P*w+P.join(x);o=str.replace
 while v!=x:os.system('sleep 1;clear');k=o(k,P,'',1);v=o(k,P,' ');print v[:w]

```

Has to call `f('Hello World', 50)` to start.
> 0 votes

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


# Question
Title: New Order #5: where Fibonacci and Beatty meet at Wythoff
## Introduction *(may be ignored)*

Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the fifth challenge in this series (links to the first, second, third and fourth challenge).

In this challenge, we will meet the Wythoff array, which is a intertwined avalanche of Fibonacci sequences and Beatty sequences!

The Fibonacci numbers are probably for most of you a well known sequence. Given two starting numbers \\$F\_0\\$ and \\$F\_1\\$, the following \\$F\_n\\$ are given by: \\$F\_n = F\_{(n-1)} + F\_{(n-2)}\\$ for \\$n\>2\\$.

The Beatty sequence, given a parameter \\$r\\$ is: \\$B^r\_n = \lfloor rn \rfloor\\$ for \\$n \ge 1\\$. One of the properties of the Beatty sequence is that for every parameter \\$r\\$, there is exactly one parameter \\$s=r/(r-1)\\$, such that the Beatty sequences for those parameters are disjunct *and* joined together, they span all natural numbers excluding 0 (e.g.: \\$B^r \cup B^{r/(r-1)} = \Bbb{N} \setminus \\{0\\}\\$).

Now here comes the mindblowing part: you can create an array, where each row is a Fibonacci sequence ***and*** each column is a Beatty sequence. This array is the Wythoff array. The best part is: every positive number appears exactly once in this array! The array looks like this:

```
   1    2    3    5    8   13   21   34   55   89  144 ...
   4    7   11   18   29   47   76  123  199  322  521 ...
   6   10   16   26   42   68  110  178  288  466  754 ...
   9   15   24   39   63  102  165  267  432  699 1131 ...
  12   20   32   52   84  136  220  356  576  932 1508 ...
  14   23   37   60   97  157  254  411  665 1076 1741 ...
  17   28   45   73  118  191  309  500  809 1309 2118 ...
  19   31   50   81  131  212  343  555  898 1453 2351 ...
  22   36   58   94  152  246  398  644 1042 1686 2728 ...
  25   41   66  107  173  280  453  733 1186 1919 3105 ...
  27   44   71  115  186  301  487  788 1275 2063 3338 ...
  ...

```

An element at row \\$m\\$ and column \\$n\\$ is defined as:

\\$A\_{m,n} = \begin{cases} \left\lfloor \lfloor m\varphi \rfloor \varphi \right\rfloor & \text{ if } n=1\\ \left\lfloor \lfloor m\varphi \rfloor \varphi^2 \right\rfloor & \text{ if } n=2\\ A\_{m,n-2}+A\_{m,n-1} & \text{ if }n \> 2 \end{cases}\\$

where \\$\varphi\\$ is the golden ratio: \\$\varphi=\frac{1+\sqrt{5}}{2}\\$.

If we follow the anti-diagonals of this array, we get A035513, which is the target sequence for this challenge (note that this sequence is added to the OEIS by Neil Sloane himself!). Since this is a "pure sequence" challenge, the task is to output \\$a(n)\\$ for a given \\$n\\$ as input, where \\$a(n)\\$ is A035513.

There are different strategies you can follow to get to \\$a(n)\\$, which makes this challenge (in my opinion) really interesting.

## Task

Given an integer input \\$n\\$, output \\$a(n)\\$ in integer format, where \\$a(n)\\$ is A035513.

*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \\$a(0) = 1; a(1) = 2\\$, etc. Please mention this in your answer if you choose to use this.*

## Test cases

```
Input | Output
---------------
1     |  1
5     |  7
20    |  20
50    |  136
78    |  30
123   |  3194
1234  |  8212236486
3000  |  814
9999  |  108240
29890 |  637

```

It might be fun to know that the largest \\$a(n)\\$ for \\$1\le n\le32767\\$ is \\$a(32642) = 512653048485188394162163283930413917147479973138989971 = F(256) \lfloor 2 \varphi\rfloor + F(255).\\$

## Rules

* Input and output are integers
* Your program should at least support input in the range of 1 up to 32767). Note that \\$a(n)\\$ goes up to 30 digit numbers in this range...
* Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default I/O rules apply.
* Default loopholes are forbidden.
* This is , so the shortest answers in bytes wins

# Answer
# Jelly, ~~27~~ 24 bytes

```
p`SÞ⁸ịð’;×ØpḞ¥×⁹r‘ÆḞ¤Sð/

```

Try it online!

Monadic link using 1-based indexing. Thanks to @JonathanAllan for a better way of getting the row and columns from `n` and saving 3 bytes. In its shortest form it’s too slow for larger n on TIO, so the following Try it online! reduces the size of the initial list of rows and columns at the cost of three bytes.

### Explanation

```
p`                       | Cartesian product of the range from 1..input with itself
  SÞ                     | Sort by sum
    ⁸ị                   | Find the tuple at the position indicated by the input - this is the row and column
      ð               ð/ | Start a new dyadic chain using the row as the left and column as the right argument
       ’                 | Increase the row by 1
        ;    ¥           | Concatenate to:
         ×Øp             |   row × φ
            Ḟ            |   rounded down
              ×     ¤    | Multiply this pair by
                  ÆḞ     |   the Fibonacci numbers at positions
               ⁹         |   column index and
                r‘       |   column index plus one
                     S   | sum

```

Note this is based on the description of the Python code on the OEIS page.
> 5 votes

# Answer
# , ~~143~~ ~~130~~ ~~124~~ 123 bytes

```
function(n){k=0:n+1
`~`=rbind
m=k-1~(k*(1+5^.5)/2)%/%1
for(i in k)m=m~m[i,]+m[i+1,]
m=m[-1:-2,]
m[order(row(m)+col(m))][n]}

```

Try it online!

Uses the formula \\$T(n,-1)=n-1; T(n,0)=\lfloor n\cdot\phi\rfloor;T(n,k)=T(n,k-1)+T(n,k-2)\\$ to construct the array (transposed), then `splits` the array along antidiagonals. `k` merely exists to prevent forcing a `drop=F` argument in `m[-1:-2,]` for the case `n=1`.

*Thanks to Neil for pointing out a 1 byte golf.*

# , ~~150~~ ~~138~~ 132 bytes

```
function(n){T[2]=1
for(j in 2:n-1)T=c(T,T[j]+T[j+1])
m=T[-1]%o%((1:n*(.5+5^.5/2))%/%1)+T[-1-n]%o%(1:n-1)
m[order(row(m)+col(m))][n]}

```

Try it online!

Implements the formula \\$T(n,k)=Fib(k+1)\cdot\lfloor n\cdot\phi\rfloor+Fib(k)\cdot(n-1)\\$ to get generate the array, then `splits` along the antidiagonals and extracts the `nth` element.

Thanks to Robin Ryder for the `T[2]=1` trick for generating the Fibonacci sequence.

---

Both solutions are highly inefficient, creating an `nxn` matrix of (most likely) `double`s, as R promotes `integer` (32-bit signed) to `double` automatically when overflowing, but the second one should be quite a lot faster. Taking `n` as a bignum should work automatically, using the call `gmp::as.bigz(n)`, should loss of precision under `double`s be worrisome, and then the language would be `R + gmp`.
> 6 votes

# Answer
# Wolfram Language (Mathematica), 90 bytes

```
Flatten[Table[(F=Fibonacci)[a+1]⌊(b-a+1)GoldenRatio⌋+(b-a)F@a,{b,#},{a,b,1,-1}]][[#]]&

```

Try it online!
> 3 votes

# Answer
# Jelly, 30 bytes

```
p`SÞ⁸ịð;Øp,²;\¤×Ḟ¥/;+ƝQƊ⁹¡ị@ð/

```

**Try it online!**
This is a little slow, but a huge improvement is made with a prefix of `Ḥ½Ċ` (double, square-root, ceiling) like in this test-suite.
> 2 votes

# Answer
# Charcoal, 54 bytes

```
Ｎθ≔⁰ηＷ‹ηθ«≦⊕η≧⁻ηθ»⊞υ¹Ｆθ⊞υ⁻⁺³ι§υ⊖§υι⊞υθＦ⁺²⁻θη⊞υΣ…⮌υ²Ｉ⊟υ

```

Try it online! Link is to verbose version of code. 0-indexed. Uses only integer arithmetic so works for arbitrary large values. Explanation:

```
Ｎθ

```

Input `q`.

```
≔⁰ηＷ‹ηθ«≦⊕η≧⁻ηθ»

```

Calculate the antidiagonal by subtracting ever increasing numbers from `q`, which ends up with the target row number `m`.

```
⊞υ¹Ｆθ⊞υ⁻⁺³ι§υ⊖§υι

```

Calculate the first `m+1` terms of A019446, although we're only interested in the `m`th.

```
⊞υθＦ⁺²⁻θη⊞υΣ…⮌υ²

```

Calculate the first `n+4` terms of the generalised Fibonacci series that starts with `[a(m), m]`. The terms of this sequence are the `m`th terms of A019446, A001477, A000201, A003622, A035336; these last two are the first two columns of the Wythoff array, and so this sequence continues with the rest of the `m`th row of the array.

```
Ｉ⊟υ

```

Output the desired term.
> 2 votes

---
Tags: code-golf, sequence
---


title: Next public holiday

text:
# Question
Title: Next public holiday
Australians love public holidays, and drinking. Yesterday, the 26th January, was Australia day, which is a public holiday. I was glad to not be at work yesterday, and eager to know the next time I get a public holiday! Unfortunately, I had a bit too much to drink, and I'm not able to work it out for myself.

Write a program that will take a date in Australian date/time notation (dd/mm) as input, and output the amount of days until the next public holiday. Because I'm a Queensland (QLD) resident, I'm only interested in public holidays that affect Queenslanders:

> 25/03 | Good Friday
> 26/03 | Easter Saturday
> 28/03 | Easter Monday
> 25/04 | Anzac Day
> 02/05 | Labour Day
> 03/10 | Queen's Birthday
> 25/12 | Christmas Day
> 26/12 | Boxing Day
> 27/12 | Christmas Day holiday

Note the following from the site:

> ### Christmas Day holiday
>
> An additional public holiday to be added when New Year's Day, Christmas Day or Boxing Day falls on a weekend.

Because Christmas day is on Sunday, there is an **extra** public holiday. Christmas day is still a public holiday.

Because I'm a morning person, you should include the current date as a day (as that's the most likely time I will check your program for the next public holiday). That is, if a public holiday's date is entered, your output should be `0`; if the day before a public holiday is entered, your output will be `1`.

I'm only interested in dates between **now** (the 27/01) until the end of the year. The final date you will need to account for is 31/12 where your output will be `1` (for New Year's day).

Standard loopholes are forbidden.

### Input

* Input will always be 5 characters: 4 letters, separated with a hyphen `-` or slash `/`
* Input will only be a date between 27/01 and 31/12

### Output

* The number of days until the next public holiday in Queensland Australia, inclusive of the input date: should be a number between `0` and `153` (the longest gap)
* No new lines or errors

### Examples

```
01-05 = 1
02-05 = 0
03-05 = 153
25/12 = 0
26-12 = 0
27/12 = 0
30/12 = 2
31-12 = 1

```

Hopefully this is clear and nothing is missed; however, this is my second question so I will appreciate any feedback and do my best to fix problems ASAP.

# Answer
> 2 votes
# Pyth, ~~98~~ ~~84~~ ~~62~~ 67 Bytes

**Update:** Saved 14 Bytes by shortening the list of the day count for all 12 months for the day number calculation. Haven't found a good way to compress the other list tho, still trying!

**Update2:** Saved another 22 bytes by endcoding the list of the day-numbers as a base256 string.

```
J30KhJ=Yc:z"\W"dd=N+s<[KtJKJKJKKJKJK)tseYshY-hfgTNCMc"UVXt{ĕŨũŪů"1N

```

Try it online!

Same algorithm as in my Python answer. And no builtin to get the day of the year, so I had to do it myself. Creating those 2 lists for the day-of-the-year calculation and for the days of the holidays is quite costly...gonna have a look at it again and try to generate them in fewer bytes.

# Answer
> 4 votes
# JavaScript (ES6), ~~131~~ 128 bytes

```
d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r

```

## Explanation

Uses the JavaScript built-in `Date` constructor to convert the input string into a number of milliseconds since epoch, then compares this with the number of milliseconds for each public holiday.

It does this by storing the public holidays in an array as the number of days since a reference date. I chose `2016-01-29` for the reference date because the number of milliseconds since epoch can be condensed the shortest for this date. Any number of milliseconds between this day and the next works because the result is rounded down, and keeping the number in the middle avoids daylight saving effects (although the OP's timezone does not have daylight savings). The number of this day is `1453986000000` and rounding it up to `1454000000000` (adding a couple of hours) means it can be written as `1454e9`.

```
d=>
  [56,57,59,87,94,248,331,332,333,338]             // list of day offsets from 01/29
  .map(n=>                                         // for each public holiday offset n
    r=r||                                          // if r is already set, do nothing
      (q=                                          // q = approximate difference in ms
        1454e9+n*864e5                             // time of public holiday
        -new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`)    // time of input date
      )
      >=0&&                                        // if q >= 0
        q/864e5,                                   // r = q in days
    r=0                                            // r = result
  )
  |r                                               // floor and return r

```

## Test

This solution is dependent on the user's timezone. This works in the OP's (and my) time zone (GMT +1000). If you want to test it in a different time zone, adding `numberOfHoursDifferentFromGMT1000 * 60 * 60 * 1000` to the reference date number *should* work. (eg. GMT +0430 would be `-5.5 * 60 * 60 * 1000 + 1454e9+n*864e5`)

```
var solution = d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r
```

```
<input type="text" id="input" value="03/05" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 4 votes
# Visual Basic for Applications, 155 or 118 bytes

Version 1 - locale-independent, 155 bytes

```
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-DateSerial(16,Val(Right(d,2)),Val(Left(d,2)))
If h>=0Goto 9
Next
9 End Function

```

Version 2 - locale-dependent, 118 bytes

```
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-CDate(d)
If h>=0Goto 9
Next
9 End Function

```

Byte count is for final .BAS file, including linefeed characters. Edited outside standard VBA editor (as it imposes additional spaces and verbose forms of some keywords) - but imports and runs smoothly on any Office Application (to test type e.g. `? h("10/08")` in immediate window, or in Excel use directly in a cell formula).

(EDITED) Initially I chose to use `DateSerial` to make the function locale-safe (version 1). As I live in Brazil and thus my system is configured to use "dd/mm/yy" format for dates (just like Australia) I could write a even smaller version by using `CDate` instead (version 2). `CDate` uses system locale information to convert text into date. I also assumed in this version that the code would only be run during 2016 (if year is omitted (-6 bytes) `CDate` assumes current year as per system clock).

The number 42454 on third line is the sum of 42450 that is the numeric representation of 01/01/2016 on VBA, and 84 that is the day-of-the-year for the first holiday. The Array contains day-of-the-year for each holiday (including 01/01/2017) offset by -84 as this takes some digits away. Using 16 instead of 2016 on `DateSerial` takes away two more bytes.

Creating an identical array nine times inside the iteration is "bad" code, but works and saves 3 more bytes (one for array name and one for equal sign outside loop, and one more to reference the array inside the loop).

The "missing" spaces between 0 and the following keyword on second and fourth lines are not necessary as they are reintroduced automatically by VBE when the module is imported. Used outdated but byte-cheap `If <...> Goto <linenumber>` to break from loop (both `If <...> Then Exit For` and `If <...> Then Exit Function` use more characters).

Also took advantage of the fact that the function name in VBA behaves as a local variable, and its value is automaticaly returned by the function in the end of execution.

# Answer
> 3 votes
## T-SQL, ~~210~~, ~~206~~, 194 Bytes

(First post here, Hope this is ok, but please be nice :)

Input goes into `@i`, caters for both `/` and `-` as the separator. I'm in Australia, so my date format is the same as @Tas

```
DECLARE @i CHAR(5)='23-09';DECLARE @c INT=DATEPART(dy,CAST(REPLACE(@i,'-','/')+'/2016' AS DATE))-1;SELECT MIN(b)-@c FROM(VALUES(84),(85),(87),(115),(122),(276),(359),(360),(361))a(b)WHERE b>=@c;

```

**Update** `varchar` to `char` saves 3 bytes plus removed a space :)

**Update 2** declare `@c` and assign without a select

# Answer
> 2 votes
# T-SQL, 296 bytes

Created as a table valued function

```
create function d(@ char(5))returns table return select min(o)o from(select datediff(day,cast('2016'+right(@,2)+left(@,2)as date),cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1)o from(values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231))d(d))d where 0<=o

```

Used in the following manner

```
SELECT *
FROM (
    VALUES
        ('01/05') --= 1
        ,('02/05') --= 0
        ,('03/05') --= 153
        ,('25/12') --= 0
        ,('26/12') --= 0
        ,('27/12') --= 0
        ,('30/12') --= 2
        ,('31/12') --= 1
    )testData(i)
    CROSS APPLY (
        SELECT * FROM d(t)
    ) out

i     o
----- -----------
01/05 1
02/05 0
03/05 153
25/12 0
26/12 0
27/12 0
30/12 2
31/12 1

(8 row(s) affected)

```

A brief explanation

```
create function d(@ char(5)) returns table  -- function definition
return
select min(o)o -- minimum set value
from(
    select datediff( -- date difference
        day, -- day units
        cast('2016'+right(@,2)+left(@,2)as date), -- convert input parameter to date
        cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1 -- convert int values into datetimes and add a day
        )o
    from(
        values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231) -- integers representing the day before public holidays
        )d(d)
    )d
where 0<=o -- only for values >= 0

```

# Answer
> 2 votes
# Python 2, ~~204~~ ~~185~~ ~~165~~ 166 Bytes

**Update:** Golfed it down by ~20 Bytes by calculating the day of the year by myself. No need for the long imports anymore :)

**Update 2:** Another 20 Bytes down by realizing that I can treat new years just as day 367 and making some other small adjustments.

```
def f(d):d=[d[:2],d[3:]];y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0]);return filter(lambda n:n>=y,[85,86,88,116,123,277,360,361,362,367])[0]-y

```

Try it online!

Ungolfed:

```
def f(d):
    l=[85,86,88,116,123,277,360,361,362,367]
    d=[d[:2],d[3:]]
    y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0])
    f=filter(lambda n:n>=y,l)
    return f[0]-y

```

Works by storing the day-of-the-year number of the holidays in a list, filtering out the ones which are before the given date, taking the first element in that filtered list and subtracting the day-of-the-year, which got calculated from the input.

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

```
x=>[0,1,3,31,38,192,275,276,277,282].find(z=>z>=(q=x[0]+x[1]- -[...'20212122121'].slice(0,x[3]+x[4]-1).reduce((a,b)=>+b+a+29,0)-85))-q

```

user81655 still has me beat by 3 bytes, but I can't find anywhere else to squeeze anything out of here. Works by calculating the number of days gone by instead of using Date, then comparing it to an array of holiday offsets.

# Answer
> 1 votes
# ruby 1.9.3, ~~155~~ 153 bytes

After Christmas Day holiday, we need our super-special-day 366! Similar case as @DenkerAffe.

```
require'date'
c=(Date.strptime(ARGV[0],'%d/%m')-Date.parse('01/01')).to_i
print [84,85,87,115,122,276,359,360,361,366].map{|i|(i-c)}.select{|i|i>=0}.min

```

Usage:

```
$ ruby i_want_to_break_free.rb "03/05"

```

# Answer
> 1 votes
# PHP, 116 bytes

Pretty straight forward approach. It stores the days of the year for the holidays and pops them as long as they are in the past. Finally the requested day of the year is subtracted.

```
for($x=[366,361,360,359,276,122,115,87,85,84];($a=date(z,strtotime($argv[1].'-2016')))>$t=array_pop($x););echo$t-$a;

```

Past all test cases. Runs from command line and accepts the input using a hyphen, like:

```
$ php holidays.php "12-05"

```

# Answer
> 0 votes
# 05AB1E, 45 bytes

```
•9JRt€ª´Q®Ië•368вDI„-/S¡`•Σ₁t•ºS₂+s<£O+©@Ïн®-

```

It may not be 2016 anymore, but whatever.. ;) Still assumes the year is 2016 for the sake of being a leap year with `29` for February.

Try it online or verify all test cases.

**Explanation:**

```
•9JRt€ª´Q®Ië•  # Push compressed integer 10549819042671399072072399
  368в         # Converted to base-368 as list: [85,86,88,116,123,277,360,361,362,367]
      D        # Duplicate this list
I              # Take the input
 „-/S¡         # Split it on ["-","/"]
      `        # Push both integer separated to the stack
•Σ₁t•          # Push compressed integer 5354545
     º         # Mirror it without overlap: 53545455454535
      S        # Converted to a list of digits: [5,3,5,4,5,4,5,5,4,5,4,5,3,5]
       ₂+      # Add 26 to each: [31,29,31,30,31,30,31,31,30,31,30,31,29,31]
         s     # Swap to get the month-integer
          <    # Decrease it by 1
           £   # Only leave the first month-1 values from the integer-list
            O  # Sum that sublist
             + # And add it to the day-integer (so we now have the N'th day of the year)
©              # Save this in the register (without popping)
 @             # Do a >= check with each integer in the first (duplicated) list we created
  Ï            # Only leave the truthy values from the list
   н           # Then pop this sublist and only leave its first value
    ®-         # And subtract the integer we saved in the register (N'th day of the year)
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•9JRt€ª´Q®Ië•` is `10549819042671399072072399`; `•9JRt€ª´Q®Ië•368в` is `[85,86,88,116,123,277,360,361,362,367]`; and `•Σ₁t•` is `5354545`.

---
Tags: code-golf, date
---


# Question
Title: Amount of permutations on an NxNxN Rubik's Cube
## Introduction:

A 3x3x3 Rubik's Cube has \\$43,252,003,274,489,856,000\\$ possible permutations, which is approximately 43 quintillion. You may have heard about this number before, but how is it actually calculated?

A 3x3x3 Rubik's Cube has six sides, each with nine stickers. Looking at the (external) pieces instead of stickers however, we have six center pieces; eight corners pieces; and twelve edge pieces. Since the centers can't be moved, we can ignore those in the calculations. As for the corners and edges:

* There are \\$8!\\$ (\\$40,320\\$) ways to arrange the eight corners. Each corner has three possible orientations, although only seven (of the eight) can be oriented independently; the orientation of the eighth/final corner depends on the preceding seven, given \\$3^7\\$ (\\$2,187\\$) possibilities.
* There are \\$\frac{12!}{2}\\$ (\\$239,500,800\\$) ways to arrange the twelve edges. The halve from \\$12!\\$ is because edges must always be in an even permutation exactly when the corners are. Eleven edges can be flipped independently, with the flip of the twelfth/final edge depending on the preceding eleven, given \\$2^{11}\\$ (\\$2,048\\$) possibilities.

Putting this together, we have the following formula:

$$8!×3^7×\frac{12!}{2}×2^{11} = 43,252,003,274,489,856,000$$

Source: Wikipedia - Rubik's Cube Permutations

Although this may already look pretty complex, it's still rather straight-forward for a 3x3x3 Cube. For even cubes the formula is slightly different; this is the formula for a 4x4x4 Cube for example:

$$\frac{8!×3^7×24!^2}{24^7} = 7,401,196,841,564,901,869,874,093,974,498,574,336,000,000,000$$

Which is approximately 7.40 quattuordecillion on the short scale.

And for larger NxNxN Cubes (i.e. the current World Record 33x33x33) the formula will be extended quite a bit. To not make this introduction too long however, I put these links here instead, where the permutations of the 4x4x4 Cube and some other sized NxNxN Cubes are explained with a resulting formula:

You may be wondering by now: is there a general formula based on \\$N\\$ for any \\$N\\$x\\$N\\$x\\$N\\$ Cube? There certainly is. Here are three completely different algorithms, all giving the exact same results based on \\$N\\$:

1: Chris Hardwick's Formula:

$$\frac{(24×2^{10}×12!)^{N\pmod2}×(7!×3^6)×(24!)^{\lfloor{\frac{1}{4}×(N^2-2×N)}\rfloor}}{(4!)^{6×\lfloor{\frac{1}{4}×(N-2)^2}\rfloor}}$$

Try it on WolframAlpha.

2: Christopher Mowla's trig Formula:

$$8!×3^7×\left(\frac{24!}{(4!)^6}\right)^{\frac{1}{4}×((N-1)×(N-3)+\cos^2(\frac{N×\pi}{2}))}×(24!)^{\frac{1}{2}×(N-2-\sin^2(\frac{N×\pi}{2}))}×(12!×2^{10})^{\sin^2(\frac{N×\pi}{2})}×\frac{1}{24^{\cos^2(\frac{N×\pi}{2})}}$$

Try it on WolframAlpha.

3: Christopher Mowla's primes Formula:

$$2^{\frac{1}{2}×(2×N×(N+7)-17-11×(-1)^N)}×3^{N×(N+1)+2}×5^{\frac{1}{2}×(2×N×(N-2)+1+(-1)^N)}×7^{\frac{1}{8}×(6×N×(N-2)+3+5×(-1)^N)}×11^{\frac{1}{4}×(2×N×(N-2)-1+(-1)^N)}×96577^{\frac{1}{8}×(2×N×(N-2)-3+3×(-1)^N)}$$

where \\$96577\\$ is \\$(13×17×19×23)\\$.

Try it on WolframAlpha.

Source: Cubers-reddit - Mathematical Counting Formulas of Number of Positions, God's Number, etc.

## Challenge:

Choose and implement one of these three formulas (or your own derivative), which given an input-integer \\$N\\$ in the range \\$\[2,100\]\\$, outputs the correct result.

## Challenge rules:

* You are free to use another formula besides these three, but keep in mind that these three are proven to be correct. If you use another formula, please add a link of where you got it from (or if you come up with it yourself add an in-depth explanation). And I will check for all integers in the range if the output is correct. Perhaps inspiration could be found in the oeis for this sequence: A075152.
* If your language automatically outputs a scientific output (i.e. \\$1.401...×10^{45}\\$ instead of the number after the 4x4x4 formula) this is allowed. But please add additional code to your answer to convert this scientific rounding to an exact output so the results can be verified, since rounding errors due to floating point precision during the execution of the formula in your code is not allowed - the actual result should be exact.
* Your program/function should be correct for at least the inputs in the range \\$\[2,100\]\\$ (although, since \\$N=100\\$ already results in a huge-ass number, any larger \\$N\\$ will probably work as well if you're able to output this one correctly).
* You are not allowed to loop over all possible permutations with a counter, since that would never output anything in a reasonable amount of time. Only the implementation of a formula (either one of the three provided, a derivative of one of those, or a completely new formula), or another method that will give the correct results in a reasonable amount of time (without hard-coding of course) is allowed. I thought about adding a to enforce this, but I'm personally against in combination with , so I won't. Still, please make sure your program gives the answers, and if it's too slow for TIO for some reason, add some screenshots with the output from your local machine as verification.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

Here the test cases for \\$N\\$ in the range \\$\[2,10\]\\$ (feel free to use the WolframAlpha links above for larger test cases):

```
n=2
3674160

n=3
43252003274489856000

n=4
7401196841564901869874093974498574336000000000

n=5
282870942277741856536180333107150328293127731985672134721536000000000000000

n=6
157152858401024063281013959519483771508510790313968742344694684829502629887168573442107637760000000000000000000000000

n=7
19500551183731307835329126754019748794904992692043434567152132912323232706135469180065278712755853360682328551719137311299993600000000000000000000000000000000000

n=8
35173780923109452777509592367006557398539936328978098352427605879843998663990903628634874024098344287402504043608416113016679717941937308041012307368528117622006727311360000000000000000000000000000000000000000000000000

n=9
14170392390542612915246393916889970752732946384514830589276833655387444667609821068034079045039617216635075219765012566330942990302517903971787699783519265329288048603083134861573075573092224082416866010882486829056000000000000000000000000000000000000000000000000000000000000000

n=10
82983598512782362708769381780036344745129162094677382883567691311764021348095163778336143207042993152056079271030423741110902768732457008486832096777758106509177169197894747758859723340177608764906985646389382047319811227549112086753524742719830990076805422479380054016000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

*NOTE: Since this is a challenge, it basically boils down to: implement one of these three formulas (or a derivative / your own method that still produces the correct results) as short as possible.*

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
f@n_:=(s=24^6)(24!/s)^(m=n-2)f@m
f@2=7!3^6
f@3=4!12!2^10f@2

```

Try it online!

uses Herbert Kociemba's algorithm found in OEIS page

here is the recursive formula:
`a(1)=1; a(2)=7!*3^6; a(3)=8!*3^7*12!*2^10; a(n)=a(n-2)*24^6*(24!/24^6)^(n-2)`

*6 bytes saved by @Peter Taylor*

*one more byte saved by @Expired Data*
> 12 votes

# Answer
# x86 machine code, 119 bytes

Hexdump:

```
60 c6 02 02 33 db be 25 01 10 00 f6 c1 01 74 05
be 26 2a b2 36 33 ed 51 b1 06 33 ff 53 8a 04 1a
f6 e1 03 c7 b5 0a f6 f5 88 64 1a 02 66 98 8b f8
4b 79 ea 5b 43 43 f6 f5 66 89 02 84 c0 75 0c 60
8b fa 8d 72 01 8b cb f3 a4 61 4b 41 d1 ee 72 ca
75 f9 be 1d d4 0d 10 4d 79 be 59 49 49 8b e9 be
06 02 02 22 83 f9 02 73 ae c6 44 1a 01 00 80 0c
1a 30 4b 79 f9 61 c3

```

The function receives the number `n` in `ecx`, and a pointer to a string to fill in `edx` (i.e. `fastcall` convention).

Before I show the source code, some explanations on how it does the thing. It uses the recursive formula, which I wrote in the following way:

```
init = 2
m1 = 24^6 = 6*8*9*16*24*32*36
m2 = 24!/24^6 = 6*7*9*10*11*17*19*21*22*23*25*26*35
num(2) = init * 6*7*9*12*15*27
num(3) = init * 6*8*9*12*16*18*20*24*27*28*30*32*33*35*36
num(n+2) = num(n) * m1 * m2^n

```

So all the code should do is multiplication by small numbers. The numbers are in the range 6...36, which is small enough to be represented in a 32-bit bitmap. I actually don't store the bit which represents multiplication by 6 - this lets me arrange the code in a `do-while` loop, starting with unconditional multiplication by 6.

The big numbers are represented using decimal form - each byte is a value in the range 0...9, starting from the MSB.

The multiplication is performed from LSB to MSB; it assumes that the number of digits will grow by 2 for each multiplication. After doing multiplication by a small factor like 6, the number of digits may grow by only 1. So if MSB = 0, it moves the whole intermediate result left. It can actually happen that the number of digits doesn't grow at all, and then MSB will still be 0, but this problem will fix itself as the code proceeds to greater factors.

Because the multiplication code is large, I don't want to put it twice. I don't want to move it to a function either, because the machine code for calling a function is large. So I rearranged the outer loops in such a way that the multiplying code is needed only once.

C code:

```
void num(int n, char* x)
{
    *x = 2;
    int len = 1;
    int exp_i;
    uint32_t m32_1;
    int m1;
    int carry;
    int temp;
    int str_i;
    bool cf;

    if (n % 2 == 0)
    {
        m32_1 = 0x100125; // 6*7*9*12*15*27
    }
    else
    {
        m32_1 = 0x36b22a26; // 6*8*9*12*16*18*20*24*27*28*30*32*33*35*36
    }

    exp_i = 0;
    while (true)
    {
        for (; exp_i >= 0; --exp_i)
        {
            m1 = 6;
            cf = true;
        do_mult:
            carry = 0;
            for (str_i = len - 1; str_i >= 0; --str_i)
            {
                temp = x[str_i] * m1 + carry;
                x[str_i + 2] = temp % 10;
                carry = temp / 10;
            }
            len += 2;
            x[1] = carry % 10;
            carry /= 10;
            x[0] = carry;
            if (carry == 0)
            {
                --len;
                for (str_i = 0; str_i < len; ++str_i)
                    x[str_i] = x[str_i + 1];
            }

        shift_m1:
            ++m1;
            cf = m32_1 & 1;
            m32_1 >>= 1;
            if (cf)
                goto do_mult;
            if (m32_1)
                goto shift_m1;

            m32_1 = 0x100dd41d; // 24!/24^6 = 6*7*9*10*11*17*19*21*22*23*25*26*35
        }
        --n;
        --n;
        exp_i = n;
        if (n < 2)
            break;
        m32_1 = 0x22020206; // 24^6

    }
    x[len] = 0;
    for (str_i = len - 1; str_i >= 0; --str_i)
    {
        x[str_i] += '0';
    }
}

```

Disassembly:

```
60                     pushad;
C6 02 02               mov byte ptr [edx], 2; // edx = x
33 DB                  xor ebx, ebx; // ebx = len - 1
BE 25 01 10 00         mov esi, 0x100125; // esi = m32_1
F6 C1 01               test cl, 1;
74 05                  jz skip1;
BE 26 2A B2 36         mov esi, 0x36b22a26; // esi = m32_1
                   skip1:
33 ED                  xor ebp, ebp; // ebp = exp_i

                   loop_n:

51                     push ecx;
                   loop_exp_i:
B1 06                  mov cl, 6; // cl = m1
                   do_mult:
33 FF                  xor edi, edi; // edi = carry
53                     push ebx; // ebx = str_i
                   loop_str_i:
8A 04 1A               mov al, [edx + ebx];
F6 E1                  mul cl;
03 C7                  add eax, edi;
B5 0A                  mov ch, 10;
F6 F5                  div ch;
88 64 1A 02            mov [edx + ebx + 2], ah;
66 98                  cbw;
8B F8                  mov edi, eax;
4B                     dec ebx;
79 EA                  jns loop_str_i;

5B                     pop ebx; // ebx = len - 1
43                     inc ebx;
43                     inc ebx;
F6 F5                  div ch;
66 89 02               mov [edx], ax;

84 C0                  test al, al;
75 0C                  jnz skip2;

60                     pushad;
8B FA                  mov edi, edx;
8D 72 01               lea esi, [edx + 1];
8B CB                  mov ecx, ebx;
F3 A4                  rep movsb;
61                     popad;
4B                     dec ebx;
                   skip2:

                   shift_m1:
41                     inc ecx;
D1 EE                  shr esi, 1;
72 CA                  jc do_mult;
75 F9                  jnz shift_m1;

BE 1D D4 0D 10         mov esi, 0x100dd41d;

4D                     dec ebp;
79 BE                  jns loop_exp_i;

59                     pop ecx; // ecx = n
49                     dec ecx;
49                     dec ecx;
8B E9                  mov ebp, ecx;
BE 06 02 02 22         mov esi, 0x22020206;
83 F9 02               cmp ecx, 2;
73 AE                  jae loop_n;

C6 44 1A 01 00         mov byte ptr [edx + ebx + 1], 0;
                   loop_to_ascii:
80 0C 1A 30            or byte ptr [edx + ebx], '0';
4B                     dec ebx;
                       dec         ebx
79 F9                  jns loop_to_ascii;

61                     popad;
C3                     ret;

```

The running time for n = 100 is about 4 seconds, and the result is a number with 38416 digits:

23491019577617 (many digits here) ... (many zeros here) 0000000000000000
> 10 votes

# Answer
# 05AB1E, 38 bytes

Initial attempt.
Uses *Chris Hardwick's Formula*.
Will attempt to golf further and explain when I have time.

```
24©To12!PIÉm7!729®!InI·-4÷mP®IÍn4÷6*m÷

```

Try it online!
> 8 votes

# Answer
# Julia 1.0, ~~83~~ 76 bytes

```
n->^(24576*~12,n%2)*3^6*~7(~24)^((m=n-2)n÷4)/24^(m^2÷4*6)
~n=prod(big,1:n)

```

Try it online!

Uses Chris Hardwick's Formula. Takes input as Big integer.

Thanks to H.PWiz for -7 bytes
> 8 votes

# Answer
# Python 2, 72 bytes

```
lambda n:3674160*61600**(n%2)*24**(~-n/2*6)*0xb88d4641131f0**(n*(n-2)/4)

```

Try it online!

Saved 4 bytes by copying `n*(n-2)/4` from Neil.
> 7 votes

# Answer
# Wolfram Language (Mathematica), 67 bytes

Using Chris Hardwick's Formula.

```
(12!24576)^Mod[#,2]7!729(24!)^⌊#(#-2)/4⌋/24^(6⌊(#-2)^2/4⌋)&

```

Try it online!
> 6 votes

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

Herbert Kociemba's recursive formula. Takes a BigInt as input.

```
f=n=>[1n,3674160n,322252536375n<<27n][--n]||f(--n)*0xb640000n*0xb88d4641131f0n**n

```

Try it online!

---

# JavaScript (Node.js),  ~~102 98~~  96 bytes

Chris Hardwick's formula. Takes a BigInt as input.

```
n=>(n&1n?1403325n<<25n:4n)*918540n*0x83629343d3dcd1c00000n**(n*n-n-n>>2n)/24n**(6n*(n*n/4n-~-n))

```

Try it online!
> 6 votes

# Answer
# JavaScript (Node.js), ~~77~~ ~~75~~ 73 bytes

```
n=>0xb88d4641131f0n**(n*(n-2n)/4n)*13824n**n*851558400n**(n%2n)*315n>>14n

```

Try it online! Based on Christopher Mowla's formula. Takes a BigInt as input. Test harness shamelessly stolen from @Arnauld. `0xb88d4641131f0n` is `3246670537110000n` in decimal. Explanation: I started with the last prime exponent and simplified it to `n*(n-2n)/4n` (this is integer division, so I don't need the adjustment for odd numbers). I then examined the other primes to see whether their exponents were related to this value (which I shall refer to as `o`), and found that they were after a fashion, if I allowed the use of the parity of `n` (which I shall refer to as `p`). The formulae for the exponents are as follows:

```
23:       o
19:       o
17:       o
13:       o
11:      2o +   p
 7:      3o +   p +  1
 5:      4o +  2p +  1
 3: 3n + 4o +  3p +  2
 2: 9n + 4o + 14p - 14

```

The powers can then be grouped by exponent so for example `p` is the exponent of `11*7*5**2*3**3*2**14`.
> 6 votes

# Answer
## Racket, ~~151~~ 141 bytes

-7 bytes thanks to fede s.!

```
(λ(n[e expt])(/(*(e 11771943321600(modulo n 2))3674160(e 620448401733239439360000(floor(/(*(- n 2)n)4))))(e 24(*(floor(/(sqr(- n 2))4))6))))

```

Try it online!

The longest answer using Chris Hardwick's Formula :)
> 5 votes

# Answer
# Python 2, 122 bytes

```
import math
f=math.factorial
x=lambda n:(1,f(7)*729,f(8)*3**7*f(12)*1024)[n-1]if n<4else x(n-2)*24**6*(f(24)/24**6)**(n-2)

```

Try it online!

Uses the Herbert Kociemba recursive method.

-2 bytes thanks to Herman L
> 4 votes

# Answer
# Jelly,  ~~39~~  38 bytes

I feel like I've missed some golfs, but...

```
12!×⁽^K*Ḃɓ_2×ṭ¥⁸:4×1,6“ð¥‘!¤*:/×“9Ḟɠ’×

```

A monadic Link implementing Chris Hardwick's Formula.

**Try it online!** Or see the test-suite (`n=[1..33]`).
> 4 votes

# Answer
## CJam (47 bytes)

```
qi[1_7m!Z6#*_3*Cm!*2D#*]{2-_j24_m!\6#:P/@#*P*}j

```

Online demo

This implements Herbert Kociemba's recursion from OEIS: $$a(n) = \begin{cases} 1 & \textrm{ if } n \in \\{0,1\\} \\ 7! \times 3^6 & \textrm{ if } n=2 \\ a(n-1) \times 3\times 12!\times 2^{13} & \textrm{ if } n=3 \\ a(n-2) \times \left(\frac{24!}{24^6}\right)^{n-2} \times 24^6 & \textrm{ if } n\>3 \end{cases}$$ using CJam's memoised recursion operator `j`. I've ordered the terms in the MathJax block in the same order as in the code to make the correspondence easy to verify for those who read CJam: any further dissection is not going to shed more light.
> 3 votes

# Answer
# Icon, ~~125~~ 110 bytes

```
procedure f(n)
q:=1;every q*:=1 to 24
return 11771943321600^(n%2)*5040*3^6*q^(n*(t:=n-2)/4)/24^(6*(t^2/4))
end

```

Try it online!
> 2 votes

# Answer
# Jelly, 43 bytes

```
_2²:4×6*@24
²_Ḥ:4;ḂU
“€ð‘!×⁽^K,1*ÇP×“9Ḟɠ’:Ñ

```

Try it online!
> 2 votes

# Answer
# C (gcc) -lgmp, 279 bytes

```
#include "gmp.h"
#define s mpz_init_set_str
#define m(X)mpz_##X
f(int N,m(t)_){m(t)x;m(init)(x);m(init_set_str)(_,N&1?"3LFbOUwC":"1",62);m(mul_si)(_,_,3674160);m(fac_ui)(x,24);m(pow_ui)(x,x,(N*N-2*N)/4);m(mul)(_,_,x);m(set_si)(x,24);N-=2;m(pow_ui)(x,x,6*N*N/4);m(tdiv_q)(_,_,x);}

```

Try it online!
> 2 votes

# Answer
# Perl 6, 85 bytes

```
{0xAB4DE800000**($_%2)*3674160*([*] 1..24)**($_*($_-2)div 4)/24**(($_-2)**2 div 4*6)}

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~86~~ ~~85~~ 74 bytes

-1 byte saved thanks to H.PWiz
-11 bytes saved thanks to Max Yekhlakov

```
a=24^6
r 2=3674160
r 3=r 2*a*61600
r n=r(n-2)*a*div(product[2..24])a^(n-2)

```

Try it online!
> 2 votes

# Answer
# Husk, ~~51~~ ~~48~~ 44 bytes

-4 bytes thanks to H.PWiz

```
÷^*6÷4□-2⁰Π4*^÷4-D⁰□⁰Π24*729*Π7^%2⁰*24576Π12

```

Try it online!

This is Chris Hardwick's Formula. Also, this is my first husk program, so any tips would be well appreciated.
> 2 votes

# Answer
# TI-BASIC, ~~63~~ 62 bytes, (noncompeting)

```
{fPart(.5Ans),1,1,-6}int(4⁻¹{8,4,Ans²-2Ans,(Ans-2)²:prod({9*11!2^15,7!3^6,24!,24}^Ans

```

Expression which takes input as an integer on `Ans`. Implementation of Chris Hardwick's formula. Noncompeting because the hardware it runs on will only store up to 16 decimal places, so the answer will never be 100% accurate.

Explanation:

```
{fPart(.5Ans),1,1,-6}              # the list {(N (mod 2))/2,1,1,-6}
                                   # implicitly multiplied by
int(4⁻¹{8,4,Ans²-2Ans,(Ans-2)²     # the list {2,1,⌊¼(N²-2N)⌋,⌊¼(N-2)²⌋}
:                                  # store this list of the formula's exponents as Ans
     {9*11!2^15,7!3^6,24!,24}      # list of the formula's bases
                             ^Ans  # raised to their exponents
prod(                              # multiplied together
                                   # implicit print

```
> 1 votes

# Answer
# Python 2, 92 bytes

```
lambda n:0xab4de800000**(n%2)*3674160*0x83629343d3dcd1c00000**(n*(n-2)/4)/24**((n-2)**2/4*6)

```

Try it online!
> 1 votes

# Answer
# C++, ~~187 185 180 176 195(there was a bug) 193~~ 175 bytes (with help from ceiling cat)

This uses the GMP C++ wrapper (GNU multi-precision library), and the formula used by @J42161217 (https://codegolf.stackexchange.com/a/183381/55953).

Use `g++ -g rubix.cpp -lgmp -lgmpxx` to compile and link

```
#include <gmpxx.h>
#define R return
using z=mpz_class;z p(z a,z b){z c=1;while(b--)c*=a;R c;}z r(z n){if(n==2)R 3674160;if(n==3)R z("pX4dIaR7jDk",62);R r(n-2)*p(24,6)*p(z("ErvSErbeq",62),n-2);}

```

ungolfed, with test code

```
#include <gmpxx.h>
#include <iostream>
mpz_class p(mpz_class a, mpz_class b) // returns a to power of b. Only works for b  = positive integer
{
    mpz_class c=1;

    while(b--)
        c*=a;

    return c;
}

mpz_class r(mpz_class n) // returns the rubix permutations for a cube of size n
{
    if(n==2)
        return 3674160; // 7!*3^6;

    if(n==3)
        return z("pX4dIaR7jDk",62); // 43252003274489856000 = 8!*3^7*12!*2^10

    return r(n-2) * p(24,6) * p(z("ErvSErbeq", 62), n-2);

    // "ErvSErbeq"base 62 = 3246670537110000 = (24!/24^6)
}

main()
{
    for(int i=2; i<34; i++)
        std::cout<<i<<'\t'<<r(i) << std::endl;
}

```

https://tio.run/##PZAxb4MwEIV3foWVDrETqBpARMImWZqha7t0iFQZ4xC3xrg2tJERf73UIVXfcE937zvpdEzrqGZsmu6EYrKvOKkbfbncn3dBb4WqgSsa7d6YpNZiBzR0gIYOlGhwgBUb/H0WksMyihBbFRQb3vVGAYZHB4xnFRr@Rqoo4n2SbdNN9pD7Jtk7uNCvafVEn7fvjx@LMItRbqCKYrTSME7D7OoeOpivl4Mp@eeMhFcAj//3AiJa2xlOm13QUKEgCoYAeJ1aA4XqgChiDARJUl/XazRnXrar8py1fUeIIGR57JaE@AUECLllXFUSB2Mw/bCTpLWdIjm/5ua/
> 1 votes

---
Tags: code-golf, math, number, combinatorics, rubiks-cube
---


title: The Nth Gryphon Number

text:
# Question
Title: The Nth Gryphon Number
I came up with a series of numbers the other day and decided to check what the OEIS number for it was. Much to my surprise, the sequence did not appear to be in the OEIS database, so I decided to name the sequence after myself (note that someone else who's a lot smarter than me has probably already come up with this, and if someone finds the actual name of this sequence, please comment and I'll change the question title). As I couldn't find the sequence anywhere, I decided to name it after myself, hence "Gryphon Numbers". EDIT: Thanks to @Surb for bringing to my attention the fact that this sequence is equal to OEIS sequence A053696 \- 1.

A Gryphon number is a number of the form \\$a+a^2+...+a^x\\$, where both \\$a\\$ and \\$x\\$ are integers greater than or equal to two, and the Gryphon sequence is the set of all Gryphon numbers in ascending order. If there are multiple ways of forming a Gryphon number (the first example is \\$30\\$, which is both \\$2+2^2+2^3+2^4\\$ and \\$5+5^2\\$) the number is only counted once in the sequence. The first few Gryphon numbers are: \\$6, 12, 14, 20, 30, 39, 42, 56, 62, 72\\$.

## Your Task:

Write a program or function that receives an integer \\$n\\$ as input and outputs the \\$n\\$th Gryphon number.

## Input:

An integer between 0 and 10000 (inclusive). You may treat the sequence as either 0-indexed or 1-indexed, whichever you prefer. Please state which indexing system you use in your answer to avoid confusion.

## Output:

The Gryphon number corresponding to the input.

## Test Cases:

Please note that this assumes the sequence is 0-indexed. If your program assumes a 1-indexed sequence, don't forget to increment all the input numbers.

```
Input:    Output:
0   --->  6
3   --->  20
4   --->  30
10  --->  84
99  --->  4692
9999 -->  87525380

```

## Scoring:

This is , so the lowest score in bytes wins.

# Answer
> 15 votes
# Jelly, 9 bytes

```
bṖ’ḅi-µ#Ṫ

```

A full program which reads a (1-indexed) integer from STDIN and prints the result.

**Try it online!**

### How?

A Gryphon number is a number which is expressible in a base less than itself such that all the digits are ones except the least significant, which is a zero. For example:

\\$30=1\times 2^4+1\times 2^3+1\times2^2+1\times2^1+0\times2^0 \rightarrow 30\_2 = 11110\\$

\\$84=1\times 4^3+1\times 4^2+1\times 4^1+0\times 4^0 \rightarrow 84\_4 = 1110\\$

This program takes `n`, then starts at `v=0` and tests for this property and increments `v` until it finds `n` such numbers, then outputs the final one.

To test a base `b` number it subtracts one from every digit, converts from base `v`, and then checks if the result is \\$-1\\$. (Note that `b` is less than `v`)

\\$30\_2 \rightarrow 0\times 30^4+0\times 30^3+0\times30^2+0\times30^1+(-1)\times30^0 = -1\\$

\\$84\_4 \rightarrow 0\times 84^3+0\times 84^2+0\times 84^1+(-1)\times 84^0 = -1\\$

```
bṖ’ḅi-µ#Ṫ - Main Link: no arguments
       #  - set v=0 then count up collecting n=STDIN matches of:
      µ   -  the monadic link -- i.e. f(v):  e.g. v=6
 Ṗ        -    pop (implicit range of v)            [1,2,3,4,5]
b         -    to base (vectorises)                 [[1,1,1,1,1,1],[1,1,0],[2,0],[1,2],[1,1]]
  ’       -    decrement (vectorises)               [[0,0,0,0,0,0],[0,0,-1],[1,-1],[0,1],[0,0]]
   ḅ      -    from base (v) (vectorises)           [0,-1,5,1,0]
     -    -    literal -1                           -1
    i     -    first index of (zero if not found)   2
          - }  e.g. n=11 -> [6,12,14,20,30,39,42,56,62,72,84]
        Ṫ - tail         -> 84
          - implicit print

```

# Answer
> 11 votes
# MATL, ~~16~~ 13 bytes

```
:Qtt!^Ys+uSG)

```

1-based.

**Try it online!**

### Explanation

Consider input `n = 3` as an example.

```
:    % Implicit input: n. Range
     % STACK: [1 2 3]
Q    % Add 1, element-wise
     % STACK: [2 3 4]
tt   % Duplicate twice, transpose
     % STACK: [2 3 4], [2 3 4], [2;
                                 3;
                                 4]
^    % Power, element-wise with broadcast
     % STACK: [2 3 4], [ 4   9  16;
                         8  27  64;
                        16  81 256]
Ys   % Cumulative sum of each column
     % STACK: [2 3 4], [ 4    9  16;
                         12  36  80;
                         28 117 336]
+    % Add, element-wise with broadcast (*)
     % STACK: [ 6  12  20;
               14  39  84
               30 120 340]
u    % Unique elements. Gives a column vector
     % STACK: [  6;
                14;
                30;
                12;
               ···
               340]
S    % Sort
     % STACK: [  6;
                12
                14;
                20;
               ···
               340]
G)   % Push input again, index. This gets the n-th element. Implicit display
     % STACK: 14

```

The matrix obtained in step (\*) contains possibly repeated Gryphon numbers. In particular, it contains `n` distinct Gryphon numbers in its first row. These are not necessarily the `n` smallest Gryphon numbers. However, the lower-left entry `2+2^+···+2^n` exceeds the upper-right entry `n+n^2`, and thus all the numbers in the last row exceed those in the first row. This implies that extending the matrix rightward or downward would not contribute any Gryphon number lower than the lowest `n` numbers in the matrix. Therefore, the matrix is guaranteed to contain the `n` smallest Gryphon numbers. Consequently, its `n`-th lowest unique element is the solution.

# Answer
> 9 votes
# Haskell, 53 bytes

```
([n|n<-[6..],or[a^y+n==n*a+a|a<-[2..n],y<-[3..n]]]!!)

```

Try it online!

\\$\newcommand{\ta}{{a}}\newcommand{\ti}{{i}}\newcommand{\tx}{{x}}\newcommand{\tn}{{n}}\newcommand{\ty}{{y}}\\$A number \\$\tn\\$ is Gryphon if there exist integers \\$\ta \geq 2\\$ and \\$\tx \geq 2\\$ such that \\$\tn=\sum\_{i=1}^\tx \ta^i\\$.

We generate an infinite list of all \\$\tn \geq 6\\$ such that a brute-force search shows this is the case.

The answer is a (zero-indexed) index function into this list, denoted in Haskell as `(list!!)`.

## Why is `a^y+n==n*a+a` correct?

From the formula for summing a geometric progression:

> $$\sum\_{i=1}^\nu \alpha \rho^{i-1} = \frac{\alpha(1-\rho^\nu)}{1-\rho}$$

we have, letting \\$(\alpha, \rho, \nu) = (\ta, \ta, \tx)\\$: $$\tn = \sum\_{\ti=1}^\tx \ta^\ti = \frac{\ta(1-\ta^\tx)}{1-\ta} = \frac{\ta-\ta^{\tx+1}}{1-\ta}.$$

Rearranging the equation, we get \\$n(1-a) = a - a^{x+1}\\$.

Rearranging that even further, we get \\$\ta^{\tx+1}+n = \tn \ta + \ta\\$.

A substitution \\$\ty = \tx+1\\$ in the brute-force search yields the final expression `a^y+n=n*a+a`.

## Is searching until `n` enough?

* If \\$\ta \> \tn\\$ (in other words, \\$\ta \geq \tn+1\\$), then $$\ta^\ty + \tn \> \ta^2 \geq (\tn+1)\ta = \tn\ta + \ta$$ which proves \\$\ta^\ty+\tn \neq \tn\ta+\ta\\$. So there's no sense checking any of the values \\$\ta \> \tn\\$.
* Similarly: if \\$\ty \> \tn\\$, then $$\ta^\ty + \tn \> \ta^\tn = \ta^{\tn-1}\ta \geq 2^{\tn-1}\ta \stackrel{\color{red}\*}\> (\tn+1)\ta = \tn\ta + \ta,$$ again proving \\$\ta^\ty + \tn \neq \tn\ta + \ta\\$.

\\$\color{red}{{}^{\*}}\\$We can assume \\$2^{n-1}\>n+1\\$ because we know \\$n \geq 6\\$, the smallest Gryphon number.

# Answer
> 7 votes
# Python 3.8 (Pre-release), 98 92 89 78 71 bytes

```
lambda n:sorted({a*~-a**x//~-a for a in(r:=range(2,n+3))for x in r})[n]

```

Try it online!

0-indexed. Integer division must be used here because f(10000) overflows floats.

Generates all Gryphon numbers where \\$2 \leq a \leq n+2\\$ and \\$2 \leq x \leq n+2\\$, sorts them, and selects the \\$n\\$th element.

-6 bytes thanks to Jonathan Allan

-3 bytes thanks to ArBo. I almost did as he suggested myself, but tried to use `{*(...)}` which didn't save space anyway

-11 bytes thanks to mathmandan

-7 bytes thanks to ArBo

## Mathematical Proof of Validity

Using 0-indexing for the sake of this proof, even though mathematical convention is 1-indexed.

* Let \\$G\_n\\$ be the \\$n\\$th Gryphon number
* Let \\$g(a,x) = a + a^2 + ... + a^x\\$ (The Gryphon number from \\$a\\$ and \\$x\\$)
* Let \\$A\_n\\$ be the set of all Gryphon numbers where \\$2 \leq a \leq n+2\\$ and \\$2 \leq x \leq n+2\\$
* We know that \\$A\_0 = \\{ g(2,2) \\} = \\{ 6 \\} = \\{ G\_0 \\}\\$
* \\$A\_{n+1} = \\{ g(a, x), g(a+1, x), g(a, x+1), g(a+1, x+1) | g(a, x) \in A\_n \\} \\$
* \\$g(a+1, x) \< g(a+1, x+1)\\$ for all \\$a\\$ and \\$x\\$
* \\$g(a, x+1) \< g(a+1, x+1)\\$ for all \\$a\\$ and \\$x\\$
* Therefore \\$G\_{n+1} \neq g(a+1, x+1)\\$ if \\$G\_n = g(a, x)\\$
* \\$g(a+1, x) \< g(a+2, x)\\$ for all \\$a\\$ and \\$x\\$
* \\$g(a, x+1) \< g(a, x+2)\\$ for all \\$a\\$ and \\$x\\$
* Therefore \\$G\_{n+1}\\$ must either be \\$g(a+1, x)\\$ or \\$g(a, x+1)\\$ if \\$G\_n = g(a, x)\\$ since no other possibilities exist.
* We can use this information to conclude that \\$G\_{n+1} \in A\_{n+1}\\$ if \\$G\_n \in A\_n\\$
* Since we know that \\$G\_0 \in A\_0\\$, we can use this rule to induce that \\$G\_n \in A\_n\\$ for all \\$n\\$
* Since this can be applied from \\$G\_0\\$ to \\$G\_n\\$, then \\$G\_n\\$ must be at index \\$n\\$ of \\$A\_n\\$ if \\$A\_n\\$ is ordered from smallest to largest

# Answer
> 5 votes
# , ~~35~~ 32 bytes

*-3 bytes thanks to FrownyFrog*

```
3 :'y{/:~~.,}.+/\(^~/>:)1+i.y+2'

```

Try it online!

Explanation is same as original. Simply uses explicit form to save bytes be removing the multiple `@`.

## original answer, tacit, with explanation: 35 bytes

```
{[:/:~@~.@,@}.[:+/\@(^~/>:)1+i.@+&2

```

Try it online!

Similar to Luis Mendo's approach, we create a "power table" (like a times table) with top row `2 3 ... n` and left column `1 2 ... n` resulting in:

```
 2   3    4     5     6      7
 4   9   16    25    36     49
 8  27   64   125   216    343
16  81  256   625  1296   2401
32 243 1024  3125  7776  16807
64 729 4096 15625 46656 117649

```

`^~/ >:` creates the table, and `1+i.@+&2` creates the `1... n` sequences, and we add 2 (`+&2`) to the input to ensure we always have enough elements to create a table even for 0 or 1 inputs.

After we have the table above the solution is trivial. We just scan sum the rows `+/\`, and then remove the first row, flatten, take unique, and sort `/:~@~.@,@}.`. Finally `{` uses the original input to index into that result, producing the answer.

# Answer
> 3 votes
# , ~~65~~ 62 bytes

-1 byte thanks to Giuseppe.

```
n=scan();unique(sort(diffinv(t(outer(2:n,1:n,"^")))[3:n,]))[n]

```

Try it online!

1-indexed.

Generates a matrix of all values of the form \\$a^i\\$, takes the cumulative sum, removes the first row (0s) and the second row (entries corresponding to \\$x=1\\$), then takes the unique sorted values.

Note that `sort(unique(...))` would not work, as `unique` would give unique rows of the matrix, and not unique entries. Using `unique(sort(...))` works because `sort` converts to vector.

# Answer
> 3 votes
# Gaia, 18 bytes

```
)┅:1D¤*‡+⊣¦tv<_uȯE

```

Try it online!

1-based index.

This is a rather sad answer with a long nose: `)┅:` It probably wishes it could be golfed down further.

Copies the algorithm given by Luis Mendo's answer

# Answer
> 2 votes
# Wolfram Language (Mathematica), 51 bytes

```
(Union@@Array[Sum[(#2+1)^k,{k,#+1}]&,{30,#}])[[#]]&

```

Try it online!

1-indexed

*-8 bytes from @attinat*

# Answer
> 2 votes
# JavaScript (ES7), 76 bytes

1-indexed.

```
f=(n,a=[i=2])=>(n-=a.some(j=>a.some(k=>(s+=j**k)==i,s=j)))?f(n,[...a,++i]):i

```

Try it online!

---

# JavaScript (ES7), 89 bytes

1-indexed.

```
n=>eval('for(a=[i=1e4];--i>1;)for(s=1e8+i,x=1;a[s+=i**++x]=x<26;);Object.keys(a)[n]-1e8')

```

Try it online!

# Answer
> 1 votes
# Charcoal, 36 bytes

```
ＮθＦθＦθ⊞υ÷⁻Ｘ⁺²ι⁺³κ⁺²ι⊕ιＦ⊖θ≔Φυ›κ⌊υυＩ⌊υ

```

Try it online! Link is to verbose version of code. 1-indexed. Uses Luis Mendo's algorithm. Explanation:

```
Ｎθ

```

Input \\$ n \\$.

```
ＦθＦθ⊞υ

```

Create an \\$ n \\$-by-\\$ n \\$ grid of Gryphon numbers and push each one to the predefined list.

```
÷⁻Ｘ⁺²ι⁺³κ⁺²ι⊕ι

```

Calculate the Gryphon number using the fact that \\$ \sum\_1^x a^i = \frac{a^{x+1}-a}{a-1} \\$.

```
Ｆ⊖θ≔Φυ›κ⌊υυ

```

Remove the lowest \\$ n-1 \\$ Gryphon numbers.

```
Ｉ⌊υ

```

Print the lowest remaining Gryphon number.

# Answer
> 1 votes
# Japt, 23 bytes

Dear Jebus! Either I *really* have forgotten how to golf or the booze is finally taking its toll!

Not a direct port of Jonathan's solution but very much inspired by his observation.

```
@ÈÇXìZ mÉ ìZÃeÄ}fXÄ}gNÅ

```

Try it

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
L¦ãε`LmO}êIè

```

0-indexed

Try it online or verify the first \\$n\\$ items.

**Explanation:**

```
L             # Create a list in the range [1, (implicit) input-integer]
              #  i.e. 4 → [1,2,3,4]
 ¦            # Remove the first item to make the range [2, input-integer]
              #  i.e. [1,2,3,4] → [2,3,4]
  ã           # Create each possible pair of this list by using the cartesian product
              #  i.e. [2,3,4] → [[2,2],[2,3],[2,4],[3,2],[3,3],[3,4],[4,2],[4,3],[4,4]]
   ε          # Map each pair to:
    `         #  Push the values of the pair separately to the stack
              #   i.e. [4,3] → 4 and 3
     L        #  Take the list [1, value] for the second value of the two
              #   i.e. 3 → [1,2,3]
      m       #  And then take the first value to the power of each integer in this list
              #   i.e. 4 and [1,2,3] → [4,16,64]
       O      #  After which we sum the list
              #   i.e. [4,16,64] → 84
        }ê    # After the map: uniquify and sort the values
              #  i.e. [6,14,30,12,39,120,20,84,340] → [6,12,14,20,30,39,84,120,340]
          Iè  # And index the input-integer into it
              #  i.e. [6,12,14,20,30,39,84,120,340] and 4 → 30
              # (after which the result is output implicitly)

```

---
Tags: code-golf, sequence
---


# Question
Title: Map values to any multidimensional array
## Codegolf challenge - mapping values in a multidimensional array

```
[
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
]

```

This **2D** array is sick of being so **false**, and wants to find the **truth** about life, once and **for** all. Your task is to write a map function to act as a highway to all the values in this array.

An example implementation of this super function would be if the above array is defined as `arr` below:

```
arr.multimap(x => {
  return 1;
}

```

Which would result in the array being:

```
[
  [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1]
]

```

This is a 2D number example, yours has to work in any dimension, and not be dimensionally-bias.

---

## The rules

* Must work in any type of dimensional array (1D, 2D, 3D, etc..)
* Least bytes, wins!
* Must only have one callback function which accounts for any level of dimensional interaction
* Meta-languages get fewer points
* Can simply be a function which applies the logic to an array given
* Can be any arbitrary initial value, as long as you can replace it on-command

# Answer
> 3 votes
# JavaScript (Node.js), ~~35~~ ~~27~~ 17 bytes

*-18 thanks to @Arnauld and @Shaggy*

```
f=a=>a?a.map(f):1

console.log(f([
  [0, 0, 0],
  [0, [0, 0, 0], 0],
  [[0, 0, [0]], 0, 0]
]))
```

# Answer
> 2 votes
# Jelly, 1 byte

Try it online!

Replaces `n` with `n + 1`.

Because Jelly things.

Note that `[x]` displays as `x` in Jelly (single-element lists don't show as lists); the internal data is still a single-element list. You can make it show using Python's `str`: Try it online!.

# Answer
> 1 votes
# Python 2, ~~29~~ ~~26~~ 25 bytes

*-3 bytes thanks to @JonathanAllan*

*-1 byte thanks to @JoKing*

```
f=lambda a:a<1or map(f,a)

```

Replaces `0` with `True`

Try it online!

# Answer
> 1 votes
# Perl 6, 4 bytes

```
!<<*

```

Try it online!

Replaces `0`s with `True`. *Extremely* short for a non-esolang.

```
   *  # From the input
!     # Boolean not
 <<   # Each element recursively

```

# Answer
> 0 votes
# Japt, 6 bytes

```
?¡ßX:1

```

Try it

```
¬Íª¡ßX

```

Try it

# Answer
> 0 votes
# JavaScript, 36 bytes

```
t=>JSON.stringify(t).replace(/0/g,1)

```

Try it online!

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


# Question
Title: Code Golf: Forwards sdrawkcaB sdrawkcaB Forwards Forwards sdrawkcaB
**Task**

* The user inputs a sentence - words only. Any input other than letters or spaces, including integers and punctuation, should throw an exception: "Sentence must only use letters".
* The output has a pattern, where some words are reversed and others words are normal.
* The pattern starts as a normal word, the next two words are reversed, then the next two words are normal and the pattern continues.
* An example of where the words should be normal and where words reversed is below:

Normal - Reversed - Reversed - Normal - Normal - Reversed - Reversed - Normal ...

**Input Example**

She sells Sea shells on the Sea shore

**Output Example**

She slles aeS shells on eht aeS shore

**Additional Rules**

* If capital letters are used, they should remain on the letter they were originally posted on.
* Any multiple spaces initially posted on input should be reduced to one space. For example `Programming Puzzles and Code Golf` becomes `Programming selzzuP dna Code Golf`

Shortest Code Wins!!

Happy coding...

# Answer
> 15 votes
# TeaScript, 55 bytes ~~58 60 69 76 78 80 87 89~~

```
xO`a-z `?xl(#~-i&2?l:lv(),/ +/):Ld`SÀZn Û § «e Ò5s`

```

This is *extremely* short, I'm very happy with it.

The last ~20 characters may seem like gibberish but that's "Sentence must only use letters" encoded. All the characters have char codes below 256 so each are one byte

### Explanation

```
xO`a-z `?  // If input contains only a-z and space...

   xl(#       // Loop through input
      ~-i&2?  // If (index - 1 "unary and"ed with 2) isn't 0...
          :l,     // Leave alone
          lv()    // Otherwise, reverse string
       / +/ // Loops on spaces
   )

:Ld`SÀZn Û § «e Ò5s` // Otherwise... decompress and print  the error string

```

# Answer
> 4 votes
## Haskell, 141 bytes

```
r=reverse
f x|all(`elem`(' ':['a'..'z']++['A'..'Z']))x=unwords$zipWith($)(cycle[id,r,r,id])$words x|1<2=error"Sentence must only use letters"

```

Almost 2/3 of the code is for error checking. Seems to be the first real world challenge.

The work is done by `unwords$zipWith($)(cycle[id,reverse,reverse,id])$words x` which splits the input into a list of words, zips it with the cycling list of functions `[id,reverse,reverse,id,id,reverse...]` and joins the result with spaces back to a single string.

Thanks to @Christian Irwan for 2 bytes.

# Answer
> 3 votes
# JavaScript (ES6) 122

```
f=s=>/[^a-z ]/i.test(s)?"Sentence must only use letters":s.split(/ +/).map((w,i)=>~-i&2?w:[...w].reverse().join``).join` `

alert(f(prompt('?','She sells Sea shells on the Sea shore')))
```

# Answer
> 2 votes
# Python, ~~163~~ ~~160~~ ~~157~~ 145

```
k=raw_input()
k=["Sentence tsum ylno use letters",k][k.replace(' ','').isalpha()]
for i,x in enumerate(k.split()):print x[::-1if(i+1)/2%2else 1],

```

Removed 15 characters, thanks Mego!!

# Answer
> 2 votes
# Retina, 103 bytes

```
\s+

(?<=^\S+ (\S+ )?((\S+ ){4})*)
;
+`(;\S*)(\S)
$2$1
;

i`.*[^a-z ].*
Sentence must only use letters

```

There should be a single space on the second line, which SE seems to be swallowing. Run the code from a single file with the `-s` flag.

Retina has no concept of exceptions so the output is simply replaced by `Sentence must only use letters` if there are non-letter non-whitespace characters in the input.

# Answer
> 2 votes
# Pyth, 61 bytes

```
?.A}R+G\ rz0jd.e_W%%k4 3bfTczd"Sentence must only use letters

```

Try it online.

# Answer
> 1 votes
# Bash + coreutils, 108

```
[ ${@//[a-zA-Z]/} ]&&echo Sentence must only use letters||for t;{
((++i/2%2))&&rev<<<$t||echo $t
}|tr \\n \

```

The last character of this program is a space.

Input is taken from the command line:

```
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf
Programming selzzuP dna Code Golf $
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf1
Sentence must only use letters
$

```

# Answer
> 1 votes
# Julia, ~~150~~ 134 bytes

```
s->ismatch(r"[^a-z ]"i,s)?error("Sentence must only use letters"):(i=3;join([(i+=1;isodd((i+1)i÷2)?reverse(w):w)for w=split(s)]," "))

```

Ungolfed:

```
function f(s::AbstractString)
    if ismatch(r"[^a-z ]"i, s)
        error("Sentence must only use letters")
    else
        i = 3
        a = [(i += 3; isodd((i + 1)i ÷ 2) ? reverse(w) : w) for w = split(s)]
        return join(a, " ")
    end
end

```

Saved 16 bytes thanks to Glen O!

# Answer
> 1 votes
# Pyth, 72

```
=zflTc?:z"[^A-Za-z ]"0"Sentence tsum ylno use letters"zdjd.e?%/hk2 2_bbz

```

Doesn't beat the other Pyth answer, but I already invested time into writing it. It's basically a translation of my Python answer.

Try it online

# Answer
> 1 votes
# Julia, 109 bytes

```
s->(i=0;join([isalpha(w)?(i+=1)%4>1?reverse(w):w:error("Sentence must only use letters")for w=split(s)]," "))

```

`i=0` and `(i+=1)%4>1` are used to decide whether each word gets `reverse`d or not. `isalpha` applies to the words after being split using `split(s)` to determine whether or not there are characters that aren't letters (spaces have already been removed by this point). `join` restores the string after the manipulation, unless the `error` is thrown.

# Answer
> 0 votes
# Pyth, 55 bytes

```
?--rz0Gd"Sentence must only use letters"jd.e_W%%k4 3bcz

```

Borrowed the `%%k4 3` bit from Pietu1998. Saved one additional byte.

Try it online: Demonstration or Test Suite

### Explanation

```
?--rz0Gd"..."jd.e_W%%k4 3bcz   implicit: z = input string
   rz0                         convert z to lower-case
  -   G                        remove all letters
 -     d                       remove all spaces
?                              if there is some chars left than
        "..."                    print the string "Sentence must only ..."
                               else:
                          cz     split z by spaces or multiple spaces
               .e                map each pair (k index, b string) of ^ to:
                 _       b          b or reversed of b, depending on
                  W%%k4 3           (k mod 4) mod 3
             jd                  join the result by spaces

```

# Answer
> 0 votes
# Japt v2.0a0 `-S`, 41 bytes

```
¸¬è\L ?`SÀZn Û § «e Ò5s`:UeS²S ¸ËzEc2

```

Try it

```
¸¬è\L ?`...`:UeS²S ¸ËzEc2     :Implicit input of string U
¸                             :Split on spaces
 ¬                            :Join
  è                           :Count occurrences of
   \L                         :RegEx /[^A-Z]/gi
      ?`...`:                 :If truthy return the compressed string "Sentence must only use letters", else
             Ue               :Recursively replace in U
               S²S            :  Two spaces with one
                   ¸          :Split on spaces
                    Ë         :Map each element at 0-based index E
                     z        :  Rotate clockwise by 90 degrees multiplied by
                      Ec2     :    E rounded up to the nearest multiple of 2
                              :Implicit output, joined with spaces

```

# Answer
> 0 votes
# Perl 5 `-ap`, 80 bytes

```
map$_=++$i%4>1?reverse:$_,@F;$_=/[^a-z ]/i?"Sentence must use only letters":"@F"

```

Try it online!

# Answer
> 0 votes
# Jelly, 39 bytes

```
³Ḳ¹ƇUJ2&TƲ¦K
“*[,ṛDṾȧƤ°Ġṛ©¦»
ØẠ” ṭ³eƇ⁼£

```

Try it online!

Thanks to Erik the Outgolfer. He saved me from a few extra bytes and from many hours of frustration.

### Here's a 46 byte solution

It actually throws a python syntax error when the input contains invalid characters.

```
³Ḳ¹ƇUJ2&TƲ¦K
“çỤḷṁŀDṀẠṠGmḟĖƲƑ⁽Ḳḟ»ŒV
ØẠ” ṭ³eƇ⁼£

```

Try it online!

# Answer
> 0 votes
# Java, 215 bytes

Regex is fun

```
s->{if(s.split("[^a-zA-Z ]").length>1)throw new Error("Sentence must only contains letters");else{int i=1;for(String a:s.split(" "))System.out.print((i++%2<1?new StringBuffer(a).reverse():a)+(a.isEmpty()?"":" "));}}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 36 bytes

```
ðKDáÊi“¸–ƒ—€É€Å™ê“.ªFë#áεN4%>2÷iR]ðý

```

Try it online.

Throws the following error when the input does not only contain `[A-Za-z ]`:

> (RuntimeError) Could not convert Sentence must only use letters to integer.

**Explanation:**

```
ðK                   # Remove all spaces from the (implicit) input-string
  Dá                 # Create a copy, and remove everything except for letters from this copy
    Êi               # If the copy with letters removed and the original are NOT equal:
      “¸–ƒ—€É€Å™ê“   #  Push dictionary string "sentence must only use letters"
                  .ª #  With sentence capitalization
      F              #  And try to loop that many times, causing the error above
     ë               # Else:
      #              #  Split the (implicit) input-string on spaces
       á             #  Only keep letters (which will remove empty items caused by multiple
                     #  adjacent spaces in the input, which is shorter than `õK`)
        ε            #  Map each word to:
         N4%>2÷      #   Calculate ((index modulo-4) + 1) integer-divided by 2
                     #   (results in 0,1,1,2,0,1,1,2,0,1 for indices 0,1,2,3,4,5,6,7,8,9)
               i     #   If this is exactly 1:
                R    #    Reverse the current word
     ]               # Close the if-statement, map, and if-else statement
      ðý             # Join the modified word-list by spaces
                     # (and then output it implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“¸–ƒ—€É€Å™ê“` is `"sentence must only use letters"`.

# Answer
> 0 votes
# PHP, 147 bytes

```
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))throw new Exception('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;

```

Try it online!

Or if `die()` is acceptable as an "Exception":

# PHP, 131 bytes

```
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))die('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;

```

Try it online!

---
Tags: code-golf, string, word, permutations
---


title: New Neighbour Sequence

text:
# Question
Title: New Neighbour Sequence
The non-negative integers are bored of always having the same two\* neighbours, so they decide to mix things up a little. However, they are also lazy and want to stay as close as possible to their original position.

They come up with the following algorithm:

* The first element is 0.
* The \\$n^{th}\\$ element is the smallest number which is not yet present in the sequence and which is not a neighbour of the \\$(n-1)^{th}\\$ element.

This generates the following infinite sequence:

```
0,2,4,1,3,5,7,9,6,8,10,12,14,11,13,15,17,19,16,18,20,22,24,21,23,25,27,29,26,28 ...

```

`0` is the first element. `1` is the smallest number not yet in the sequence, but it is a neighbour of `0`. The next smallest number is `2`, so it is the second element of the sequence. Now the remaining numbers are `1,3,4,5,6,...`, but as both `1` and `3` are neighbours of `2`, `4` is the third member of the sequence. As `1` is not a neighbour of `4`, it can finally take its place as fourth element.

### The Task

Write a function or program in as few bytes as possible which generates the above sequence.

You may

* output the sequence infinitely,
* take an input \\$n\\$ and return the \\$n^{th}\\$ element of the sequence, or
* take an input \\$n\\$ and return the first \\$n\\$ elements of the sequence.

Both zero- or one-indexing is fine in case you choose one of the two latter options.

You don't need to follow the algorithm given above, any method which produces the same sequence is fine.

---

Inspired by Code golf the best permutation. Turns out this is A277618.
* Zero has literally only one neighbour and doesn't really care.

# Answer
# JavaScript (ES6), 13 bytes

Returns the \\$n\\$th term of the sequence.

```
n=>n-2-~++n%5

```

Try it online!

### How?

This computes:

$$n-2+((n+2) \bmod 5)$$

```
           n |  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 ...
-------------+--------------------------------------------------
       n - 2 | -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 ...
 (n+2) mod 5 |  2  3  4  0  1  2  3  4  0  1  2  3  4  0  1 ...
-------------+--------------------------------------------------
         sum |  0  2  4  1  3  5  7  9  6  8 10 12 14 11 13 ...

```
> 19 votes

# Answer
# Python 2, 20 bytes

```
lambda n:2*n%5+n/5*5

```

Try it online!
> 8 votes

# Answer
# MathGolf, 5 bytes

```
⌠5%+⌡

```

Try it online!

Some nice symmetry here. Returns the `nth` element of the sequence.

### Explanation:

```
⌠      Increment input by 2
 5%    Modulo by 5
   +   Add to copy of input
    ⌡  Decrement by 2

```
> 8 votes

# Answer
# Jelly, 5 bytes

```
æ%2.+

```

Try it online!

Go go gadget obscure built-in!

```
æ%2.      Symmetric modulo 5: map [0,1,2,3,4,5,6,7,8,9] to [0,1,2,-2,-1,0,1,2,-2,-1]
    +     Add to input

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 14 bytes

```
#+Mod[#,5,-2]&

```

Try it online!

Prints the n-th, zero-indexed, integer in the sequence.
> 4 votes

# Answer
# , ~~25~~ ~~23~~ 21 bytes

-2 bytes thanks to Jo King

```
n=scan();n-2+(n+2)%%5

```

Try it online!

Outputs `nth` element in sequence.
> 4 votes

# Answer
# dzaima/APL, 9 bytes

```
2-⍨⊢+5|2+

```

Port of Arnauld's answer.

Try it online!
> 3 votes

# Answer
# Pip, 14 bytes

```
02413@a+a//5*5

```

Takes \\$n\\$ (0-based) as a command-line argument and outputs \\$a\_n\\$. Try it online!

Observe that \\$a\_{n+5} = a\_n+5\\$. We hard-code the first five values and offset from there.

---

Or, the formula everyone's using, for **12 bytes**:

```
a-2+(a+2)%5

```
> 3 votes

# Answer
# Common Lisp, 67 bytes

```
(defun x(n)(loop for a from 0 to n collect(+(mod(+ a 2)5)(- a 2))))

```

Try it online!
> 2 votes

# Answer
# Japt, 8 bytes

```
U-2Ò°U%5

```

Japt Interpreter

A straight port of Arnauld's Javascript answer. The linked version runs through the first n elements, but if the `-m` flag is removed it is still valid and prints the nth element instead.

For comparison's sake, here is the naive version which implements the algorithm provided in the question:

```
@_aX É«NøZ}a}gNhT

```

I'll give an explanation for this one:

```
              NhT    Set N to [0]
@           }g       Get the nth element of N by filling each index with:
 _        }a          The first integer that satisfies:
  aX É                 It is not a neighbor to the previous element
      «NøZ             And it is not already in N

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
Ì5%+Í

```

Port of @JoKing's MathGolf answer.

Try it online or verify the first 100 numbers.

**Explanation:**

```
Ì        # Increase the (implicit) input by 2
 5%      # Take modulo-5
   +     # Add the (implicit) input to it
    Í    # Decrease by 2 (and output implicitly)

```
> 2 votes

# Answer
# Clean, 31 bytes

The formula everyone's using.

```
import StdEnv
?n=n-2+(n+2)rem 5

```

Try it online!

# Clean, 80 bytes

My initial approach, returning the first `n` items.

```
import StdEnv
$n=iter n(\l=l++[hd[i\\i<-[0..]|all((<>)i)l&&abs(i-last l)>1]])[0]

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 14 bytes

```
n->2*n%5+n\5*5

```

Try it online!

---

# Pari/GP, 14 bytes

```
n->n-2+(n+2)%5

```

Try it online!
> 2 votes

# Answer
# , 30 bytes

```
{.2}.[:,_5,./\2(i.-4 0$~])@,~]

```

Try it online!

Returns a list of first `n` numbers

This solution is obviously non-competitve, but I wanted to try an array-based method.

## Explanation:

The argument is `n`

`2 ,]` \- append 2 to the input

```
   (2,~]) 10
10 2

```

`()@` \- and use this list to:

`i.` \- create a matrix `n` x 2 with the numbers in the range 0..2n-1:

```
   i.10 2
 0  1
 2  3
 4  5
 6  7
 8  9
10 11
12 13
14 15
16 17
18 19

```

`4 0$~]` \- `~` reverses the arguments, so it is \]$4 0 - creates matrix `n` x 2 repeating 4 0

```
   4 0$~10 2
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0

```

`-` subtract the second matrix from the first one, so that the first column is "delayed" with 2 positions

```
   2(i.-4 0$~])@,~] 10
_4  1
_2  3
 0  5
 2  7
 4  9
 6 11
 8 13
10 15
12 17
14 19

```

`_5,./\` traverse the matrix in non-overlapping groups of 5 rows and stitch the columns

```
   _5,./\2(i.-4 0$~])@,~] 10
_4 _2  0  2  4
 1  3  5  7  9

 6  8 10 12 14
11 13 15 17 19

```

`[:,` ravel the entire array

```
   ,_5,./\2(i.-4 0$~])@,~] 10
_4 _2 0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19

```

`2}.` \- drop the first 2 numbers

```
   2}.,_5,./\2(i.-4 0$~])@,~] 10
0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19

```

`{.` take the first `n` numbers

```
   ({.2}.[:,_5,./\2(i.-4 0$~])@,~]) 10
0 2 4 1 3 5 7 9 6 8

```

# , 9 bytes

```
+_2+5|2+]

```

Try it online!

Returns the `n`th element.

Port of Arnauld's answer
> 2 votes

# Answer
# K (ngn/k), 12 bytes

```
{-2+x+5!x+2}

```

Try it online!
> 2 votes

# Answer
# Pepe, 65 bytes

```
REeeeeeeEerEeERRrEEEEEERREeeeeeEeErEEeEeErRrEEEEEEEErRrEEEEEereEE

```

Try it online!

Port of Jo King's answer.
> 2 votes

# Answer
# x86 machine code, 16 bytes

```
00000000: 31d2 89c8 4949 4040 b305 f7f3 9201 c8c3 1...II@@........

```

Assembly:

```
section .text
	global func
func:	;function uses fastcall conventions, 1st arg in ecx, returns in eax
	;reset edx to 0 so division works
	xor edx, edx

	mov eax, ecx
	;calculate ecx (1st func arg) - 2
	dec ecx
	dec ecx

	;calculate (ecx+2) mod 5
	inc eax
	inc eax
	mov bl, 5
	div ebx
	xchg eax, edx

	;add (ecx-2) and ((ecx+2) mod 5), returning in eax
	add eax, ecx
	ret

```

Try it online!
> 1 votes

# Answer
# Red, 26 bytes

```
func[n][n + 2 % 5 + n - 2]

```

Try it online!

Port of Arnauld's answer
> 1 votes

# Answer
# Excel, 17 bytes

```
=A1-2+MOD(A1+2,5)

```

Nothing smart. Implements the common formula.
> 1 votes

# Answer
# C (gcc) POSIX, 20 bytes

```
f(n){n=n-2+(n+2)%5;}

```

Try it online!
> 1 votes

# Answer
# QBasic, 30 bytes

```
INPUT x
x=x+2
?-4+x*2-(x\5)*5

```

Gives the 0-indexed entry of the list at pos `x`.

Try it online! (Note that `?` was expanded to `PRINT` because the interpreter fails otherwise...)
> 1 votes

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

```
n=>2*n%5+n/5*5

```

Try it online!

Same logic than others answers:
> 1 votes

# Answer
# TI-BASIC, 11 bytes

```
Ans-2+remainder(Ans+2,5

```

Input is in `Ans`.
Outputs \\$a(n)\\$.

A simple port of the other answers.

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
> 1 votes

# Answer
# , 25 bytes

```
n=1:scan()-1;n-2+(n+2)%%5

```

Try it online!

Port of Robert S.'s answer (and only by adding just 4 bytes) thanks to R being excellent at handling vectors.

Outputs the first n values.
> 1 votes

# Answer
# dc, 9 bytes

```
d2+5%+2-p

```

Try it online!

Same method as most. Duplicate top-of-stack, add 2, mod 5, add to original (duplicated earlier), subtract 2, print.
> 1 votes

---
Tags: code-golf, sequence, integer
---