15
\$\begingroup\$

Inspiring myself on a recent challenge, we ought to compute a sequence that is very close to A160242.

Task

Your task is to generate the sequence \$ \{s_i\}_{i=0}^\infty \$:

1, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, ...

Which is more easily understandable in this format:

      1 2 1
    1 2 2 2 1
  1 2 2 2 2 2 1
1 2 2 2 2 2 2 2 1 ...

Another way to think of it is, this sequence is the concatenation of blocks \$b_i, 0 \leq i\$ where block \$b_i\$ is a 1, followed by \$2i + 1\$ 2s, followed by another 1.

Input

If your program takes input, the input is a non-negative integer n, telling you how far you should go in computing the sequence.

The sequence can

  • be 0-indexed, so that \$s_0 = 1, s_1 = 2, s_2 = 1, ... \$
  • be 1-indexed, so that \$s_1 = 1, s_2 = 2, s_3 = 1, ... \$

Output

Your code may do one of the following:

  • indefinitely print the sequence
  • print/return the term n as given by the input
  • print/return all the terms up to the term n as given by the input

Test cases

(the test cases are 0-indexed)

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

This is so the shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

\$\endgroup\$
  • \$\begingroup\$ If I do my answer in 1-index, can I treat the test cases as 1-indexed as well? \$\endgroup\$ – Jeff Zeitlin Mar 13 at 17:14
  • \$\begingroup\$ @JeffZeitlin of course! \$\endgroup\$ – RGS Mar 13 at 17:15
  • \$\begingroup\$ You should leave the IO formats as the default rather than override them. If you meant to re-iterate the defaults, then you left a couple out (like a few of the options for functions) \$\endgroup\$ – Jo King Mar 14 at 1:51
  • \$\begingroup\$ @JoKing I was pretty confident I had seen a fair share of sequence challenges where the 3 standard outputs were these. What did I leave out? \$\endgroup\$ – RGS Mar 14 at 6:33
  • 1
    \$\begingroup\$ I may be taking indefinitely print the sequence too literally, but the tag wiki for sequence allows returns an infinite lazy iterator/generator \$\endgroup\$ – Jo King Mar 14 at 10:51

25 Answers 25

9
\$\begingroup\$

JavaScript (ES7),  25 24  23 bytes

Returns the \$n\$-th term, 1-indexed.

n=>n>(++n**.5|0)**2?2:1

Try it online!

How?

We have \$a(n)=2\$ iff the difference between \$n+1\$ and the previous square is greater than \$1\$:

$$n+1-\left\lfloor \sqrt{n+1}\right\rfloor^2>1$$

which boils down to:

$$n>\left\lfloor \sqrt{n+1}\right\rfloor^2$$

|improve this answer|||||
\$\endgroup\$
6
\$\begingroup\$

Jelly, 6 bytes

,‘ƲE‘

Try it online!

Explanation

,‘ƲE‘  Main Link:                  N
,       pair with
 ‘                increment         [N, N + 1]
  Ʋ    is it a square?             [issq(N), issq(N + 1)]
    E   are both equal (N and N+1 cannot both be square, so if one is square, it will return 0, and if both are not square, it will return 1)
     ‘  increment (if N or N+1 is square, return 1; otherwise, return 2)
        (implicit input)
|improve this answer|||||
\$\endgroup\$
  • 1
    \$\begingroup\$ 1 indexing is fine, Ty for your comment. \$\endgroup\$ – RGS Mar 13 at 16:07
6
\$\begingroup\$

Python 3.8 (pre-release), 31 bytes

i=0
while i:=100*i+121:print(i)

Try it online!

Print the sequence infinitely, with a questionable format.


The following version output the first n terms of the sequence:

Python 3, 56 bytes

lambda n:"".join(f"{1:2<{-~i*2}}1"for i in range(n))[:n]

Try it online!

Input: Non-negative integer n

Output: the first n terms of the sequence, concatenated into a string.

Explanation

A different approach using only string formatting instead of @Arnauld's closed-form formula.

  • f"{1:2<{x}}1" evaluates to "122..21" with x-1 characters "2". (The first "1" is left justified to a block of width x, with "2" being the fill character).
  • -~i*2 is equivalent to (i+1)*2

Thus f"{1:2<{-~i*2}}1" evaluates to the string "122..21" with i*2+1 characters "2".

|improve this answer|||||
\$\endgroup\$
  • 2
    \$\begingroup\$ I like your 31 byter a lot! Really clever way of building the sequence. \$\endgroup\$ – RGS Mar 13 at 19:27
  • \$\begingroup\$ You can get rid of the questionable format by adding ,end=''. \$\endgroup\$ – L. F. Mar 16 at 7:32
  • \$\begingroup\$ @L.F. yeah... but that will takes more bytes on something not absolutely necessary. I'd prefer keeping the format as it is if it saves some characters. \$\endgroup\$ – Surculose Sputum Mar 16 at 8:44
4
\$\begingroup\$

R, 27 25 bytes

-1 byte thanks to Giuseppe

1+all((scan()+1:2)^.5%%1)

Try it online!

Uses the fact that \$s_n=1\$ iff \$n+1\$ or \$n+2\$ is a perfect square.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ 26 bytes? \$\endgroup\$ – Giuseppe Mar 13 at 15:57
  • \$\begingroup\$ @Giuseppe Thanks! I found an extra byte to golf, down to 25. \$\endgroup\$ – Robin Ryder Mar 13 at 16:15
4
\$\begingroup\$

Symja, 38 33 bytes

f(x_):=If(Mod(-(x^.5),1)*x<1,1,2)

Y'all can try it here

This is just a port of xnor's (who helped me save 5 bytes) Python 2 answer in Symja. This took a while to generate, as I had to properly understand what the formula was, due to operator precedence. Anyhow, enjoy!

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I dunno Symja, but I'd guess you could replace the 2- by putting the resulting values in as the outcomes of the If. Also, it doesn't lok like you need parens after the *x. \$\endgroup\$ – xnor Mar 14 at 6:36
  • \$\begingroup\$ @xnor You're right. The brackets must have been from failed attempts at porting. Thanks! \$\endgroup\$ – Lyxal Mar 14 at 6:38
3
\$\begingroup\$

Python 2: 52 bytes

def g(n):return(2,1)[not((n+1)**.5%1and(n+2)**.5%1)]

Try it online!

Returns the nth term in the sequence. Also using the fact that the nth term = 1 <=> (n+1) or (n+2) is square as Robin Ryder pointed out.

|improve this answer|||||
\$\endgroup\$
  • 1
    \$\begingroup\$ You can use lambda to get rid of return statement, and 2-i instead of (2,1)[i]. 43 bytes \$\endgroup\$ – Surculose Sputum Mar 13 at 17:39
3
\$\begingroup\$

PowerShell, 23 bytes

for(){$i++;1;,2*$i++;1}

Try it online!

Prints the sequence indefinitely.

|improve this answer|||||
\$\endgroup\$
3
\$\begingroup\$

APL (Dyalog Unicode), 67 bytes

This answer returns the entire sequence up to the requested value.

f←{(⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵)[⍳⍵]}

Try it online!

Decomposition/Explanation:

f←                                     ⍝ assign the name f to
  {                                  } ⍝ a dfn that takes a single argument
                              ⍟⍵       ⍝ The natural logarithm of the argument,
                             ⌈         ⍝ rounded up to the next integer,
                           1+          ⍝ and add 1 (giving N), then
                          ⍳            ⍝ generate the sequence 1..N,
                       1-⍨             ⍝ and subtract 1 from each term (0..N-1)...
                                       ⍝    ⍨ means to swap the arguments to
                                       ⍝    - (the standard subtraction function), so
                                       ⍝    1-⍨N is the same as N-1.
                     2×                ⍝ ... then multiply each term in the sequence by 2,
                   1+                  ⍝ and add 1
                  ¨                    ⍝ then take each term in the sequence, and
               2⍴⍨                     ⍝ generate a vector of that many 2s
                                       ⍝    ⍨ means to swap the arguments to
                                       ⍝    ⍴ the "shape" function. For simple numeric
                                       ⍝    values of A and B, A⍴B means to generate a 
                                       ⍝    vector of A repeats of B.
                                       ⍝ We now have a vector of vectors of 2s.
              ¨                        ⍝ For each of those vectors,
            1,                         ⍝ prepend a 1, then
           ¨                           ⍝ for each vector, 
          ⌽                            ⍝ reverse it (so that the 1 is on the 'back end'), then
       1,¨                             ⍝ for each (now reversed with a 1) vector, prepend a 1, and
     ,/                                ⍝ concatenate all the vectors. For reasons I don't quite
                                       ⍝    understand, this generates an enclosed object, so
    ⊃                                  ⍝ unenclose (disclose) it into a 'real' vector, and
   (                            )      ⍝ treat all that as an object...
                                 [  ]  ⍝ ...which can be subscripted. If the subscript is
                                       ⍝    a single integer, it will return just that item from
                                       ⍝    the array; if it's a vector, it will return all of the
                                       ⍝    requested values, in the order specified by the vector.
                                  ⍳⍵   ⍝ This subscript is a vector, of the integers 1 to the original
                                       ⍝    argument to the function, so it will generate the entire
                                       ⍝    sequence up to the ⍵th term. If I only wanted the single
                                       ⍝    term, I would omit the ⍳, which would give me only the ⍵th term.

FIRST GOLFING (courtesy ngn):

APL (Dyalog Unicode), 65 bytes

f←{⍵↑(⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵)}

Try it online!

Explanation of golfing:

[⍳⍵] is the same as [1 2 3 4 5 6 ... ⍵], 
      which is the first ⍵ items of the vector being subscripted.
      That's the same as 
⍵↑    "Take" the first ⍵ items.  Savings, 2bytes.

SECOND GOLFING (my own discovery):

APL (Dyalog Unicode), 63 bytes

f←{⍵↑⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵}

Try it online!

Explanation of golfing: The expression that was formerly subscripted does not need to be parenthesized if using ⍵↑ instead of [⍳⍵]. Savings, 2bytes.

|improve this answer|||||
\$\endgroup\$
3
\$\begingroup\$

GolfScript, 16 bytes

Port of Surculose Sputum's Python answer.

0{100*121+.p.}do

Try it online!

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 42 bytes

If[#==1||(d=NumberQ@*Sqrt)@#||d[#+1],1,2]&     

returns 1 if n=1 or n is a perfect square or n+1 is a perfect square

Try it online!

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 6 bytes

>‚ŲË>

Port of @HyperNeutrino's Jelly answer, so make sure to upvote him!

Outputs the result for the 1-based input \$n\$.

Try it online or verify all the first \$n\$ outputs.

Printing the infinite sequence is 9 8 bytes (based on the 6-byter above):

∞ü‚Ų€Ë>

Try it online.

Previous 9 bytes variations for the infinite sequence:

Explanation:

>         # Increase the (implicit) input-integer by 1
 ‚        # Pair it with the (implicit) input-integer: [input, input+1]
  Ų      # Check for both whether they're a square (which will be either both falsey,
          # or just one of the two is truthy)
    Ë     # Check if both are equal (so both falsey) (1 if truhy; 0 if falsey)
     >    # And increase that by 1 (2 if truthy; 1 if falsey)
          # (after which the result is output implicitly)

∞         # Push an infinite positive list: [1,2,3,...]
 ü‚       #  Pair each overlapping pair together: [[1,2],[2,3],[3,4],...]
   Ų     # Check for each whether it's a square
     €Ë   # Check for each pair whether they're equal
       >  # Increase it by 1
          # (after which it is output implicitly as result)              

 ∞        # Push an infinite positive list: [1,2,3,...]
Y и       # Repeat a 2 that many times as list: [[2],[2,2],[2,2,2],...]
    δ     # For each inner list:
   X š    #  Prepend a 1: [[1,2],[1,2,2],[1,2,2,2],...]
      €   # For each inner list:
       û  # Palindromize it: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1],...]
        ˜ # Flatten the list of lists: [1,2,1,1,2,2,2,1,1,2,2,2,2,2,1,...]
          # (after which it is output implicitly as result)

ÅÉ        # Push all odd numbers equal to or less than the given argument,
          # which will be an infinite sequence without argument: [1,3,5,...]
  Å2      # Create for each value a list with that many 2s: [[2],[2,2,2],[2,2,2,2,2],...]
     δ    # For each inner list:
    X .ø  #  Surround it with 1s: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1],...]
        ˜ # Flatten the list of lists: [1,2,1,1,2,2,2,1,1,2,2,2,2,2,1,...]
          # (after which it is output implicitly as result)
|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 56 bytes

i,c;main(){main(i--<-2?i=c+=2:putchar(49+(c+~i&&i+3)));}

-1 byte thanks to RGS!
-8 bytes thanks to ceilingcat!

Try it online!

C (gcc), 46 bytes

i;f(n){for(i=0;n--;)printf("%d",i=i*100+121);}

Stretches the rules and only works up to \$n=4\$.

Try it online!

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 11 bytes

↷²1W¹«2P1D2

Try it online! Link is to verbose version of code. Prints the infinite sequence. Explanation:

↷²

Change the default direction to downwards, so that everything now prints vertically by default.

1

Output 1 to the canvas.

W¹«

Loop forever.

2

Output 2 to the canvas.

P1

Output 1 to the canvas, but don't move the cursor.

Copy the canvas to STDOUT.

2

Replace the 1 with a 2.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

dc, 18 bytes

?d2+vd*rvd*-d/2r-p

Try it online!

This uses 0-based indexing, and it computes the nth value in the sequence for index n. Input is on stdin, and output is on stdout.

It computes $$2 -K_{\neq0}\big(\lfloor{\sqrt{n+2}}\rfloor-\lfloor{\sqrt{n}}\rfloor\big),$$ where \$K_{\neq0}\$ is the function that maps 0 to 0, and any non-zero number to 1. (\$K_{\neq0}\$ isn't built into dc, but you can compute it by dividing a number by itself, as long as you're careful with the stack when its argument is 0.)

There may be spurious output on stderr (due to division by 0).

Here's a TIO link to the test suite.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

W, 7 bytes

The long length doesn't really matter to me. W doesn't have a square-checking built-in.

φßéW!r♀

Uncompressed:

){Q1m!=r)

Explanation

)         % Increment the input. [input + 1]
 {        % Pair with the input. [input, input + 1]
  Q       % Find the square root.[sqrt(input), sqrt(input + 1)]
   1m     % Modulo 1. (Find the digits after the decimal point.)
     !    % Are the digits 0? (True, it's a square number. Otherwise,
          % it can't be a square number.)
      =r  % Reduce by equality.
        ) % Increment the result.
|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Perl 6, 28 27 bytes

{flat (1,2,2 xx$++*2,1)xx*}

Try it online!

Anonymous codeblock returning a lazy infinite list. I wish I could do 2 xx++$++ or some combination of it, but i can't figure it out.

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Python 3, 39 34 bytes

i=1
while 1:print(1,*[2]*i,1);i+=2

Prints the sequence infinitely. Thanks to @SurculoseSputum for saving me 5 bytes.

Try it online!

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I forgot that printing the sequence infinitely is an option... 34 bytes \$\endgroup\$ – Surculose Sputum Mar 13 at 17:06
  • 1
    \$\begingroup\$ 33 bytes by using the print statement as conditional \$\endgroup\$ – Surculose Sputum Mar 13 at 18:21
1
\$\begingroup\$

Brainfuck, 72

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

Might be able to make it shorter but here's my shot. Prints indefinetly

  1. Initialize first two cells with (ASCII values for) 1 and 2
  2. Start a loop (looping on the 2 cell but it doesn't really matter)
    1. Print the 1
    2. Increase the count, and then copy the count to the next two cells
    3. Use one of the counts to print the twos (decreases the count until 0, then exits loop)
    4. Copy the second copy of the count back to where it was before
    5. Print a final 1
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Can you please provide a TIO link? \$\endgroup\$ – RGS Mar 13 at 19:25
  • 2
    \$\begingroup\$ 66 bytes using Brainfuck constants. \$\endgroup\$ – S.S. Anne Mar 14 at 16:15
  • \$\begingroup\$ 42 bytes by just using 1 cell for ASCII 1 \$\endgroup\$ – Akangka Mar 16 at 4:15
1
\$\begingroup\$

C (gcc) -lm, 57 \$\cdots\$ 52 50 bytes

Saved 2 bytes thanks to ceilingcat!!!

t;s(n){t=sqrt(n);n=n!=t*t;};f(n){n=1+s(n)*s(n+1);}

Try it online!

Returns the nth term in the sequence.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ @ceilingcat Nice one - thanks! :-) \$\endgroup\$ – Noodle9 Mar 13 at 23:57
1
\$\begingroup\$

Bash, 64 61 41 bytes

Saved 20 bytes thanks to S.S. Anne!!!

s=2;while :;do echo 1 $s 1;s+=' 2 2';done

Try it online!

Infinitely prints the sequence.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ 41 bytes you don't need the quotes for bash strings without spaces, and some other major fixes \$\endgroup\$ – S.S. Anne Mar 14 at 0:16
  • \$\begingroup\$ maybe 37 \$\endgroup\$ – S.S. Anne Mar 14 at 0:19
  • \$\begingroup\$ @S.S.Anne Yeah, was trying to get at it from the wrong angle (originally printf with string padding) . Nice one - thanks! :-) \$\endgroup\$ – Noodle9 Mar 14 at 0:32
1
\$\begingroup\$

PowerShell, 55 bytes

$i=0;1.."$args"|%{$i+=2;write-host "1,$('2,'*$i)1," -n}

Try it online!

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

C (clang), 80 75 bytes

j,k=1;main(int a,char**b){for(a=atoi(b[1]);j<a;k+=2,j+=k);return(1<j-a)+1;}

Try it online!

This one takes an input N at the terminal and returns the Nth value. This is zero-indexed.

C (gcc), 48 44 bytes

j,k=1;f(a){for(;j<a;k+=2,j+=k);a=(1<j-a)+1;}

Try it online!

Same basic function here, but modified to just be a function to not take the hit from main's arg-list and converting a string to an integer. Switched over to GCC to take advantage of undefined behavior that avoids need for explicit return.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Hey there, welcome to this community! Can you please provide a TIO link with your code? \$\endgroup\$ – RGS Mar 16 at 21:43
  • \$\begingroup\$ @RGS Added TIO. \$\endgroup\$ – Christian Gibbons Mar 16 at 22:13
  • \$\begingroup\$ Thanks, nice first post! \$\endgroup\$ – RGS Mar 16 at 22:29
  • 2
    \$\begingroup\$ Suggest j+=k+=2 instead of k+=2,j+=k \$\endgroup\$ – ceilingcat Mar 17 at 1:06
  • 1
    \$\begingroup\$ 39 bytes by removing j and using 1-based indexing. \$\endgroup\$ – Bubbler Mar 17 at 4:44
0
\$\begingroup\$

APL+WIN, 31 bytes

Prompts for integer. Index origin=1
Returns single term of the series.

2 1[1++/m=1,(n+1),n←+\1+2×⍳m←⎕]

Try it online! Courtesy of Dyalog Classic

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Haskell, 51 Bytes

f n=concat['1':['2'|x<-[0..y*2]]++"1"|y<-[0..n]]!!n

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Not very competitive, but I thought that I would provide a Haskell solution. \$\endgroup\$ – Benji Mar 13 at 20:10
0
\$\begingroup\$

Perl 5, 35 + 1 (-p) = 36 bytes

$_=(map{(1,2,(2,2)x$_,1)}0..$_)[$_]

Try it online!

Reads input n from stdin. Simplisticly builds a list of the first at least n elements (actually the first 2n+3 elements), then prints the nth element.

Perl 5, 30 + 1 (-p) = 31 bytes

$_=$_+1>(($_+2)**0.5|0)**2?2:1

Smarter and more efficient way of doing it with Arnauld's formula from above (but adjusted to be 0-indexed instead of 1-indexed, because that's how I like it).

Try it online!

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.