# Ones and Twos for days

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

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!

• If I do my answer in 1-index, can I treat the test cases as 1-indexed as well? Mar 13, 2020 at 17:14
• @JeffZeitlin of course!
– RGS
Mar 13, 2020 at 17:15
• 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)
– Jo King
Mar 14, 2020 at 1:51
• @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?
– RGS
Mar 14, 2020 at 6:33
• I may be taking indefinitely print the sequence  too literally, but the tag wiki for sequence allows returns an infinite lazy iterator/generator
– Jo King
Mar 14, 2020 at 10:51

# 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$$

# 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)

• 1 indexing is fine, Ty for your comment.
– RGS
Mar 13, 2020 at 16:07

# Python 2, 24 bytes

lambda n:2-(-n%n**.5<.5)


Try it online!

Outputs the $$\n\$$'th value one-indexed.

We use an arithmetic expression to identify indices n that are either perfect square or one below a perfect square. To do so, we use a measure that's roughly of the distance between n and the next perfect square, given by -n%n**.5.

For squares, we have -n%n**.5==0 because n is an even multiple of its square root, that is for n=k*k, -(k*k)%k==0. If n is one less than a perfect square, then the remainder is <0.5, if it's two less, it's be between 0.5 and 1, and so on. So, the condition -n%n**.50.5 accepts only perfect squares and numbers one less.

• This gives the wrong output for n=8, 15, 24,... Mar 17, 2020 at 5:51
• @PoonLevi Thanks, that's embarrassing I missed that.
– xnor
Mar 17, 2020 at 17:45
• Fixed and undeleted
– xnor
Oct 15, 2020 at 19:49

# 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".

• I like your 31 byter a lot! Really clever way of building the sequence.
– RGS
Mar 13, 2020 at 19:27
• You can get rid of the questionable format by adding ,end=''. Mar 16, 2020 at 7:32
• @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. Mar 16, 2020 at 8:44
• now 3.8 is stable. Oct 15, 2020 at 16:40

# 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.

• 26 bytes? Mar 13, 2020 at 15:57
• @Giuseppe Thanks! I found an extra byte to golf, down to 25. Mar 13, 2020 at 16:15

# 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!

• 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.
– xnor
Mar 14, 2020 at 6:36
• @xnor You're right. The brackets must have been from failed attempts at porting. Thanks! Mar 14, 2020 at 6:38

# 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.

• You can use lambda to get rid of return statement, and 2-i instead of (2,1)[i]. 43 bytes Mar 13, 2020 at 17:39

# PowerShell, 23 bytes

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


Try it online!

Prints the sequence indefinitely.

# 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,
¨                    ⍝ 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.

• -13 chars Mar 13, 2020 at 18:36

# GolfScript, 16 bytes

Port of Surculose Sputum's Python answer.

0{100*121+.p.}do


Try it online!

# 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.

# Python 3, 37 bytes

i=1
while 1:print('1'+'2'*i+'1');i+=2


Try it online!

# Husk, 14 12 10 bytes

ṁJḋ3MRİ12


Try it online!

Infinite list.

-1 byte from Dominic Van Essen.

-2 bytes from Zgarb using voodoo magic.

• 13 bytes I think... Oct 15, 2020 at 16:19
• @DominicvanEssen that works with ȯ. nice. Oct 15, 2020 at 16:20
• Ah yes! Well spotted. Oct 15, 2020 at 16:21
• 10 bytes. It was a bit challenging to get J to choose the right type... Oct 17, 2020 at 11:39

# 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!

# 05AB1E, 6 bytes

>‚Å²Ë>


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

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

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)


# 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!

# Charcoal, 11 bytes

↷²1Ｗ¹«2Ｐ1Ｄ2


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.

Ｗ¹«


Loop forever.

2


Output 2 to the canvas.

Ｐ1


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

Ｄ


Copy the canvas to STDOUT.

2


Replace the 1 with a 2.

# 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.

# 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.


$i=0;1.."$args"|%{$i+=2;write-host "1,$('2,'*$i)1," -n}  Try it online! # 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. • Hey there, welcome to this community! Can you please provide a TIO link with your code? – RGS Mar 16, 2020 at 21:43 • @RGS Added TIO. Mar 16, 2020 at 22:13 • Thanks, nice first post! – RGS Mar 16, 2020 at 22:29 • Suggest j+=k+=2 instead of k+=2,j+=k Mar 17, 2020 at 1:06 • 39 bytes by removing j and using 1-based indexing. Mar 17, 2020 at 4:44 # MAWP 0.0, 16 bytes [1:![2:1A]%1:2M]  # 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! • I forgot that printing the sequence infinitely is an option... 34 bytes Mar 13, 2020 at 17:06 • 33 bytes by using the print statement as conditional Mar 13, 2020 at 18:21 # 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 • Can you please provide a TIO link? – RGS Mar 13, 2020 at 19:25 • Mar 14, 2020 at 16:15 • 42 bytes by just using 1 cell for ASCII 1 Mar 16, 2020 at 4:15 # 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. # 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.

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

# 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! # dirt (verbose mode), 17 bytes "1 2 1"|1" 2 2".*  Run as dirt ones_and_twos.dirt -v -i "" Outputs each element of the sequence on a new line. Alternatively, if we allow new lines between some but not all elements, ## dirt (verbose mode), questionable format, 13 bytes "121"|1"22".*  prints 121 12221 1222221 122222221 12222222221 1222222222221 122222222222221 12222222222222221 ...  # cQuents, 21 bytes _+(Tr$)%1)=Tr_+$)%1))  Try it online! Port of the jelly answer. ## Explanation  r$)     r_+\$)     # Root (defaults to square root)
%1        %1   # Modulo 1 (only taking the decimal part)
T     ) T       )  # Ceiling (round up if there is a decimal part)
(       =         ) # Equal (same as jelly answer)
_+                    # Successor (same as jelly answer)


# List output, 15 bytes

1,D2)*_-(k*2),1


Try it online!

Playing with the output a bit, we can golf off 6 bytes.

Instead of outputting 1,2,2,2,1, it outputs 1,[2,2,2],1.

## Explanation

1,              # A one
D2)           # Digits of 2 (which is of course, just 2)
*_-(k*2)   # Multiplied by k*2-1 (it's multiplying a list)
,1 # Another one

• Why is it cheating?
– RGS
Apr 9, 2020 at 6:06
• It outputs a list instead of outputting the sequence. It only works for indefinitely printing, whereas other normal cQuents code could work for all 3 cases (the third requiring an &). Apr 9, 2020 at 6:07
• Indefinite printing is fine but the lists in the middle of the numbers look weird
– RGS
Apr 9, 2020 at 6:09
• Hold on, I just found the jelly answer. Gonna port. Apr 9, 2020 at 6:15

do n<-[0..];'1':([1..n]>>"22")++"21"
`