Skip to main content
4 of 4
deleted 105 characters in body
J. Sallé
  • 3.5k
  • 10
  • 24

APL (Dyalog Unicode), 52 59 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!
J. Sallé
  • 3.5k
  • 10
  • 24