The cyclic sequence of even digits, with odds in between

Consider the following sequence:

1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 0, 1, ...

The even digits start from 0 and are grouped into runs of increasing length. They are arranged cyclically, meaning that they are sorted in ascending order until 8 is reached, and then cycled back from 0. 1 separates the runs of even digits, and it also starts the sequence. Let's visualize how this sequence is formed:

1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1,  ...

-     ----     -------     ----------     -------------
run length:         1      2          3            4                5            ...
position of 1:   X     X        X           X              X                 X   ...
even sequence:      0,    2, 4,    6, 8, 0,    2, 4, 6, 8,    0, 2, 4, 6, 8      ...

Acceptable Input and Output methods:

• Receive an integer N as input and output the Nth term of this sequence.

• Receive an integer N as input and output the first N terms of this sequence.

• Print the sequence indefinitely.

You can choose either 0 or 1-indexing for the first two methods.

You can compete in any programming language, while using the standard input and output methods. Standard loopholes are forbidden. This is , so the shortest code in each language wins.

• This challenge has been sandboxed. – Mr. Xcoder Nov 10 '17 at 13:50

1#cycle[0,2..8]
n#r=1:take n r++(n+1)#drop n r

Try it online!

1#cycle[0,2..8] returns the sequence as infinite list.

-4 bytes thanks to Ørjan Johansen!

• You can save four bytes by making the first argument of # just a number. Try it online! – Ørjan Johansen Nov 11 '17 at 0:36

Jelly, 10 bytes

5ḶḤṁR€1pFḣ

Returns the first n items of the sequence.

Try it online!

How it works

5ḶḤṁR€1pFḣ  Main libk. Argument: n

5           Set the return value to 5.
Ḷ          Unlength; yield [0, 1, 2, 3, 4].
Ḥ         Unhalve; yield [0, 2, 4, 6, 8].
R€      Range each; yield [[1], [1, 2], [1, 2, 3], ..., [1, ..., n]].
ṁ        Mold; in the result to the left, replace [1] with [0], [1, 2] with
[2, 4], [1, 2, 3] with [6, 8, 0], and so forth.
1p    Take the Cartesian product of [1] and the result.
F   Flatten the result.
ḣ  Head; take the first n items of the result.
• ಠ_ಠ Unhalve... Isn't that just Double? – Mr. Xcoder Nov 10 '17 at 14:21
• It's just a mnemonic. H is halve, so is unhalve. ÆA is arccosine, so ÆẠ is unarccosine. – Dennis Nov 10 '17 at 14:25

Husk, 1211 10 bytes

ṁ:1CN¢mDŀ5

Try it online!

Prints the sequence indefinitely.

Alternatively:

J1CΘN¢mDŀ5

Try it online!

Explanation

ŀ5   Start from [0, 1, 2, 3, 4]
mD     Double each value to get [0, 2, 4, 6, 8]
¢       Repeat this list indefinitely, [0, 2, 4, 6, 8, 0, 2, ...]
CN        Cut it into chunks of increasing lengths,
[[0], [2, 4], [6, 8, 0], ...]
ṁ:1          Prepend 1 to each sublist and concate the resulting lists.

For the alternative solution:

¢mDŀ5   Again, get [0, 2, 4, 6, 8, 0, 2, ...].
CΘN        This time we prepend a zero to the natural numbers, which
prepends an empty list to the resulting chunks.
J1           Join all the sublists with 1.

We could also do ...ΘCN..., because Θ does "prepend default element", which prepends a zero for lists of integers and an empty list for lists of lists.

Python 3, 52 bytes

def f(n):t=(8*n+1)**.5+1;return 0==t%1or(n-t//2)%5*2

Takes a 1-based index and returns True or an integral float.

Try it online!

Python 2, 51 bytes

k=n=0
while 1:print 1;k+=1;exec'print n%10;n+=2;'*k

Prints the whole sequence.

Try it online!

APL, 25 bytes

Returns nth term.

1,(⌽n↑⌽(+/⍳n←⎕)⍴0,2×⍳4),1

Explanation

n←⎕     Prompts for screen input of integer
+/⍳      Creates a vector of integers of 1 to n and sums
⍴0,2×⍳4  Creates a vector by replicating 0 2 4 6 8 to the length of sum
⌽n↑⌽   Rotates the vector, selects first n elements and rotates result
(selects last n elements}
1,...,1 Concatenates 1s in front and behind result

APL (Dyalog Unicode), 5259 56 bytes

r←c k
r←~n←0
:For j :In ⍳k
n+←j-1
r,←1,⍨j⍴n⌽0,2×⍳4
:End
r←k⍴r

Try it online!

This is a tradfn (traditional function) taking one argument k and returning the first k items of the sequence.

Thanks to @GalenIvanov for pointing out an error in the function. Thanks to @Adám for 3 bytes.

How it works:

r←c k             ⍝ The function c takes the argument k and results in r
r n←1 0           ⍝ Initializing the variables r and n, and setting them to 1 and 0, respectively.
:For j :In ⍳k     ⍝ For loop. ⍳k yields [1, 2, 3, ..., k], and j is the control variable.
n+←j-1            ⍝ Accumulates j-1 into n, so it follows the progression (0, 1, 3, 6, 10, 15...)
r,←1,⍨j⍴n⌽0,2×⍳4  ⍝ This line is explained below.
:End              ⍝ Ends the loop
r←k⍴r             ⍝ return the first k items of r.
⍝ ⍴ actually reshapes the vector r to the shape of k;
⍝ since k is a scalar, ⍴ reshapes r to a vector with k items.
2×⍳4  ⍝ APL is 1-indexed by default, so this yields the vector 2 4 6 8
0,      ⍝ Prepend a 0 to it. We now have 0 2 4 6 8
n⌽        ⍝ Rotate the vector n times to the left.
j⍴          ⍝ Reshape it to have j items, which cycles the vector.
1,⍨            ⍝ Append a 1, then
r,←               ⍝ Append everything to r.

Below are a Dfn(direct function) and a tacit function that also solve the challenge, both kindly provided by @Adám.

• Dfn: {⍵⍴1,∊1,⍨¨j⍴¨(+\¯1+j←⍳⍵)⌽¨⊂0,2×⍳4} Try it online!
• Tacit: ⊢⍴1,∘∊1,⍨¨⍳⍴¨(⊂0,2×⍳4)⌽⍨¨(+\¯1+⍳) Try it online!
• I'm interested in the explanation of the tacit vesrion. Thanks! – Galen Ivanov Nov 10 '17 at 20:23
• @GalenIvanov I'll add one later today. – J. Sallé Nov 10 '17 at 20:53
• I noticed that the 3 functions yield incorrect answers - the subsequences always start from 0 after 1 - they should continue from the last even digit of the previous subsequence. – Galen Ivanov Nov 13 '17 at 7:14
• @GalenIvanov You're right. I'll see if I can fix it and add the explanations today. – J. Sallé Nov 13 '17 at 12:13

JavaScript (ES6), 6254 52 bytes

Returns the Nth term of the sequence, 0-indexed.

n=>(g=e=>n--?g(e+=k++<l?2:k=!++l):k<l?e%10:1)(k=l=0)

Demo

let f =

n=>(g=e=>n--?g(e+=k++<l?2:k=!++l):k<l?e%10:1)(k=l=0)

for(n = 0; n < 30; n++) {
console.log('a(' + n + ') = ' + f(n))
}

C (gcc), 84 bytes

i;j;f(){for(i=1;;i++){printf("%d ",1);for(j=0;j<i;)printf("%d ",(2*j+++i*i-i)%10);}}

Try it online!

A function (f()) that prints the sequence infinitely, separated by spaces.

i is the length of the current even-run.

j is the index in the current even-run

(2*j+++i*i-i)%10 gives the correct even number, given i and j (and increments j), equivalent to ((j+Tr(i))%5)*2, where Tr(x) is the xth triangular number (which is the number of even numbers that have been printed before the current even run;

Java 8, 96 bytes

v->{for(int i=0,j=-2,k;;i++,System.out.println(1))for(k=0;k++<i;System.out.println(j%=10))j+=2;}

Prints indefinitely, each number on a new line.

Explanation:

Try it here.

v->{                               // Method with empty unused parameter and no return-type
for(int i=0,                     //  Index integer, starting at 1
j=-2,                    //  Even index integer, starting at -2
k;                       //  Inner index integer
;                            //  Loop (1) indefinitely
//    After every iteration:
i++,                        //     Increase index i by 1
System.out.println(1))      //     And print a 1
for(k=0;                       //   Reset index k to 0
k++<i;                     //   Inner loop (2) from 0 to i
//     After every iteration:
System.out.println(j%=10))  //      Set j to j modulo-10, and print it
j+=2;                        //    Increase j by 2
//   End of inner loop (2) (implicit / single-line body)
//  End of loop (1) (implicit / single-line body)
}                                  // End of method

Batch, 85 bytes

@set/an=%2+1,t=n*-~n/2
@if %t% lss %1 %0 %1 %n%
@cmd/cset/a(%1-n)%%5*2*!!(t-=%1)+!t

Outputs the Nth term of the sequence. Works by calculating the next triangular number.

Perl 5, 44 bytes

do{say 1;map{say(($r+=2)%10)}0..$i++}while 1

Try it online!

Infinite output

• -4 bytes {...;redo} instead of do{...}while 1 – Nahuel Fouilleul Nov 13 '17 at 10:39

J, 4642 40 bytes

-6 bytes thanks to cole

{.({.[:;[:#:&.>2^i.);@(1,&.><;.1)10|2*i.

Outputs the first N terms of this sequence.

How it works:

10|[:+:i. - generates a list of length N of 0 2 4 6 8 0 2 4... It simply takes mod 10 of the doubled items of a list of integers starting at 0.

[:;[:#:&.>2^i. - generates a bit mask for cutting the above list.

(1 means start): 1 1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 ... It finds 2 to the power of the consecutive non-negative integers, converts them into binary, flattens the list and takes only the first N items, so that the length of the both lists is the same.

;@(1,&.><;.1) - splits (cuts) the list of the even digits into sublistsaccording to the map of ones and zeroes, appends the sublist to 1 and finally flattens the resulting list

]{. - takes only the first N items, getting rid of the additional numbers in the list due to the added 1s.

Try it online!

• 42 bytes: {.({.[:;[:#:&.>2^i.);@(1,&.><;.1)(10|2*i.). The changes I did were to use hooks and refactor the right tine of the fork to take advantage of how forks work. I like the 2^i. trick. I'm trying to work on the left tine of the fork now. – cole Nov 11 '17 at 2:15
• @cole Thanks, I need to learn to use forks better. Apparently the fork 2*i. is better then than the capped hook [:+:i. – Galen Ivanov Nov 11 '17 at 8:32
• You can also drop the parens on the right tine (10|2*i.) ->10|2*i. – cole Nov 11 '17 at 17:04

Common Lisp, 74 bytes

(do((b 1(1+ b))(k -2))(())(print 1)(dotimes(m b)(print(mod(incf k 2)10))))

Try it online!

Prints the sequence indefinitely.

Perl 5, 35 bytes

{say$i--?$r++%5*2:($i=++$j)>0;redo}

try it online

Jelly, 17 bytes

9Ḷm2ẋ⁸ṁJRj1 1;ḣ

Try it online!

Proton, 55 bytes

i=0 j=-2while1{for k:0..i print(j=(j+2)%10)print(1)i++}

Try it online!

Prints the sequence indefinitely

• ಠ_ಠ What is that, new syntax? :p i=0 j=-2while1{... – Mr. Xcoder Nov 10 '17 at 14:15
• @Mr.Xcoder :P -2while is just like Python and while1 is because I made identifiers not able to be a keyword followed by a number – HyperNeutrino Nov 10 '17 at 14:21

Java (OpenJDK 8), 107 bytes

i->{String b="";for(int l=i,r=0,z=0;i>0;b+=l-i--==r?(l=i)<1+r++*0?"1":"1":"02468".charAt(z++%5));return b;}

Try it online!

Mathematica, 68 bytes

Returns the Nth term

Insert[Join@@Table[{0,2,4,6,8},#^2],1,Array[{(2-#+#^2)/2}&,#]][[#]]&

Try it online!

Wolfram Language (Mathematica), 61 bytes

Flatten[TakeList[2Mod[r=0~Range~#,5],UpTo/@r]~Riffle~1][[#]]&

Try it online!

JavaScript, 45 bytes

1 indexed:

f=(x,t=0,p=0)=>p<x?f(x-1,t+1,p+t):x-p?x%5*2:1

0 indexed:

g=(x,p=0)=>p<x?g(x-1,p?++t+p:t=1):x-p?x%5*2:1

f=(x,t=0,p=0)=>p<x?f(x-1,t+1,p+t):x-p?x%5*2:1

g=(x,p=0)=>p<x?g(x-1,p?++t+p:t=1):x-p?x%5*2:1

a.value=[...Array(100)].map((_,i)=>f(i+1))
b.value=[...Array(100)].map((_,i)=>g(i))
<output id=a></output>
<output id=b></output>

Ruby, 48 46 bytes

a=b=c=0;loop{a>b&&(p 2*b%10;b+=1)||a+=c+=p(1)}

Try it online!

Print the sequence indefinitely

bash, 42 bytes

for((;;)){ echo $[i--?r++%5*2:(i=++j)>0];} or 34 if valid echo$[i--?r++%5*2:(i=++j)>0];. \$0

try it online