text:
Compute the Kolakoski sequence

This is a repost of an old challenge, in order to adjust the I/O requirements to our recent standards. This is done in an effort to allow more languages to participate in a challenge about this popular sequence. See this meta post for a discussion of the repost.

The Kolakoski sequence is a fun self-referential sequence, which has the honour of being OEIS sequence A000002 (and it's much easier to understand and implement than A000001). The sequence starts with 1, consists only of 1s and 2s and the sequence element a(n) describes the length of the nth run of 1s or 2s in the sequence. This uniquely defines the sequence to be (with a visualisation of the runs underneath):
1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1,2,1,1,2,1,2,2,1,1,2,1,1,2,...
= === === = = === = === === = === === = = === = = === === = === =
1, 2,  2, 1,1, 2, 1, 2,  2, 1, 2,  2, 1,1, 2, 1,1, 2,  2, 1, 2, 1,...

Your task is, of course, to implement this sequence. You may choose one of three formats to do so:

Take an input n and output the nth term of the sequence, where n starts either from 0 or 1.
Take an input n and output the terms up to and including the nth term of the sequence, where n starts either from 0 or 1 (i.e. either print the first n or the first n+1 terms).
Output values from the sequence indefinitely.

In the second and third case, you may choose any reasonable, unambiguous list format. It's fine if there is no separator between the elements, since they're always a single digit by definition.
In the third case, if your submission is a function, you can also return an infinite list or a generator in languages that support them.
You may write a program or a function and use any of our standard methods of receiving input and providing output. Note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.

Related, but not a dupe.

Generalization of the problem, but optimizations are probably possible since the initial portion of the sequence is fixed.

While we're at it, I've got another generalisation as well.

Jelly, 7 bytes
2Rṁxṁµ¡

This is a full program that prints the first n terms.
Try it online!
How it works
2Rṁxṁµ¡  Main link. Argument: n (integer)

     µ   Combine the preceding links into a monadic chain.
      ¡  Set t = n.  Call the chain n times, updating t with the return value after
         each call. Yield the last value of t.
2R           Set the return value to 2 and take its range. Yields [1, 2].
  ṁ          Mold; cyclically repeat 1 and 2 to match t's length.
             In the first run, ṁ promotes t = n to [1, ..., n].
   x         Repeat the k-th element of the result t[k] times.
             In the first run, x repeats each element t = n times.
    ṁ        Mold; truncate the result to match the length of t.
             In the first run, ṁ promotes t = n to [1, ..., n].

Example run
Let n = 5.
The first invocation of the chain repeats 1, 2 cyclically to reach length 5, then each element 5 times, and finally truncates the result to length 5.
  1         2         1         2         1
x 5         5         5         5         5
---------------------------------------------------
  1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1

  1 1 1 1 1

This yields a list of length 5. The first element is the first element of the Kolakoski sequence.
The second invocation of the chain repeats 1, 2 cyclically to reach length 5, then repeats the kth element j times, where j is the kth element of the previous list, and finally truncates the result to length 5.
   1 2 1 2 1
x  1 1 1 1 1
------------
   1 2 1 2 1

   1 2 1 2 1

This yields another list of length 5. The first two elements are the first two elements of the Kolakoski sequence.
The process continues for three more iterations.
   1 2   1 2   1
x  1 2   1 2   1
----------------
   1 2 2 1 2 2 1

   1 2 2 1 2

   1 2   1   2 1
x  1 2   2   1 2
------------------
   1 2 2 1 1 2 1 1

   1 2 2 1 1

   1 2   1   2 1
x  1 2   2   1 1
----------------
   1 2 2 1 1 2 1

   1 2 2 1 1

These are the first five elements of the Kolakoski sequence.

Python 2, 42 bytes
x=y=-1
while 1:x=x/2^y;y<<=x%2;print x%2+1

Try it online!
Full disclosure - I didn't find the solution myself. I let my brute forcer do the heavy lifting for me and just watched the results roll in. At first, I didn't even try to understand the solution. I just assumed it was too complicated for me to wrap my head around. But then I realized that It's actually pretty simple.

Welcome to Code Golf! This was generated by a brute forcer? Surprised something this big can be generated by one in a reasonable amount of time. Guessing it works on something like the token/AST level rather than byte-for-byte of source code?

@RydwolfPrograms Yes, it works at the token/AST level. The first time I ran it, it took 21 hours! But now, after optimizing the brute force algorithm, it takes less than 10 hours. Another important thing to note is that it's written in Python and compiled to C using mypyc. I'm planning to rewrite it in C++, which should give it at least a 5x speedup. The reason it's so fast is because it prunes a lot of duplicate expressions. But There are still many things that I haven't pruned yet, and doing so would give it even more speedup than even rewriting it in C++.

This is very impressive! Did you give your brute-forcer a template to use for this solution, or did it find the whole structure?

I specified that it should use exactly 2 variables and that a==b and that they are within the range of [-4,9]. It found this at the start (b:=b//2^a)%(a:=a<<b%2)%2+1. However, I also added the ability to generate multiple separate expressions like (b:=b//2^a)%2+1; (a:=a<<b%2) (although I never enabled it :3). I also attempted to brute force it with a!=b and found other solutions, but none of them are shorter. I have given up for now, but I plan to improve it in the future.

Python 2, 51 bytes
l=[2]
print 1,2,
for x in l:print x,;l+=x*[l[-1]^3]

Prints indefinitely. Builds the list l as it's being iterated through. For each entry x of l, appends x copies of 1 or 2, whichever is opposite the current last element.
The main difficulty is dealing with the initial self-referential fragment [1,2,2]. This code just prints the initial 1,2 and proceeds from there. The extra printing costs 12 bytes. Without that:
39 bytes, missing first two entries:
l=[2]
for x in l:print x;l+=x*[l[-1]^3]

Another approach is to specially initialize the first two entries. We initialize l as [0,0,2] so that the first two entries don't cause appending, but print x or n makes them be printed as n.
51 bytes
l=[0,0,2]
n=1
for x in l:print x or n;l+=x*[n];n^=3

Another fix is to initialize l=[1], track the alternation manually in n, and correct the printing:
51 bytes
n,=l=[1]
for x in l:print(l==[1,1])+x;l+=x*[n];n^=3

Without the (l==[1,1])+, everything works except the printed sequences starts 1,1,2 instead of 1,2,2. There has to be a better way to recognize we're at this second step.
And another weird fix, also somehow the same byte count:
51 bytes
l=[1];q=2
for x in l:print x;l+=x*[l[-1]^3]*q;q=q<2

46 bytes

Wumpus, 13 11 bytes
=[=)O?=!00.

Try it online!
Prints the sequence indefinitely without separators.
I am genuinely surprised by how short this is.
Explanation
The basic idea is to keep the sequence on the stack and repeatedly use the bottom-most element to generate another run and then print it. We're effectively abusing the stack as a queue here. We can also save a couple of bytes by working 0 and 1 (incrementing only for output) instead of 1 and 2, because this way we don't need to explicitly initialise the stack with a 1 and we can use logical negation to toggle between the two values.
     The entire program is run in a loop.
     At the beginning of loop iteration i, a(i)-1 will be at the bottom of the
     stack and the first element of the ith run of values will be on top.
     The caveat is that on the first iteration, the stack is empty, but
     popping from an empty stack produces an implicit zero.
=    Duplicate the top of the stack. Since this is defined as "pop x, push
     x, push x" this will result in 2 zeros when the stack is empty.
     After this we've got two copies of the ith run's value on top of the stack.
[    Pull up a(i)-1 from the bottom of the stack.
=)O  Duplicate, increment to a(i) and print it.
?=   If a(i)-1 is 1 (as opposed to 0), make another copy of the top of the
     stack. We've now got a(i)+1 copies, so one more than the run should be
     long, but that's great because we can use the additional copy to get
     the start of the next run.
!    Logical negation which swaps 0 and 1.
00.  Jump back to the beginning of the program.

Brachylog, 30 26 25 23 17 16 bytes
~l{1|2}ᵐ.~lᵐ~ḅa₀

Outputs the first n values.
Try it online!
This is extremely slow: n = 6 takes over 30 seconds on TIO.

Doesn't work when the input is 1.

@Λ̸̸ You're right, good catch. I rolled back to a previous version that works for n=1.

Java 10, 155 108 105 100 97 94 bytes
v->{var s="122";for(int i=1;;s+=(s.charAt(i)>49?11:1)<<i%2)System.out.print(s.charAt(++i-2));}

Prints indefinitely without delimiter.
-3 bytes after an indirect tip from @Neil.
-5 bytes thanks to @MartinEnder.
-3 bytes converting Java 8 to Java 10.
-3 bytes thanks to @ceilingcat with the binary left-shift trick.
Explanation:
Try it online (times out after 60 sec on TIO).
v->{              // Method with empty unused parameter and no return-type
  var s="122";    //  String, starting at "122"
  for(int i=1;;   //  Loop `i` from 1 upwards indefinitely
      s+=         //    After every iteration: Append the String with:
         (s.charAt(i)>49?11:1)
                  //     Either once or twice depending on the digit at index `i`
          <<i%2)  //     With digits 2 or 1 by left-shifting with `i` modulo-2
    System.out.print(s.charAt(++i-2));}
                  //   Print the character at index `i-2` of the String
                  //   After we've first increased `i` by 1 with `++i`

The binary for 1 and 11 are 1 and 1011. If we left-shift with 0 they'll remain the same, but if we left-shift with 1 they'll become 10 (binary for 2) and 10110 (binary for 22) respectively.

I like how you have made this look so simple.

@EriktheOutgolfer Thanks! :) When I read the challenge I wasn't sure how to even start, but then it hit me (using a list with the initial [1,2,2] and go from there) and I wrote the 155 byte answer (which is now golfed by using a String instead of List).

Why not use (3-i) instead of (1+i%2)?

@EriktheOutgolfer because i isn't 1 or 2, it's the string index.

@ceilingcat Oh, that's a very nice trick! Thanks. (And best wishes for the New Year.)

Husk, 10 bytes
Ṡωo↑⁰`Ṙ¢ḣ2

Returns the first n values.
Try it online!
Explanation
Ṡωo↑⁰`Ṙ¢ḣ2  Input is an integer N.
        ḣ2  The range [1,2]
       ¢    Cycle: C = [1,2,1,2,1,2...
 ω          Iterate until fixed point is found:
Ṡ    `Ṙ      Replicate the list C element-wise according to the current list,
  o↑⁰        then take first N elements.

For input 20, the process goes like this:
[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2...
[1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2]
[1,2,2,1,1,2,1,1,2,2,1,2,2,1,1,2,1,1,2,2]
[1,2,2,1,1,2,1,2,2,1,2,1,1,2,2,1,2,2,1,1]
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,1,2]
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1]
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1]

Here's a variation printing the sequence indefinitely, same byte count but maybe you'll see some golfing opportunities I didn't Try it online!

⍵ should really be added to the documentation.

Python 2, 45 bytes
x=y=0
while 1:print 1+x%2;x^=~y&~-y;y=~-y&x/2

Try it online!
Based on this blog post, but golfed better. Has the bonus advantage of only using logarithmic space.
-1 thanks to xnor who realised we can invert and use ~x and ~y instead of x and y to avoid writing x=y=-1 for the initial condition.

Nice, I've posted a bounty! I'll be curious to read and understand how this approach works.

huh, do you not need the intermediate variable from the blog post? interesting that you can omit it entirely

@JoKing It works out because if you plug in f = y & ~(y+1) into y = (y+1) | (f & (x>>1)) to get y = (y+1) | (y & ~(y+1) & (x>>1)), the (y+1) | on the left means that the & ~(y+1) doesn't matter so it can be removed, leaving y = (y+1) | (y & (x>>1)). And now there's no need for storing f. (It also turns out the y & has no effect and can be removed.) So the end result is much cleaner than in the blog post.

One byte saved by replacing x and y with ~x and ~y to shorten the initial values: TIO

Thanks again for posting this! Reading the blog posts gave me a new understanding of BFS and of crawling binary trees.

J, 12 bytes
Single-argument function taking n and producing the first n terms. Try it online!
$(1+2|I.)^:]

Just sprucing up my old answer to the old question.
I. is a verb which takes an array of numbers and spits out a list of indices, so that if the k-th item in the array is n, then the index k appears n times. We'll use it to bootstrap the Kolakowski sequence up from an initial seed. Each step will proceed as follows:
1 2   2   1 1 2   1 2   2   1   (some prefix)
0 1 1 2 2 3 4 5 5 6 7 7 8 8 9   (use I.)
0 1 1 0 0 1 0 1 1 0 1 1 0 0 1   (mod 2)
1 2 2 1 1 2 1 2 2 1 2 2 1 1 2   (add 1)

If we perform this operation (1+2|I.) over and over starting from 10, it looks something like this:
10
1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2
1 2 2 1 2 2 1 2 2 1 2 2 1 2 2
1 2 2 1 1 2 1 1 2 2 1 2 2 1 1 ...
1 2 2 1 1 2 1 2 2 1 2 1 1 2 2 ...
1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 ...

Notice how we get more and more correct terms each time, and after a while the first n terms are fixed. The number of iterations it takes to settle down is hard to describe precisely, but it looks to be roughly logarithmic in n, so if we just run it n times (^:]) it should be fine. (Check out these other OEIS sequences for more info: generation lengths, partial sums.)
Once we're done that, all we have to do is take the first n terms using $. The construction $v for any verb v is an example of a hook, and giving it n as argument will execute n $ (v n).
Here is the old 13-byte version which is far less wasteful of time and space: ($1+2|I.)^:_~. It truncates the input at every step, so we can run exactly as many times as is needed to settle, instead of linearly many times.

Oh this works perfectly with I.. I've always wanted to see the copy feature of it used in some golf.

This is damn nice.

Jelly, 10 bytes
’ß€+\<¹SḂ‘

Returns the nth term.
Try it online!
How it works
’ß€+\<¹SḂ‘  Main link. Argument: n (positive integer)

’           Decrement; yield n-1.
 ß€         Recursively map the main link over [1, ..., n-1].
   +\       Take the cumulative sum.
            The k-th sum is the combined length of the first k runs.
     <¹     Compare each sum with n.
       S    Sum the Booleans.
            This counts the number of runs that occur before the n-th term.
            If there's an even number (including 0) of runs, the n-th term is 1.
            If there's an odd number of runs, the n-th term is 2.
        Ḃ   Extract the least significant bit of the count.
         ‘  Increment.

Haskell, 33 bytes
r=r%1
~(x:t)%n=n:[n|x>1]++t%(3-n)

Try it online!
Ørjan Johansen saved 7 bytes using an irrefutable pattern to force the prefix.

You can save 7 bytes by making it lazier. Try it online!

@ØrjanJohansen That's amazing and the lazy pattern is magic to me. Want to post your own answer?

Nah you were most of the way there. By using n: at the start of the expression you don't need to know the x is there to produce the first n. But you need the pattern to be lazy in order to avoid the function checking it before getting to the n:.

Shakespeare Programming Language, 594 583 572 bytes
Thanks to Ed Wynn for -10 bytes!
,.Ford,.Puck,.Act I:.Scene I:.[Enter Ford and Puck]Ford:You cat!Open heart!You big cat!Open heart!Puck:Remember you!Remember me!Scene V:.Ford:You is the sum ofI a cat!Puck:Recall!Open heart!Ford:Remember a pig!Is I nicer a cat?If notyou be the sum ofyou a big pig!Scene X:.Puck:Recall!Ford:Is I nicer zero?If soremember I!If solet usScene X!Puck:Is I nicer zero?You is the sum ofI a big cat!If soyou is I!Remember zero!Remember I!Remember you!You be the difference betweena big cat you!Scene L:.Ford:Recall!Is you worse I?If so,let usScene V!Puck:Remember I!Let usScene L!

Try it online!
This is a golfed version of Ed Wynn's ungolfed solution, starting from the 828 byte solution he linked in the comments and going a little nuts from there.
Explanation:
,.Ford,.Puck,.Act I:.Scene I:.[Enter Ford and Puck]    Boilerplate, introducing the characters
Ford:You cat!Open heart!You big cat!Open heart!  Print 1,2 as the first two terms of the sequence

Puck:Remember you!Remember me!  Initialise stack as 0, 2
                                Ford's value is currently 0, representing the value to be pushed to the stack

Scene V:.     Start infinite loop
  Ford:You is the sum ofI a cat!
  Puck:Recall!Open heart!                 Pop the next value in the stack and print it
  Ford:Remember a pig!                    Push -1 as the end of the stack
  Is I nicer a cat?                       If Ford's value is 2
  If notyou be the sum ofyou a big pig! Subtract 2 from Puck's value to represent making 2 only one copy

        #Reverse the stack until it reaches the terminator value 0 or -1
  Scene X:.Puck:Recall!Ford:Is I nicer zero?If soremember I!If solet usScene X!

  Puck:Is I nicer zero?                          Check if the Puck's value is bigger than 0 (only making one copy)
  You is the sum of Ia big cat!                 Set Ford's value to Puck+2 to counter the change
  If soyou is I!                                But undo it if making one copies
  Remember zero!                                 Push 0 as the stack terminator
  Remember I!                                    Push Ford's value, which is 0 or -1 if this is a single copy, or 1 or 2 for a double copy
  Remember you!                                  Push one copy of Puck's value
  You be the difference betweena big cat you!   Map Ford's value from 1,2 to 1,0

  Scene L:.   #Reverse the stack until it reaches the terminator 0
     Ford:Recall!Is you worse I?If solet us Scene V!
     Puck:Remember I!Let usScene L!

Nice! You can save 7 bytes by making the single child be (-1 or 0) instead of the twins.  This costs you 1 byte just before Scene X (when "If so" becomes "If not"), and another byte just after the Scene X loop (when "Is I nicer you" becomes "Is I nicer zero").  The saving is that you can replace the "If not,remember you!" with simply "Remember I!" one line earlier.  We insert either a second child or a spare terminator. (This is why you need to change the finely-balanced "Is I nicer you?" -- you can no longer rely on Ford==0 after Scene X.) Here is TIO, 587 bytes: https://tinyurl.com/yb9zg4gp

You can remove the first "If so," in Scene L and move the command to the start of Scene V.  This saves you only 1 byte, because you need a new "Ford:".  But you save a couple of bytes in Scene I, so long as you can rely on Ford being automatically zero-initialised. You have no right to rely on this, but it might work: here is TIO, 584 bytes: https://tinyurl.com/y9f6vy7u

Gol><>, 8 7 bytes
:{:PnKz

Try it online!
Explanation
This is a port of my Wumpus answer. Gol><> is basically the language that has all the necessary features to port the Wumpus answer (specifically, implicit zeros at the bottom of stack, "duplicate" implemented "pop, push, push", and a stack rotation command), but:

It has a toroidal grid, which means we don't need the explicit 00. to jump back to the beginning.
It has K, which is "pop N, then duplicate the next element N times", which can replace ?=, saving another byte.

So the mapping from Wumpus to Gol><> becomes:
Wumpus   Gol><>
=        :
[        {
=        :
)        P
O        n
?=       K
!        z
00.

JavaScript, 67 66 60 58 52 51 50 bytes
Well, that made my brain itch more than it should have! Retruns the nth term, 0-indexed.
s=`122`
x=1
f=n=>s[n]||f(n,s+=s[++x%2]*(s[x]+0-9))

5+1 bytes saved thanks to tsh scratching my itchy brain!

Test it
The snippet below will output the first 50 terms.

s=`122`
x=1
f=n=>s[n]||f(n,s+=s[++x%2]*(s[x]+0-9))
o.innerText=[...Array(50).keys()].map(f).join`, `
<pre id=o></pre>

Explanation
This is one of those rare occasions when we can declare some variables outside the scope of our function, modify them within the function and still be able to reuse them on subsequent calls of the function.
s=`122`       :Initialise variable s as the string "122"
x=1           :Initialise variable x as integer 1
f=n=>         :Named function f taking input as an argument through parameter n
 s[n]         :If s has a character at index n, return it and exit
 ||           :Or
 f(n          :Call f with n again
  ,s+=        :At the same time, append to s
  s[++x%2]    :  Increment x, modulo by 2 and get the character at that index in s
  *           :  Multiplied by (the above gets cast to an integer)
  (s[x]+0-9)  :  Append a 0 to the xth character of s and subtract 9
 )            :  (The above gives "1"+0-9="10"-9=1 or "2"+0-9="20"-9=11)

What about n=>(g=s=>s[n]||g(s+(++x%2+1)*(10*s[x]-9)))('122',x=1)

Btw, is s='122',x=1,g=n=>s[n]||g(n,s+=(++x%2+1)*(10*s[x]-9)) considered a valid submission?

Thanks, @tsh. s[n]|| was a clear case of not seeing the wood for the trees! Your second suggestion wouldn't be valid ,though, as the function could only be called once; s & x need to be initialised with each call.

the second one does be reusable, as long as s and x not touched by other codes between each invokes (which is by default).

Nice! s[x]+0-9 is a pretty neat trick

Wait, hang on; I see what you're saying now, @tsh. Don't know what my pre-caffeinated brain was thinking you were suggesting this morning! Yes, that would be valid as if we call the function a second time with a lower n then s[n] will already exist and if we use a higher n then the building of s will pick up where it left off after the first call. Thanks again. Will update shortly.

><>, 13 12 bytes
0:{:1+n?:0=!

Try it online!
A port of Martin Ender's Wumpus answer. Unfortunately, ><> doesn't have an increment or an invert command nor does it have implicit 0s on the bottom of the stack, so this ends up being a bit longer.

Yep, this is what I had before remembering Gol><>. :)

05AB1E, 12 9 bytes
Saved 3 bytes thanks to Grimy
Prints the first n items.
Δ2LÞsÅΓI∍

Try it online!
Explanation
Δ           # repeat until ToS doesn't change
 2LÞ        # push [1,2,1,2 ...]
    sÅΓ     # run-length encode with previous value (initially input)
       I∍   # extend/shorten to the length specified by input

Run-length decoding is now a built-in, so this can simply be 2L[2LÞsÅΓ.

Or even better: ∞[2LÞsÅΓ.

Or Δ2LÞsÅΓI∍ for a version that prints the first n items given input n.

@Grimy: Thanks! I like the first n version since it actually terminates :)

Haskell, 48 bytes
-1 byte thanks to nimi. -2 bytes thanks to Lynn.
c=1:2:c
l=1:2:drop 2(id=<<zipWith replicate l c)

Try it online!
Repeat every element its position mod 2 + 1 times.

You can save two more by defining c=1:2:c

Fueue, 30 bytes
Fueue is a queue-based esolang in which the running program and its data are both in the same queue, the execution goes around the queue in cycles, and programming requires lots of synchronizing to keep anything from executing at the wrong time.
1)2:[[2:])~)~:~[[1]:~))~:~~]~]

Try it online!
The above prints an unending list of digits as control codes. For 34 bytes it can print actual digits:
49)50:[[50:])~)~:~[[49]:~))~:~~]~]

Try it online!
The rest of the explanation uses the latter version.
Summary of Fueue elements
The Fueue queue can contain the following kind of elements:

Integers, which print their Unicode codepoint when executed,
Square-bracket delimited subprogram blocks, which are mercifully inactive (just moving to the end of the queue) unless the ) function deblocks them, and
Single-character functions, which execute if they are followed by the right type of arguments and remain inactive otherwise.

The only functions used in this program are ~ (swap two following elements), : (duplicate next element), and ) (deblock following block).

High level overview
During the main loop of the program, the queue consists of:

a chain of blocks representing digits to be iterated through;

A digit 1 or 2 is represented by the blocks [49] and [50:], respectively.

a self-replicating main loop section that traverses the digit blocks and puts alternating 1s and 2s after them, then deblocks them.

An deblocked digit block prints its own digit d, and then creates d copies of the following block, thus creating the digits for the run it describes.

Low level trace of first 10 commands
Cmds   Explanation              Queue
49     Print '1'.               )50:[[50:])~)~:~[[49]:~))~:~~]~]
)      Inactive, move to end.   50:[[50:])~)~:~[[49]:~))~:~~]~])
50     Print '2'.               :[[50:])~)~:~[[49]:~))~:~~]~])
:[...] Duplicate block.         )[[50:])~)~:~[[49]:~))~:~~]~][[50:])~)~:~[[49]:~))~:~~]~]
)[...] Deblock (rmv. brackets). [[50:])~)~:~[[49]:~))~:~~]~][50:])~)~:~[[49]:~))~:~~]~
[...]  Inactive.                [50:])~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~]
[50:]  Inactive.                )~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:]
)      Inactive.                ~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:])
~)~    Swap ) and ~.            :~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:])~)
:~     Duplicate ~.             [[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:])~)~~

Walkthrough of a full main loop iteration
Optional whitespace has been inserted to separate commands.
49 ) 50 :[[50:])~)~:~[[49]:~))~:~~]~]

Cycle 1: 49 prints 1. ) is inactive, waiting to be brought together with the main loop block. 50 prints 2. : duplicates the main loop block (which needs a copy for self-replication.)
) [[50:])~)~:~[[49]:~))~:~~]~] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 2: ) deblocks the first main loop block, making it start executing next cycle.
[50:] ) ~)~ :~ [[49]:~))~:~~] ~[[50:])~)~:~[[49]:~))~:~~]~]

Cycle 3: [50:] represents the first digit produced in the chain, a 2 not yet deblocked. The following ) will eventually do so after the rest of the main loop has traversed it. ~)~:~ is a golfed (using a swap and a copy) one-cycle delay of ~)~~. [[49]:~))~:~~] is inactive. ~ swaps the following main loop block past the [50:] digit block.
) ~)~ ~[[49]:~))~:~~][50:] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 4: ) still waits, ~)~ produces ~), ~ swaps [[49]:~))~:~~] past the [50:] digit block.
) ~)[50:] [[49]:~))~:~~] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 5: ~ swaps ) past the [50:] digit block.
)[50:] )[[49]:~))~:~~] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 6: The first ) now deblocks the [50:] digit block, the next ) deblocks the subprogram [[49]:~))~:~~].
50 :[49] :~ ) ) ~:~ ~[[50:])~)~:~[[49]:~))~:~~]~]

Cycle 7: 50 prints 2, : duplicates the just produced [49] digit block, creating a run of two 1s. :~))~:~ is a one-cycle delay of ~~))~:. ~ swaps the remaining main loop block past the first [49].
[49] ~~) ) ~:[49] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 8: ~~)) is a one-cycle delay of )~). ~ swaps : past the currently traversed [49].
[49] ) ~)[49] :[[50:])~)~:~[[49]:~))~:~~]~]

Cycle 9: ~ swaps ) past [49]. : duplicates the main loop block.
[49] )[49] )[[50:])~)~:~[[49]:~))~:~~]~] [[50:])~)~:~[[49]:~))~:~~]~]

Cycle 10: The first ) deblocks the [49] digit block just traversed, the second ) restarts the main loop to traverse the next one (above shown at the beginning of the queue.)

Nice work! The reason I learned some Fueue and answered the HW challenge because I actually looked into it for this challenge, but ended up being too intimidated by the queue-based nature. That's a really great score for Fueue! :)

Python (2 and 3), 65 60 bytes
f=lambda n:sum([f(i)*[i%2+1]for i in range(2,n)],[1,2,2])[n]

Returns the nth entry, 0-indexed.
Alternative (65 bytes):
f=lambda n:n>1and sum([f(i)*[i%2+1]for i in range(n)],[])[n]or-~n

Welcome to PPCG!

You can (probably, I didn't tested though) save 5 bytes in the alternative version by using [1,2,2] as starting value in the sum

brainfuck, 61 bytes
+.+.[.[>]>+++>+++<<<[->+>->-<<<]<[[->+<]<]>>--[[>]<,<[<]>+]>]

Try it online!
Prints numbers as char codes indefinitely. For clarity, here's a version that prints in numbers (except for the first two elements, which are easy enough to verify).
How It Works:
+.+. Prints the first two elements. These are the self-referential elements
     This also intitialises the tape with the third element, 2
[ Start infinite loop
   . Print current lowest element
   [>]>+++>+++ Move to end of tape and create two 3s
   <<<[->+>->-<<<] Subtract the last element of the tape from these 3s
   <[[->+<]<]>> Move to the beginning of the tape
   --  Subtract two from the first element
       This leaves 2 as 0 and 1 as -1
   [ If the number was 1
     [>]<,  Delete the excess element from the end of the tape
     <[<]>+ Remove the -1
   ]
   > Move to the next element of the list
]

It took me a while to spot that your step "Move to the beginning of the tape" is really neat -- it actually shuffles the rest of the tape up one place, to fill the gap. Nice! So it's almost a shame to point out a way to save 9 bytes by not making a gap: Try it online!
+.+.[.[>]<-[>>>-<]>+[>+>]<+<+<+[<]>--[[>]<,<[<]>+]>]

05AB1E, 15 bytes
ƵLS[DNÌ©èF®É>¸«

Try it online!
or with an iteration limit
Explanation
ƵLS               # push our initial list [1,2,2]
   [              # for every N in [0 ...
    D             # duplicate current list of numbers
     NÌ©è         # get the N+2'th element from the list
         F        # that many times do
          ®É>     # push ((N+2)%2==1)+1
             ¸«   # append to current list

Instead of ¸«, = would print them for 2 bytes saved. ƵLS[NÌ©èF®É>=, no need to dupe if you're not consuming.

@MagicOctopusUrn: I don't produce the first 3 items though, so printing unfortunately doesn't work

Perl 5, 36 bytes
Still a trivial modification of the classic TPR(0,3) solution:
Outputs the series from 0 to n
#!/usr/bin/perl
use 5.10.0;
say$_=($n+=!--$_[$n])%2+1for@_=0..<>

Try it online!

Python 3, 55 54 bytes
n=h=1;l=[]
while n:print(h);n^=3;h,*l=l+[n]*(l+[2])[0]

Try it online!

C (gcc), 72 71 65 64 62 bytes
-9 bytes thanks to @ceilingcat
x,y;f(z){for(x=y=-1;putchar(49-~x%2);y=-~y|z&x/2)x^=z=y&~-~y;}

Try it online!
Generates values of the sequence indefinitely (option 3 from the challenge)

Explanation please! I have no idea how this works. There is no array! And the numbers stay too small to contain one as bits.

@ØrjanJohansen I have to admit, I have no idea how this works either! :) I took the python implementation from OEIS A000002, ported it to C and golfed it :)

Ah I thought it might have been something there, but didn't look far enough down that page to find the Python. There's a link to an explanation, but it was a bit buried in the link section. This method definitely fits C at least as well.

56 bytes in PHP: for($x=$y=-1;;$y=$y+1|$f&.5*$x^=$f=$y&-$y-2)echo$x&1?:2;. 2) 50-x%2 should save one byte for you. 3) I tried to get it running with x=y=1; but couldn´t get the operations right so far. Can you?

R, 63 bytes or 61 bytes
Implementation 1: prints out the nth term of the sequence.
x=scan()
a=c(1,2,2)
for(n in 3:x)a=c(a,rep(2-n%%2,a[n]))
a[x]

Implementation 2: prints out the first n terms of the sequence.
x=scan()
a=c(1,2,2)
for(n in 3:x)a=c(a,rep(2-n%%2,a[n]))
a[1:x]

(The difference is only in the last line.)
Yes, yes, you may complain that my solution is inefficient, that it computes really more terms than needed, but still...
Update: Thanks to @Giuseppe for shaving off 9 bytes.

use a=c(a,rep(2-n%%2,a[n])) instead of the second for loop to shave off some bytes.

@Giuseppe Implemented, thanks!

We don't mind inefficient for golfing solutions here. In fact using a more inefficient algorithm is one of the tips in the code-golf tag wiki.

You can use 2-!0:2 instead of c(1,2,2) for -2 bytes.

x86, 41 37 35 33 28 bytes
I had a lot of fun messing around with different x86 instructions, as this is my first "non-trivial" x86 answer. I actually learned x86-64 first, and I saved many bytes just by converting my program to 32-bit.
It turns out the algorithm I used from OEIS pushes values to an array, which makes it amenable to x86 and storing values on the stack (note MIPS doesn't have stack instructions).
Currently the program takes N values as input in ecx and returns an address in ebp of an array with the nth element representing the nth value in the sequence. I assume returning on the stack and computing extra values is valid (we consider what's beyond the array as garbage anyway).
Changelog

-4 bytes by computing x = 2 - n%2 with xor every iteration
-2 bytes by using do-while instead of while loop.
-2 bytes by pushing initial values 1, 2, 2 using eax
-5 bytes by not storing n explicitly and instead running loop N times

.section .text
.globl main
main:
        mov     $10, %ecx           # N = 10

start:
        mov     %esp, %ebp          # Save sp
        push    $1
        push    $2                  # x = 2
        pop     %eax
        push    %eax                # push 2
        push    %eax                # push 2
        mov     %esp, %esi          # sn = stack+3 addr

loop:
        xor     $3, %al             # flip x between 1 <-> 2
        push    %eax                # push x
                                    # maybe use jump by parity?
        cmp     $2, (%esi)          # if *sn == 2
        jne     loop1
        push    %eax                # push x

loop1:
        sub     $4, %esi            # sn += 1
        loop    loop                # --N, do while (N)
end:
        mov     %ebp, %esp          # Restore sp
        ret

Objdump:
00000005 <start>:
   5:   89 e5                   mov    %esp,%ebp
   7:   6a 01                   push   $0x1
   9:   6a 02                   push   $0x2
   b:   58                      pop    %eax
   c:   50                      push   %eax
   d:   50                      push   %eax
   e:   89 e6                   mov    %esp,%esi

00000010 <loop>:
  10:   34 03                   xor    $0x3,%al
  12:   50                      push   %eax
  13:   83 3e 02                cmpl   $0x2,(%esi)
  16:   75 01                   jne    19 <loop1>
  18:   50                      push   %eax

00000019 <loop1>:
  19:   83 ee 04                sub    $0x4,%esi
  1c:   e2 f2                   loop   10 <loop>

0000001e <end>:
  1e:   89 ec                   mov    %ebp,%esp
  20:   c3                      ret

Appleseed, 89 bytes
(def K(lambda()(concat(q(1 2))(drop 2(flatten(zip-with repeat-val(cycle(q(1 2)))(K)))))))

Defines a function K that takes no arguments and returns the Kolakoski sequence as an infinite list. Try it online!
This approach was inspired by totallyhuman's Haskell answer. My original approach was longer and was probably O(2^n). :^P
Ungolfed
(def kolakoski
 (lambda ()
  (concat (list 1 2)
   (drop 2
    (flatten
     (zip-with repeat-val
      (cycle (list 1 2))
      (kolakoski)))))))

The return list begins with (1 2). After that, to generate the rest of it (reading from the inside out):

Recursively call (kolakoski) to get the Kolakoski sequence list (due to lazy evaluation, it doesn't matter that the list hasn't been fully generated yet)
(cycle (list 1 2)) creates an infinite list (1 2 1 2 1 2 ...)
Zip the two infinite lists together using the function repeat-val. This will repeat the 1 or 2 from the cycle list either one or two times depending on the associated value in the Kolakoski list. Result: ((1) (2 2) (1 1) ...)
flatten that list into (1 2 2 1 1 ...)
We've already got the first two terms from (concat (list 1 2), so we drop the first two from the generated list to avoid duplication.

Javascript ES6 - 71 70 68 bytes
(_="122")=>{for(x=1;;_+=(1+x%2)*(_[x]>1?11:1))console.log(_[++x-2])}

1 bit saved thanks to Neil
Tanks to Shaggy for correcting my mistake, also for saving 1 bit.

f = (_="122") => {
  for(x=1;x<20;_+=(1+x%2)*(_[x]>1?11:1))
    document.getElementById('content').innerHTML += '   ' + _[++x-2]
}
f()
<div id="content"></div>

This looks like a port of my Java 8 answer (except for x=0 instead of x=1), but @Shaggy is indeed right: this doesn't work in its current form (I added the ,i=100;i-->0 temporarily to just see the first 100 items, instead of having to wait 60 sec before seeing an output). No idea why it doesn't work, though. JS is not my thing.

The problems are: 1. initiating x to 0 instead of 1 (as @KevinCruijssen mentioned) and 2. checking if the xth character in the string, which can only ever be 1 or 2, is greater than 49.

Here's a golfed down (but not fully tested) version of the fixed solution: https://tio.run/##HctBCoAgEADAvwSBZgbrsbAeEh3ELAppw5XY31t0HZjTPY58Ou6sL1xDcTGkbD1ehDF0EfeyYRJkKzCmatnCMJCyAhTXRjaCZl5GmAB6kPK/HynF2iyylBc

(_[x]*10-9) than (_[x]>1?11:1)

Stax, 12 bytes
╦╥2Bïß▄n»-[╒

Run and debug it
This is the ascii representation of the same program.
G@}2R;D{|;^]*m$

It expands the sequence x times where x is the input.  Then it outputs the xth element, 0-indexed.
G }             G jumps to trailing } and returns when done
 @              get xth element in array
   2R           [1, 2]
     ;D         repeat the rest x times
       {     m  map array using block
        |;^]    produces [1] and [2] alternately
            *   repeat array specified number of times
              $ flatten array

Here's a bonus 12-byte solution that produces output as an infinite stream.  Press Run to start.

Shakespeare Programming Language, 575 bytes (but defective), or 653 or 623 bytes
,.Puck,.Ford,.Act I:.Scene X:.[Enter Puck and Ford]Ford:You big cat!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you nicer zero?If not,let us Scene X.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L.

In the hotly contested SPL category, this would beat Jo King's current entry (583 bytes), except that it is defective: First, it does not run in the TIO version (implementing the SPL website) -- but it does run in the Perl version, so maybe that is not a serious defect.  Second, though, it does not print the first two digits.  If we allowed that defect in Jo King's solution, then that defective solution would be 553 bytes, beating my defective solution.
My solution fails on TIO for two reasons: we try to rely on an empty stack returning zero when popped; and we goto the first scene, with "[Enter Ford and Puck]" even though nobody has left the stage.  These are merely warnings in the Perl version.  If I fix these errors and put in the first two digits, I reach 653 bytes:
 ,.Puck,.Ford,.Act I:.Scene I:.[Enter Puck and Ford]Ford:You cat!Open heart!You big cat!Open heart!You zero!Scene X:.Ford:Remember you!You big cat!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you nicer zero?If not,let us Scene X.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L.

Try it online!
I can generate the full sequence in the Perl implementation using 623 bytes:
,.Puck,.Ford,.Act I:.Scene I:.[Enter Puck and Ford]Ford:You cat!Open heart!You big cat!Open heart!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you worse a cat?If so,you big cat!If so,let us Scene L.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L.

However, I would point out that this solution is fast compared to many other solutions, and uses logarithmic amounts of memory rather than storing the whole list.  (This is similar to vazt's C solution, to which it is distantly related.)  This makes no difference for golf, but I'm pleased with it even so. You can generate a million digits in about a minute in Perl (for example if you pipe to sed and wc to get a digit count), where the other solution might give you a few thousand digits.
Explanation
We store a sequence of variables in order: Puck's stack (bottom to top), Puck's value, Ford's value, Ford's stack (top to bottom). Apart from zero values at the ends (with the zero on the left maybe from popping an empty stack), each value is the digit generated next at that generation, with 2 added if the next generation needs to have another child from that parent.  When we have N non-zero values in the sequence, we generate all the children up to and including the N-th generation, in a kind of depth-first tree traversal.  We print values only from the N-th generation.  When the N-th generation has been completely generated, the stored values are in fact the starting values for generations 2 to (N+1), so we append a 2 at the left and start again, this time generating the (N+1)-th generation.
So, an outline:
Scene X: When we reach here, this the start of a new traversal.  Puck==0. We optionally push that zero onto Puck's stack, and set Puck=2.
Scene L: If Ford==0, we have reached the printing generation.  If not, goto V.  For printing, if the value in Puck has had 2 added, remove the 2 and print it twice; if not, print it once.
Scene M: This is a loop where we repeatedly toggle the value of Puck and go back through the sequence. We repeat until either we reach the end (Puck==0), in which case goto X, or we reach a value that needs another child (Puck>2), in which case subtract the extra 2 and go forwards in V.
Scene V: Here we go forwards. If Puck is 2 or 4, the next generation will contain two children from the current parent, so Ford+=2.  Step forwards through the sequence.  Goto L to check for termination.

APL (Dyalog Unicode), 34 bytes
1{⎕←⍺⌷⍵⋄(1+⍺)∇⍵,⍵[2+⍺]⍴2-2|⍺}1 2 2

Try it online!
I'm flabbergasted that there was no APL answer to this challenge yet.
This is a full program that outputs the sequence indefinitely.
Thanks to @dzaima for -3 bytes.
How
1{⎕←⍺⌷⍵⋄(1+⍺)∇⍵,⍵[2+⍺]⍴2-2|⍺}1 2 2 ⍝ Full program. Inputs ⍺=1, ⍵=1 2 2
  ⎕←                                ⍝ Print
    ⍺⌷⍵                             ⍝ the ⍺th element of ⍵
       ⋄                            ⍝ Then
        (1+⍺)∇                      ⍝ Recurse with ⍺=⍺+1 and ⍵=
              ⍵,                    ⍝ append to ⍵
                       2-2|⍺        ⍝ 2 minus ⍺ modulo 2
                      ⍴             ⍝ reshape (repeats right arg, left arg times)
                ⍵[2+⍺]              ⍝ using the (2+⍺)th element of ⍵

{⍵{⍺↑⍵/⍺⍴⍳2}⍣⍵⍴⍨⍵} (port of the jelly answer)

axo, 13 bytes
[:|[1+{#;1;-_

Try it online!
Explanation
This started out as a port of an alternative solution in my Wumpus answer:
2%)[=]&=[O00.

This resulted in 18 bytes. I ended up golfing it down to the 13 bytes you see above to adjust it more to the way axo works. This 13-byte version then ended up inspiring the improvement down to 11 bytes in Wumpus, so now it's actually closer to that version.
As in Wumpus, in iteration i, the bottom of the stack holds a(i)-1 and the top holds the first element of the ith run, but we're working with 0 and 1 throughout, except for printing.
[:    Store a copy of the top of the stack in register A.
|     Pull up a(i)-1 from the bottom of the stack.
[1+{  Print a(i).
#;    If a(i)-1 is 1, push the value in register A.
1;-   Push another copy of that value and subtract it from 1 to swap
      0 and 1 for the next run.
_     Jump back to the beginning of the program.

Wolfram Language (Mathematica), 59 bytes
Nest[Flatten@*MapIndexed[Mod[#2,2,1]~Table~#&],{2},#][[#]]&

Try it online!

Ruby, 45 39 bytes
a=*i=0;loop{a+=[k=1+i%2]*p(a[i+=1]||k)}

prints indefinitely
Try it online!
Try it with an overloaded print function that allows you to pick a separator and the number of elements printed

Ruby, 44 43 37 bytes
b=*a=2;loop{b+=[a^=3]*p(b[$.+=1]||a)}

Try it online!
Prints an infinite sequence of numbers separated by newlines.
-1 byte thanks to Martin Ender.

Br**nfuck, 96 bytes
+.+..<<+.[.[[>>]<+<[<<]>>-]>>[>>]<[>[>>]+++<<[<]>>-]<[<+>>+<-]>[>->>[-<]<<[<]>-]<<[>+<-]>[<<]>>]

Try it online!
This prints terms indefinitely.
Explanation
+.+..<<+.[                       Initialize the tape with {1, 0, 2} (printing the first four terms). Start an infinite loop.
  .[ [>>] <+< [<<] >>- ]           Print the first value and move it to the end. Let's call it n.
  >> [>>]                          Move to the end of the filled part of the tape.
  <[                               n times:
    > [>>] +++<< [<] >>-             Make a three on the end.
  ]
  < [<+>>+<-]                      Copy the last sequence value calculated, k.
  >[>->>[-<]<<[<]>-]               Subtract k from all the 3s made earlier.
  <<[>+<-]>                        Move the copied k back into place.
  [<<]>>                           Return to the start of the tape.
]                                End loop.

I've been trying to save some bytes by including no empty cells between terms. No luck so far, but maybe someday soon...
Pastebin of the (naïvely) transpiled .java file. Outputs as base-10 numbers, each on a line. Come to think of it, unary is probably the way to go for this challenge...

Why would you censor "brain" but not "fuck"... ?

@EsolangingFruit It seems to be a variant of one of the name variants of BF

Jelly, 15 bytes
R€a"JḂ$Fo2
2Ç¡ḣ

A monadic link accepting an integer n which yields the first n terms.
Try it online!

CJam, 31 27 23 bytes
Prints the first n entries.
l~H3b{ee{(2%)+}%e~}2$*<

Try online

You can replace [1 2 2] with H3b (convert 17 to base 3).

Good catch! Answer updated.

A simple byte save would be ~4+ --> 3^, but you can actually do several bytes better by making use of run-length decoding: l~H3b{ee{(2%)+}%e~}2$*< (I also changed = to < because it's the same byte count but makes it easier to verify the correctness of the solution.)

I'm quite new to code golfing and I hadn't looked into these compression mechanisms like base conversion and runlength encoding yet. Gotta read up I guess :)

I managed to golf the anwer without ee down to 24 bytes: l~_H3b\{_X2%)a\X)=*+}fX<

Perl 6, 53 41 bytes
-12 bytes thanks to nwellnhof!
{1,2,2,{$/=$++%2+1;|($/xx@_[2+$++])}...*}

Try it online!
Anonymous code block that returns a lazy infinite sequence of values.
Explanation:
{                                       }  # Anonymous code block
 1,2,2,     #Hard-code the self-referential elements
       {                           }...*   # Get the next element based on the previous elements
        $/=$++%2+1;    # Swap the variable keeping track of 1 or 2
                     $/xx   # Repeat that variable
                         @_[2+$++]   # From the next element in the sequence
                   |(             )  # And add those elements to the sequence

41 bytes (I think it's OK to simply return an infinite sequence. 47 bytes, otherwise.)

@nwellnhof Neat. I didn't know you could add more than one element to the list at a time, thanks!

-1 byte, avoiding $/: Try it online!

APL (Dyalog Extended), 13 bytes
{⍺↑2-2|⍸⍵}⍣≡⍨

Try it online!
Basically a port of 13-byte J code at the bottom of algorithmshark's J answer ($1+2|I.)^:_~.
Takes an integer n and gives first n terms.
How it works
{⍺↑2-2|⍸⍵}⍣≡⍨  ⍝ Input: n
{        }     ⍝ At each step,
       ⍸⍵      ⍝   For each item a_i at index i, give a_i copies of i
   2-2|        ⍝   Modulo 2 then subtract from 2;
               ⍝   convert 1 2 3 4 5 .. to 1 2 1 2 1 ..
 ⍺↑            ⍝   Take first n items
          ⍣≡   ⍝ Repeat until the result does not change
            ⍨  ⍝   using n as both the fixed ⍺ and the starting ⍵

Factor, 75 bytes
[ { 1 2 } over [ [ 2 mod 1 + <array> ] map-index concat ] times swap head ]

Try it online!
Somewhat ended up like the J solution, just more bloaty.
Since Factor is stack-based, it is shorter to hardcode the starting array than to copy the input and create an array out of it.
[                      ! anonymous lambda, taking input n from stack
  { 1 2 } over         ! ( n arr n )
  [ ... ] times        ! run lambda n times to the array { 1 2 } ...
    [ ... ] map-index  !   given an array, map each with index...
      2 mod 1 +        !     ( item idx%2+1 )
      <array>          !     an array of length `item`, filled with idx%2+1
    concat             !   concat the elements of nested arrays
  swap head            ! take first n items from the result
]

Jelly, 21 bytes
3_ṪẋŒgL‘ịƲ⁸;
2Rx`Ç⁸¡ḣ

Try it online!

MIPS, 128 124 108 88 bytes
Changelog:

Mar 24: Fix mod
Mar 25: Simplify algorithm (no need to push n)
Mar 26: Simpler algorithm using stack

 Address    Code        Basic                     Source

0x00400000  0x24020001  addiu $2,$0,0x00000001    8         li      $v0, 1          # print first 3 vals
0x00400004  0x2404007a  addiu $4,$0,0x0000007a    9         li      $a0, 122
0x00400008  0x0000000c  syscall                   10        syscall
0x0040000c  0x24180002  addiu $24,$0,0x0000000    12        li      $t8, 2          # const 2
0x00400010  0xafb8fff4  sw $24,0xfffffff4($29)    13        sw      $t8, -12($sp)   # l[3] = 2
0x00400014  0x24080003  addiu $8,$0,0x00000003    14        li      $t0, 3          # n = 3
0x00400018  0x23a9fff4  addi $9,$29,0xfffffff4    15        addi    $t1, $sp, -12   # i = l + 3
0x0040001c  0x23abfff4  addi $11,$29,0xfffffff    16        addi    $t3, $sp, -12   # ln = l + 3
0x00400020  0x31040001  andi $4,$8,0x00000001     19        andi    $a0, $t0, 1     # n%2
0x00400024  0x03042022  sub $4,$24,$4             20        sub     $a0, $t8, $a0   # x = 2 - n%2
0x00400028  0xad24fffc  sw $4,0xfffffffc($9)      21        sw      $a0, -4($t1)    # *(i+1) = x
0x0040002c  0x0000000c  syscall                   24        syscall                 # print x
0x00400030  0x8d6c0000  lw $12,0x00000000($11)    26        lw      $t4, ($t3)      # temp = *ln
0x00400034  0x20010002  addi $1,$0,0x00000002     27        bne     $t4, 2, kol2    # if temp == 2
0x00400038  0x142c0003  bne $1,$12,0x00000003
0x0040003c  0xad24fff8  sw $4,0xfffffff8($9)      29        sw      $a0, -8($t1)    # *(i+2) = x
0x00400040  0x0000000c  syscall                   32        syscall                 # print x
0x00400044  0x2129fffc  addi $9,$9,0xfffffffc     34        addi    $t1, $t1, -4    # i += 1
0x00400048  0x2129fffc  addi $9,$9,0xfffffffc     37        addi    $t1, $t1, -4    # i += 1
0x0040004c  0x21080001  addi $8,$8,0x00000001     38        addi    $t0, $t0, 1     # n += 1
0x00400050  0x216bfffc  addi $11,$11,0xfffffff    39        addi    $t3, $t3, -4    # ln += 1
0x00400054  0x08100008  j 0x00400020              40        j       koll

Old solution
 Address    Code        Basic                     Source

0x00400040  0x23bdfff4  addi $29,$29,0xfffffff    32        addi    $sp, $sp, -12           # allocate 3 ints
0x00400044  0xafbf0000  sw $31,0x00000000($29)    33        sw      $ra, ($sp)              # push $ra
0x00400048  0x20010001  addi $1,$0,0x00000001     34        bne     $a0, 1, kol1            # if n == 1
0x0040004c  0x14240002  bne $1,$4,0x00000002
0x00400050  0x00041021  addu $2,$0,$4             35        move    $v0, $a0                # return n
0x00400054  0x08100026  j 0x00400098              36        j       kolret
0x00400058  0x24100001  addiu $16,$0,0x0000000    39        li      $s0, 1                  # k = 1
0x0040005c  0x00048821  addu $17,$0,$4            40        move    $s1, $a0                # x = n
0x00400060  0xafb00004  sw $16,0x00000004($29)    43        sw      $s0, 4($sp)             # push k
0x00400064  0xafb10008  sw $17,0x00000008($29)    44        sw      $s1, 8($sp)             # push x
0x00400068  0x00102021  addu $4,$0,$16            45        move    $a0, $s0                # arg1 = k
0x0040006c  0x0c100010  jal 0x00400040            46        jal     kol                     # f(k)
0x00400070  0x8fb00004  lw $16,0x00000004($29)    48        lw      $s0, 4($sp)             # pop k
0x00400074  0x8fb10008  lw $17,0x00000008($29)    49        lw      $s1, 8($sp)             # pop x
0x00400078  0x02228822  sub $17,$17,$2            51        sub     $s1, $s1, $v0           # x -= f(k)
0x0040007c  0x20010001  addi $1,$0,0x00000001     52        bgt     $s1, 1, kol4            # if x <= 1
0x00400080  0x0031082a  slt $1,$1,$17
0x00400084  0x14200007  bne $1,$0,0x00000007
0x00400088  0x02301020  add $2,$17,$16            53        add     $v0, $s1, $s0           # r = x + k
0x0040008c  0x20420001  addi $2,$2,0x00000001     54        addi    $v0, $v0, 1             # r = x + i + 1
0x00400090  0x30420001  andi $2,$2,0x00000001     55        andi    $v0, $v0, 1             # r = (x + k + 1) % 2
0x00400094  0x20420001  addi $2,$2,0x00000001     56        addi    $v0, $v0, 1             # ret (x+k+1)%2 + 1
0x00400098  0x8fbf0000  lw $31,0x00000000($29)    59        lw      $ra, ($sp)              # pop $ra
0x0040009c  0x23bd000c  addi $29,$29,0x0000000    60        addi    $sp, $sp, 12            # free stack memory
0x004000a0  0x03e00008  jr $31                    61        jr      $ra
0x004000a4  0x22100001  addi $16,$16,0x0000000    64        addi    $s0, $s0, 1             # k += 1
0x004000a8  0x08100018  j 0x00400060              65        j       kolw

Assembly-friendly algorithm I came up with, based on Benoit Cloitre's OEIS formula:
def f(n):
    if n == 1: return n
    k = 1
    x = n
    while True:
        x -= f(k)

        if x <= 1:
            return (x + k + 1)%2 + 1

        k += 1

for n in range(1, 10):
    print(f(n), end=',')

PHP, 61 bytes

for($v=2;$n<$argn;$s.=$v^=3,$x>1&&$s.=$v)echo$x=$s[$n++]?:$n;

prints the first \$n\$ elements without a separator. Run as pipe with -nr or try it online.

Momema, 64 bytes
02 1 3-8 1j0+1*0+1-**00+1*0-8+1**1 1+1*1j+-1*+-1*1+1*0**00+1*0j1

Explanation
The idea is to gradually fill up the tape with the decremented values of the sequence. We use index 0 for the write head and index 1 for the read head.
0  2            #  w = 2
1  3            #  r = 3
-8 1            #  print(1)
j  0            #  do {
  +1*0  +1-**0  #    tape[1 + w] = 1 - tape[w]
  0     +1*0    #    w = 1 + w
  -8    +1**1   #    print(1 + tape[r])
  1     +1*1    #    r = 1 + r
j  +-1*+-1*1    #    if (tape[r - 1] - 1) continue
  +1*0  **0     #    tape[1 + w] = tape[w]
  0     +1*0    #    w = 1 + w
j  1            # } while (1)

Try it online!

dirt -v, 48 bytes
"122,11"|.*`,(1',.*(1'2|2'1)|2',.*(1"22"|2"11"))

Continuously outputs longer and longer Kolakoski sequences, with a , in the middle that moves right as the sequence is generated:
122,11
1221,12
12211,21
122112,122
1221121,221
12211212,2122
122112122,12211
1221121221,22112
12211212212,211211
122112122122,1121122
1221121221221,1211221
12211212212211,2112212
122112122122112,11221211
1221121221221121,12212112
12211212212211211,22121121
122112122122112112,212112122
1221121221221121122,1211212211
12211212212211211221,2112122112

Run as dirt kolakoski.dirt -v -i "", or by feeding it an empty file dirt kolakoski.dirt -v < empty.txt

Unlambda, 419 bytes
```c`.1.2``s``s`ks``s`kd``s`kk``sii`k``s``s``s``si`kk`k``s``s``s``si`k`ki`k``s`k.1``s``s`ks``s`k`si``s`kk`s``s`ks``s`kk``s`ksk`k`k`ki`k``s`k.1``s``s`ks``s`k`si``s`kk`s`k`s``s`ksk`k`kk``si`kk`k``s``s``s``si`k`ki`k``s`k.2``s``s`ks``s`k`si``s`kk``s`k`s``s`ks``s`kk``s`ksk`s``s`ks``s`kk``s`ksk`k`k`ki`k``s`k.2``s``s`ks``s`k`si``s`kk``s`k`s`k`s``s`ksk`s`k`s``s`ksk`k`kk``si`kk``s`k`s``si`k`k`ki``s`kk``si`k`ki``s``si`k`ki`kk

Try it online!
No way this could be a contender for the shortest solution, but oh well. Prints indefinitely.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Finding Factorials with Gamma
Introduction
We know that the factorial notation is valid for all natural numbers. However, Euler had extended it for all positive real numbers, as well as for complex numbers by defining a function, which is known as the Gamma Function. It is represented by Γ.
Challenge
You will be given a non-negative floating point number, say 'n' (with a maximum of 2 decimal places in it), and you need to output the factorial of that number correct to at least 3 decimal places. Assume all inputs to be valid, and n <= 7.
Now talking about Gamma function, there is an integral which can be used to find the value of any factorial. You may choose to use it. You can find more information here. The Gamma function is recursive in nature. One important property, which would probably be useful to you is:
Γ(n) = (n-1)! , which means that, n! = Γ(n) . n
Also note that we really do not need to know Γ(n) for all values of n. For instance, look at the number 4.5 - we can write its factorial as:
4.5! = 4.5 * 3.5 * 2.5 * 1.5 * 0.5! = 59.0625 * 0.5!

So here we need only the value of 0.5! , which means the value of Γ(1.5). Also, similarly, we can find the factorial of any decimal if we know the values of factorials of numbers between 0 and 1, i.e, values of gamma function of numbers between 1 and 2. You need it, so that is why there is a table below for your help:

Using this table, we can see that 0.5!, i.e, the value of Γ(1.5) = 0.88623, which gives our result: (4.5)! = 59.0625 * 0.88623 = 52.3429594 , which is indeed a good result. Similarly,
(5.7)! = (5.7)*(4.7)*(3.7)*(2.7)*(1.7)*(0.7)! = 454.97457 * 0.90864 = 413.408093

Also, if you do not wish to use the table for calculating the gamma function, here is a simple integral to help you out:

Remember that you can provide your answers only up to 3 decimal places if you want to. But the value should have minimum error. Like, +- 0.003 is acceptable.
You are free to decide in what way you want to compute the factorial - whether by the integral, or by the table, or using any other method.
Examples
Please note that here the answer is correct to 3 decimal places.
2.4 -> 2.981
3.9 -> 20.667
2.59 -> 3.675
1.7 -> 1.545
0.5 -> 0.886

Scoring
This is code-golf, so the shortest code wins!

Please note that this challenge was posted on sandbox and people decided that this is not a dupe because this challenge allows built ins.

Can we output as a rational number (i.e fraction)? Like, 8275608925237915/2251799813685248 for the 3rd test case.

Sorry but as per the rules, decimal answers only

I interpreted "3 decimal places" to mean the leading digits, so "the relative error is < 1/1000". But your examples seems to imply 3 digits after the decimal point, which would be a relative error of 1/5040000 for 7! which is more accurate than your table. You can almost see this in your example of 5.7! where the correct result 413.40752 only juuust rounds to 413.408. It should be easy to find examples where it fails. Please clarify what you mean

@TonHospel well I meant 3 places after decimal.Also the table is very unlikely to fail.

Aww, I was about to extend Whispers' factorial notation to cover the gamma function, and it'll look like cheating if I add an answer now.

Since all built-in solutions are being combined in a single post, I consider this a duplicate of the Gamma challenge.

I think that near 7! the table is actually very likely to fail for 3 digits after .. And even if it didn't, you don't want to have to think about 1000.000499 vs 1000.000501 so you should really have asked for accuracy as a max absolute error

Community wiki for built-in solutions
This answer is intended to collect answers that are simply built-ins. It's a community wiki, so anybody can edit in without approval. Go ahead and include any built-in only solution here, following xnor's proposal and according to our consensus.
Jelly, 1 byte
!

Try it online!
J , 1 byte
!

Try it online!
2sable, 1 byte
!

Try it online!
Pyth, 2 bytes
.!

Try it online!
R, 9 bytes
factorial

Try it online!
Stax, 2 bytes
|F

Try and debug online!
Wolfram Language (Mathematica), 3 bytes
#!&

Try it online!

! is not a function in Mathematica, it is an operator, and hence is not a valid submission.

@totallyhuman Fixed.

Perl 5, -p 40 bytes
Very slow. One run takes about 13 minutes for me.
#!/usr/bin/perl -p
$\=5e8**++$_/$_;$\/=1+$'/$_ for//..5e8}{

Try it online!
The TIO link uses 1e7 instead of 5e8 to avoid timeouts and is therefore not accurate enough
Old version, -p 60 bytes, not accurate enough
Uses a Stirling approximation. But even with the first correction term that is pretty inaccurate for small n. So instead I approximate (n+2)!/(n+2)/(n+1).
Notice that I don't bother trying to get the first 3 digits right, but the relative error seems to properly be < 0.001 in the range [0, 7]. E.g. 0! outputs 0.999481433067179 which would be 1.000 if rounded to 3 digits.
#!/usr/bin/perl -p
$_=(($_+=2)/exp 1)**$_*(2+1/6/$_)/$_/($_-1)*sqrt$_*atan2 1,0

Try it online!

APL (Dyalog Unicode), 1 byte
!

Try it online!
In APL, the factorial primitive has always included the entire domain of the gamma function.

I've created a community wiki answer for built-in only answers following our consensus and xnor's proposal. You can transfer your solution there if you want, but feel free to keep it as-is otherwise.

Unsurprisingly, this also works in J.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Wanna be an Alchemist
Wanna be an Alchemist
I've been watching Full Metal Alchemist these past days and I've been wondering, It is really possible to trans-mutate matter? In the real world, I don't know if it is possible, but in the machine world, we think we "can".

Problem
Your task is, Given an input of N chemical elements (K, Mg, C, O, etc...), you are going to:

Get the first letter of the element
Convert that letter into binary
Rotate 2 bits to the right
Apply Binary Addition
If the result is more that 8 bits then get the one's complement of the result and removes the highest bit
Output the ASCII (ISO 8859-1) representation of the result

Example
Given Chemical Elements: (K, Ca, Mg)

Get the first letter of the element

K, C, M

Convert that letter into binary

K => 01001011, C => 01000011, M => 01001101

Rotate 2 bits to the right

K => 11010010, C => 11010000, M => 01010011

Sum bits
K => 11010010 +
 C => 11010000 +
 M => 01010011 = 111110101
If the result is more that 8 bits then get the one's complement and removes the highest bit

00001010

Output the ASCII representation of the result.
Result:

Test Cases
(H, Mn, C) =>  Ê

(I, H, Se) =>  Ç

(K, Ca, Mg) =>

This is code golf so the shortest answer wins

When you say "Convert that letter into binary" am I correct in thinking you mean using ASCII? Or is it ok to use EBDIC or UTF-32? :)

@AndrewPiliser ASCII. Sorry if i was misunderstood

This is a great idea! In the future though, if you have an idea but it isn't a complete challenge, or if you just need help, you can use the Sandbox.

The binary sum question needs addressing, the test cases don't work and the given link is about adding numbers that are represented in binary (which does not work out with the examples either). I am voting to close this as unclear in the interim (i.e. will vote to reopen when that is addressed).

@totallyhuman yuup, I really don't know why I thought I read that.

Step 3 of the problem and example don't match (shift discards bits, rotate keeps them). Also, your test cases are wrong because the problem requires "ASCII" and the result characters are not in the seven-bit character set known as ASCII (perhaps you want ISO 8859-1?)

I'd recommend changing "ASCII" to "Unicode" and remove the requirement to check whether the result is printable or not (allow the output to be the character, no matter what it is)

@Fox Sorry, I meant the Extended ASCII (ISO 8859) that includes 8 bits . About the shit, I meant rotate. I'll update my question

@cairdcoinheringaahing from 00000000 to 00011111 are non printable characters.

@LuisfelipeDejesusMunoz 1) That doesn't include all the non-printable characters and 2) it adds unnecessary overhead to the challenge, which isn't recommended

@cairdcoinheringaahing ok, so just removing that part will be ok?

Personally, I'd allow results with more than 8 bits to stay as they were (but that's up to you). If you remove the printable part, I'd definitely vote to reopen

Perl 5, 44 bytes
$n+=257*ord>>2&255}{$_=chr($n>>8?~$n%256:$n)

Try it online!

Python 2, 78 bytes
e=sum(ord(e[0])/4+ord(e[0])%4*64for e in input());print chr([e,~e][e>255]%256)

Try it online!
-8 bytes thanks to Jonathan Frech

An imperative function is shorter.

Python 2, 78 bytes.

@JonathanFrech oh thanks :D

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
We ended up where we started!…
Challenge:
Input:
You take two inputs:
- A string only containing printable ASCII (excluding spaces, tabs or new-lines)
- A printable ASCII character
Output:
The first line will contain the string-input. Every i-modulo-3 first occurrence of this character will move in a South-East direction; every i-modulo-3 second occurrence will move in a South direction; and every i-modulo-3 third occurrence will move in a South-West direction. You'll continue until the characters are about to be at their initial starting position again (which means it will wrap around from one side to the other if necessary), and then you'll print the last line with the string-input again to finish it. (Note that all test cases will end up at their initial input after at most length(input) rows, including the row containing the trailing input. It can be sooner though, as seen in this first test case below, with a length of 14, but ending after 9.)
This may all be pretty vague, so here an example:
Test case 1:
String-input: "This_is_a_test"
Character-input: 's'
Output:
This_is_a_test
    s s    s
     ss   s
      s  s
      sss
      sss
      s  s
     ss   s
    s s    s
This_is_a_test

Here is the same test case with the colored paths of the three s:

where the first 's' follows the green path in a South-East direction; the second 's' follows the yellow path in a South direction; and the third 's' follows the light blue path in a South-West direction. (If there would be a fourth 's' it would go in a South-East direction again, which can be seen in some of the other test cases below.)
Challenge rules:

The inputs will only contain printable ASCII (excluding spaces, tabs and new-lines)
I/O formats are flexible. Can be a new-line delimited string, character matrix, etc. Your call.
It is possible that the given character isn't present in the string, in which case you are allowed to either output the input-string once or twice (i.e. "test", 'a' can have either of these as possible output: "test\ntest"/"test").
Leading spaces are mandatory; trailing spaces are optional. One or multiple leading/trailing new-lines are allowed.

General rules:

This is code-golf, 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, 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.
Also, please add an explanation if necessary.

Test cases / more examples:
Test case 2:
String-input: "abcabcabcabcabc"
Character-input: 'b'
Output:
abcabcabcabcabc
  b b b    b b
   bbb      bb
    b        b
   bbb       bb
b b b b      b
 b  b  b     b
b b b   b    b
   bb    b   bb
    b     b  b
    bb     bbb
    b b    bbb
    b  b  b  b
    b   bb   bb
b   b   bb   b
abcabcabcabcabc

Here is the same test case with the colored paths of the five a:

Test case 3:
String-input: "only_two_paths?"
Character-input: 'o'
Output:
only_two_paths?
 o     o
  o    o
   o   o
    o  o
     o o
      oo
       o
       oo
       o o
       o  o
       o   o
       o    o
       o     o
       o      o
only_two_paths?

Here is the same test case with the colored paths of the two o:

Test case 4:
String-input: "lollollollollol"
Character input: 'l'
Output:
lollollollollol
lll   ll  ll
 ll   ll  ll
l ll ll ll ll
  lll l ll l ll
  llllll  ll ll
l l  ll    ll
 ll  lll   ll
l l l lll ll l
  ll  l ll l  l
l l l l llll l
 ll  lll  lll
l l   l    ll
  ll lll  lllll
  l l l ll l ll
lollollollollol

Here is the same test case with the colored paths of the ten l:

Test case 5:
String-input: "AbCdEeDcBaAbCdEeDcBa_CCCCC"
Character input: 'C'
Output:
AbCdEeDcBaAbCdEeDcBa_CCCCC
C  C        C       C  C
 C  C       C      C  CCC
  C  C      C     C  C C C
C  C  C     C    C  C  C
 C  C  C    C   C  C   C
  C  C  C   C  C  C    C
   C  C  C  C C  C     C
    C  C  C CC  C      C
     C  C  CC  C       C
      C  C CC C        C
       C  C CC         C
        CC CC C        C
        CC CC  C       C
       C  C CC  C      C
      C  C CC C  C     C
     C  C   C  C  C    C
    C  C    CC  C  C   C
   C  C     C C  C  C  C
  C  C      C  C  C  C C
 C  C       C   C  C  CC
C  C        C    C  C  C
  C         C     C  C CCC
 C          C      C  CCCC
C           C       C  C
 C          C        CCCCC
AbCdEeDcBaAbCdEeDcBa_CCCCC

Here is the same test case with the colored paths of the seven C:

Test case 6:
String-input: "XyX"
Character input: 'X'
Output:
XyX
 XX
  X
XyX

Here is the same test case with the colored paths of the two X:

Test case 7:
String-input: "aaaa"
Character input: 'a'
Output:
aaaa
aa
aaa
 aaa
aaaa

Here is the same test case with the colored paths of the four a:

So when the string contains a multiple of 3 of the character, the output might have fewer rows than the length of the string?

@Neil I'm not sure if it's a multiple of 3, haven't investigated it that much. All I know is that at most length(input) everything matches up again, but it can be sooner as the first test case proves. But it seems you're indeed right about the multiple of 3 part (although I'm not 100% sure).

@Neil any string with the character appearing only 3 times in a row will print 3 lines however long it is

Are trailing new lines allowed between 2 printed lines?

@AsoneTuhid Sorry but no. I don't care about any amount of trailing or leading new-lines before or after the entire expected output, but I won't allow in between lines. The diagonal lines wouldn't be correct anymore as well..

I would agree, was just asking to make sure.

Stax, 24 bytes
»v↕*δó‼Γ█|q┬YM╨|·£↕fßßZo

Run and debug it online
This is the ascii representation of the same program.
YxP|Ic{{i3%v-x%%mb-!Czny&PWxP

It gets the indices of all the character, and then mutates them until they are set-wise equal to the original indices.  For every change, output a string with the character at those indices.
Y                               Store character in y.  Now the inputs are x and y.
 xP                             Print x.
   |Ic                          Get all indices of y in x. Make a copy.
      {                   W     Loop until cancelled.
       {        m               Map index array using block.
        i3%v-                   Subtract i%3-1 from each element. i is the loop index.
             x%%                Modulo len(x)
                 b-!            Is the mutated array set-equal to the original?
                    C           If so, cancel W loop
                     zny&P      Print a string with y at all specified indices
                           xP   Finally, print x again

Perl 5, -plF 101 100 99 98 97 96 bytes
Replace the \0 by a literal 0 byte to get 96. Notice that the Try It Online link has 97 bytes because it doesn't seem possible to input a literal 0 character there.
#!/usr/bin/perl -plF
say;say$$l=~y/\0/ /runtil--$l,(s:\Q${\<>}:$$l|=v0 x((++$#$l%3*$l-$l+"@-")%@F).$&;v0:oreg^$$l)eq$_

The code golf perl highlighter thinks # start a comment. How naive
Try it online!
How it works
$l is a counter for which line after the first we are on (it counts down though, so e.g. -3 for 3 lines below the top string).After printing the initial string once it repeatedly does the following.
Search the first string for occurrences of the target character and calculate at which offset it should appear: (++$#$l%3*$l-$l+"@-")%@F which is the current position plus the line number (negative) times -1, 0, 1 (cyclic). Construct a string with that many times \0 followed by the target character and or that into an accumulator $$l (that is a different accumulator for each $l and the reason $l counts down instead of up because $1, $2 etc are read-only). Simularly $#$l refers to a different array each time through the loop. The result is the $lth line but with \0 instead of spaces.
The target charcters in the first string are replaced by \0 so you end up with the original string with "holes" (with \0)  at the original positions of the target character. If you xor that with the accumulator the holes get filled if and only if the accumulator has the target characters in the original positions, so the result will be the original string. That is used to terminate the loop. If the loop is not finished yet print the accumulator with \0 replaced by space.
When the loop ends the -p option once more prints the first string and the program is done.
The target character is picked up in a rather tricky way. The ${\<>} converts a line read from STDIN to a reference which is then immediately dereferenced and substituted in the regex. The \Q prefix escapes all characters that are special in a regex (like . and *). The \E is implicit. The o modifier causes the search part to never be evaluated again but just repeated in all subsequent matches (which is good since there is nothing on STDIN anymore).

I don't think you can put a null byte directly, but you could run it in bash or something.

@FryAmTheEggman Thanks, that's a nice dodge. But I don't think I will bother. People will just have to trust me that that works if they don't want to try it out themselves :-)

Completely fair, but I'll leave the comment so people can see it. Nice golf, by the way :)

Python 2, 199 193 191 bytes
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
 j=[(j[i]-i%3+1)%l for i in r(len(I))]
 if sorted(j)==I:print s;break
 print''.join((' '+c)[i in j]for i in r(l))

Try it online!

If the loop can exit via exception:
Python 2, 187 bytes
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
 j=[(j[i]-i%3+1)%l for i in r(len(I))]
 if sorted(j)==I:print s;q
 print''.join((' '+c)[i in j]for i in r(l))

Try it online!

-4 bytes thanks to Jonathan Frech
-2 bytes thanks to Lynn

Possible 189 bytes (exiting the loop via an exception).

You can drop a pair of parens in (j[i]-i%3+1)%l for two bytes.

Ruby, 189 176 171 156 150 146 144 137 bytes
->s,c,r=0..k=s.size,b=[p,s]{d=0;g=s.tr c,n=' '*k;l=r=r.map{|i|l||c==s[i]?(n[z=(i+1-d%3)%k]=g[z]=c;d+=1;z):p}-b;g==s||b<<n&&redo;puts b,s}

Try it online!

JavaScript (Node.js), 197 194 bytes
s=>c=>{(C=console.log)(s);w=0;g=[];while(~(w=s.indexOf(c,w)))g.push(w++);h=(H=_=>g.map(x=>A[x]=c,A=Array(l=s.length).fill` `)&&A.join``)();while(h!=(y=H(g=g.map((x,i)=>(l-~x-i%3)%l))))C(y);C(s)}

Try it online!
Takes inputs in currying syntax, i.e. f(s)(c).
Not a perfect one at all, but I need JS. A lot of functions in function.

C (gcc), 261 bytes
i,j,l,k;g(L,t,r,c)char**L;{L[r++][c]=k;c-=t?t-1?:0:-1;l<r||g(L,t,r,c<0?l-1:c%l);}f(S,K){char*s=S,*L[i=1+(l=strlen(s))];for(k=K;i--;)for(L[i]=calloc(j=l,1);j--;)L[i][j]=32;for(puts(s);s[++i];)s[i]-k||g(L,++j%3,0,i);for(i=1;strcmp(*L,L[i]);)puts(L[i++]);puts(s);}

Try it online!

Jelly, 33 bytes
3ḶNṁ+%⁹L¤‘
Ṅẹ©¥@ÇÇṢ⁻®ƊÐ¿Ṭị;⁶¥ṖY,Y

Try it online!

Call as a function. (dyadic link)
I found some 33-byte alternatives, but no actual improvement.


text:
Some Lonely Primes
I know, I know, yet another primes challenge...
Related
A lonely (or isolated) prime is a prime number p such that p-2, p+2, p-4, p+4 ... p-2k, p+2k for some k are all composite. We call such a prime a kth-times-isolated prime.
For example, a 5th-times-isolated prime is 211, since all of 201, 203, 205, 207, 209, 213, 215, 217, 219, 221 are composite. (p-2*5=201, p-2*4=203, etc.)
Challenge
Given two input integers, n > 3 and k > 0, output the smallest kth-times-isolated prime that is strictly larger than n.
For example, for k = 5 and any n in range 4 ... 210, the output should be 211, since that's the smallest 5th-times-isolated prime strictly larger than the input n.
Examples
n=55 k=1
67

n=500 k=1
503

n=2100 k=3
2153

n=2153 k=3
2161

n=14000 k=7
14107

n=14000 k=8
14107

Rules

If applicable, you can assume that the input/output will fit in your language's native Integer type.
The input and output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Is a 3rd-times-isolated prime also a 2nd-times-isolated prime?

@EriktheOutgolfer The last two test cases indeed seems to confirm that.

@KevinCruijssen Test cases are not a part of the challenge specification.

@EriktheOutgolfer Yes, a kth-times-isolated is also, by definition, a k-1th, k-2th, etc.

@AdmBorkBork Just wanted to check, thanks.

@l4m2 2 here is a special case because it's infinitely isolated by this definition, which is why I'm starting with n>3.

ok it doesn't matter. The smallest result 5 with k=2 go to 9

Jelly, 17 13 bytes
_æR+⁼ḟ
‘ç1#Ḥ}

Try it online!
How it works
‘ç1#Ḥ}  Main link. Left argument: n. Right argument: k

‘       Increment; yield n+1.
    Ḥ}  Unhalve right; yield 2k.
 ç1#    Call the helper link with arguments m = n+1, n+2, ... and k until 1 one
        them returns a truthy value. Return the matching [m].

_æR+⁼ḟ  Helper link. Left argument: m. Right argument: k

_       Subtract; yield m-2k.
   +    Add; yield m+2k.
 æR     Prime range; yield the array of primes in [m-2k, ..., m+2k].
     ḟ  Filterfalse; yield the elements of [m] that do not occur in [k], i.e., [m]
        if m ≠ 2k and [] otherwise.
        The result to the left will be non-empty when m = 2k, as there always is
        a prime in [0, ..., 2m], since m > n > 3.
    ⁼   Test the results to both sides for equality.
        This yields 1 iff m is the only prime in [m-2k, ..., m+2k].

Husk, 13 bytes
ḟ§=;ofṗM+ṡD⁰→

Try it online!
Explanation
Pretty straightforward.
ḟ§=;ofṗM+ṡD⁰→  Inputs are k and n.
            →  Increment n
ḟ              and find the first number m >= n+1 such that:
         ṡD⁰    Take symmetric range [-2k,..,2k].
       M+       Add m to each.
    ofṗ         Keep those that are prime.
 §=             Check equality with
   ;            the singleton [m].

Java 8, 144 143 bytes
(n,k)->{for(k*=2;;)if(p(++n)>1){int i=-k;for(;i<=k&p(n+i)<2|i==0;i+=2);if(i>k)return n;}}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

Explanation:
Try it online.
(n,k)->{                      // Method with two integer parameters and integer return-type
  for(k*=2;                   //  Multiply `k` by 2
      ;)                      //  Loop indefinitely
    if(p(++n)>1){             //   Increase `n` by 1 before every iteration with `++n`
                              //   And if it's a prime:
      int i=-k;for(;i<=k      //    Loop `i` from `-k` to `k` (inclusive)
        &p(n+i)<2|i==0;       //    As long as `n+i` is not a prime (skipping `n` itself)
        i+=2);                //    And iterate in steps of 2 instead of 1
      if(i>k)                 //    If we've reached the end of the loop:
        return n;}}           //     We've found our result, so return it

// Separated method to check if `n` is a prime
// `n` is a prime if it remained unchanged, and not when it became 0 or 1
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

JavaScript (Node.js), 94 92 89 bytes
f=(n,k)=>(Q=y=>y<-k||(P=(a,b=2)=>a>b?a%b&&P(a,b+1):1)(n+2*y)^!!y&&Q(--y))(k,++n)?n:f(n,k)

Try it online!
Mysteriously, further golfs end up stack overflow. Only this works at the size of 14000.
Finally one golf that won't end up stack overflow at 14000.
Explanation
f=(n,k)=>            // Two inputs
 (Q=y=>              // Function checking whether all numbers in
                     // [n-2*k, n+2*k] except n are all composite
  y<-k               // The counter runs from k to -k
                     // If none breaks the rule, return true
  ||(P=(a,b=2)=>     // Function checking primality
   a>b?              // Check if a>b
   a%b&&P(a,b+1)     // If a>b and a%b==0 return false, else proceed
   :1                // If a<=b return 1 (prime)
  )(n+2*y)^!!y       // If n+2*y is prime, then y must be 0
                     // If n+2*y is not prime, then y must be non-zero
                     // If none of the conditions are met, return false
  &&Q(--y)           // Else proceed to the next counter
 )
 (k,++n)?            // Add 1 to n first, then start the check
 n                   // If conditions are met, return n
 :f(n,k)             // Else proceed to the next n.

Python 2, 105 104 bytes
-1 byte thanks to ovs

n,k=input()
n+=1
while sum(all(x%i for i in range(2,x))^(x==n)for x in range(n-k*2,2*k-~n)):n+=1
print n

Try it online!

Stax, 14 bytes
åΣ▀ë F▬&■º↔╔^∞

Run and debug it
This is the corresponding ascii representation.
w^x:r{Hn+|p_!=m0#

w                   while; run the rest of the program until a falsy value remains
 ^                  increment candidate value.
  x:r               [-x, ..., -1, 0, 1, ... x] where x is the first input
     {        m     map using block, using k from -x to x
      Hn+           double and add to candidate value - this is "p+2k"
         |p         is it prime? produces 0 or 1
           _!       k is zero?
             =      two values are equal; always true for a passing candidate
               0#   any falses left after mapping? if so, continue running

Ruby + -rprime, 73 71 61 57 bytes
->n,k{n+=1;(-k..k).all?{|i|(i*2+n).prime?^(i!=0)}?n:redo}

Try it online!
It feels good to be learning! I'm using the Integer#[] and redo techniques that I learned here on PPCG. getting lost in the weeds of fun techniques...
-1 byte: Use n%2 instead of n[0] to get the least significant bit. Thanks, Asone Tuhid!
-1 byte: Use a ternary operator instead of a boolean expression. Thanks, Asone Tuhid!
-10 bytes: Use the XOR operator to avoid typing out .prime? twice... This is just as much Asone Tuhid's answer as mine now :)
-4 bytes: There's no harm in checking even values of n. Asone Tuhid is non-stop.
Ungolfed:
->n,k{
  n += 1;                   # Increment n
  (-k..k).all?{|i|          # In the set [n-2*k, n+2*k], is every number
    (i*2+n).prime? ^ (i!=0) #    EITHER prime XOR different from n itself?
  } ? n                     # If yes, return the current value of n
  : redo                    # Otherwise, restart the block
}

Flags no longer need to be included in the byte count. Each separate invocation of a flag is instead considered a different language. So this answer should instead be Ruby + -rprime, 73 bytes

Oh lovely! Thanks for keeping me up to date on the meta, @Mr.Xcoder.

71 bytes. n%2 is shorter than n[0] in this case and ?...: can be shorter than &&...||

-10 bytes :)

@AsoneTuhid Very nice!

this one's small but it turns out "n%2+" was useless

C (gcc), 113 bytes
P(n,d,b){for(b=d=n>1;++d<n;)b=b&&n%d;n=b;}f(n,k,i,f){for(f=n;f;)for(f=i=!P(++n);i++<k;f|=P(n+i+i)|P(n-i-i));f=n;}

Try it online!

Pari/GP, 55 bytes
f(n,k)=until(isprime(n++)&&#primes([n-2*k,n+2*k])<2,);n

Try it online!

Perl 6, 63 bytes
{$^k;first {[grep *.is-prime,$_-2*$k..$_+2*$k]eqv[$_]},$^a^..*}

Try it online!


text:
Convergence of a Markov Process
Challenge
Given a left- or right-stochastic matrix where the limit as x approaches infinity of the matrix to the power of x approaches a matrix with all finite values, return the matrix to which the matrix converges. Basically, you want to keep multiplying the matrix by itself until the result no longer changes.
Test Cases
[[7/10, 4/10], [3/10, 6/10]] -> [[4/7, 4/7], [3/7, 3/7]]
[[2/5, 4/5], [3/5, 1/5]] -> [[4/7, 4/7], [3/7, 3/7]]
[[1/2, 1/2], [1/2, 1/2]] -> [[1/2, 1/2], [1/2, 1/2]]
[[1/3, 2/3], [2/3, 1/3]] -> [[1/2, 1/2], [1/2, 1/2]]
[[1/10, 2/10, 3/10], [4/10, 5/10, 6/10], [5/10, 3/10, 1/10]] -> [[27/130, 27/130, 27/130], [66/130, 66/130, 66/130], [37/130, 37/130, 37/130]]
[[1/7, 2/7, 4/7], [2/7, 4/7, 1/7], [4/7, 1/7, 2/7]] -> [[1/3, 1/3, 1/3], [1/3, 1/3, 1/3], [1/3, 1/3, 1/3]]

Rules

Standard Loopholes Apply
You may choose whether you want a right- or a left-stochastic matrix
You may use any reasonable number type, such as floats, rationals, infinite precision decimals, etc
This is code-golf, so the shortest submission in bytes for each language is declared the winner for its language. No answer will be accepted

@FryAmTheEggman it seems like some earlier comments have been deleted, so this might be redundant, but reducible and periodic matrices are already excluded by "Given a left- or right-stochastic matrix where the limit as x approaches infinity of the matrix to the power of x approaches a matrix with all finite values", which I read as saying the input is guaranteed to converge to a unique solution. (i.e. the input matrix is guaranteed to be ergodic.)

@Nathaniel That isn't quite true, as if the chain is reducible you can have a result (like for the identity matrix) that meets what you said but the chain it describes is not irreducible and therefore the input wouldn't be guaranteed to be ergodic (since it won't be positive recurrent). Guaranteeing ergodicity is what the OP wants, and I think they have that now, thanks to the additional constraint of all of the row values being identical. If you know a better way to constrain the input without needing to add an explanation of Markov chains, I'm sure HyperNeutrino would appreciate it! :)

@FryAmTheEggman ah, you're right, sorry. I was thinking of power iteration rather than raising the matrix to a power. (So by "unique solution" I meant "one that's independent of the starting point of the iteration process", but that's not relevant here.) I agree that the 'all rows are identical' condition does the job. I suppose the OP could just say "the Markov chain is guaranteed to be ergodic," which would satisfy people like us who are likely to worry about it!

Actually, if B is a solution to BA = B, then so is cB for any scalar constant c. So a non-zero solution cannot be strictly unique, unless you somehow fix the scale. (Requiring B to be stochastic would do it.) Also, obviously, whether its the rows or the columns of B that are equal will depend on whether A is left or right stochastic.

@IlmariKaronen that's a good point. I'll just remove that because that's not really a formal spec, more so just a way of thinking about it, but based on current answers all of them seem to get how to do it

For anyone else who never learned about matrices during Math-class in high school and how to multiply them: https://www.mathsisfun.com/algebra/matrix-multiplying.html. I had to look it up to understand what was being asked.. Maybe it's common knowledge elsewhere on Earth.. :S

@KevinCruijssen oh yeah whoops I just kind of assumed that everyone knew how to do matrix-matrix multiplication :P sorry. I learned it in grade 10 as one of the advanced placement units but idk when they actually teach it in standard curriculum

So, the rules mean i can't use BigDecimal types? (Infinite precision decimal)

@moonheart08 that was added by martin; I'll change it to allow all reasonable number types

Thanks. I'm going to make a noncompeting (QUARK isn't done yet, i'm just adding the finishing touches needed to do this challenge at all) answer, and I wouldn't be able to use QUARK if I couldn't use infinite precision decimal (the only number type allowed) \o/

@moonheart08 BTW just to clarify, you can't submit invalid answers even as "noncompeting"; that word isn't meaningful here anymore

Oh, Huh. So that changed. RIP

R,  44  43 bytes
function(m){X=m
while(any(X-(X=X%*%m)))0
X}

Try it online!
Just keeps multiplying until it finds a fixed matrix. Apparently X!=(X=X%*%m) does the comparison, then reassigns X, so that's neat.
Thanks to @Vlo for shaving off a byte; even though crossed out 44 is still regular 44.

I wonder why function(m){ while(any(m!=(m=m%*%m)))0 m} doesn't work. Numerical inaccuracies preventing the termination condition from triggering?

@CodesInChaos most likely it's a lack of precision. Switching to an arbitrary precision library doesn't help, either -- they either time out (Rmpfr) or fail (gmp) in the same manner, although I'm probably doing something wrong.

@Giuseppe I guess the suggested approach is repeated squaring until no longer changes? (I can't read R)

@user202729 yeah it is. R uses 64-bit floating point numbers and I know errors propogate pretty quickly.

I think that algorithm is unstable. Jelly has the same problem too. (TODO prove this and find an alternative)

Save one byte by replacing != with -. Spooky how the code doesn't work without defining m. Might post to overflow to check with some Rxpert.

@Vlo ah good call. If you do post to SO, I'd love a link here so I can read the discussions myself :)

https://stackoverflow.com/questions/49180576/what-is-going-on-with-floating-point-precision-or-perhaps-primitiveany

Octave, 45 42 35 bytes
@(A)([v,~]=eigs(A,1))/sum(v)*any(A)

Try it online!
Saved 3 bytes thanks to Giuseppe, and 7 more thanks to Luis Mendo!
This uses that the eigenvector corresponding to the eigenvalue 1 (also the maximum eigenvalue) is the column vector that is repeated for each value of the limiting matrix. We have to normalise the vector to have sum 1 for it to be stochastic, then we simply repeat it to fill out the matrix. I'm not too well versed in golfing Octave, but I haven't been able to find a functional way to do repeated multiplication, and a full program seems like it will always be longer than this.
We can use any(A) since from the restrictions we know that the matrix must describe an irreducible Markov chain, and so each state must be reachable from the other states. Therefore at least one value in each column must be non-zero.

How does eigs always return the eigenvector corresponding to 1? My memory of markov chains is a bit fuzzy.

42 bytes

@Giuseppe Because the matrix is stochastic, and a couple other things, its maximum eigenvalue is 1, and eigs returns starting from the largest eigenvalue. Also, thanks for the golf!

Ah, right. Markov chains are on my next exam but since it's for actuaries, some of the details are entirely missing.

Wolfram Language (Mathematica), 14 bytes
Output floats:
N@#//.x_:>x.#&

Try it online!

Wolfram Language (Mathematica), 30 bytes
Output fractions:
Limit[#~MatrixPower~n,n->∞]&

Try it online!

Jelly, 6 bytes
æ×³$ÐL

This is a full program.
Try it online!

APL (Dyalog), 18 6 bytes
12 bytes saved thanks to @H.PWiz
+.×⍨⍣≡

Try it online!

+.×⍨⍣≡ for 6 bytes. That is, square until nothing changes

@H.PWiz I believe it is. I have no idea why I hadn't done it in the first place. Thanks!

C (gcc), 207 192 190 181 176 bytes + 2 flag bytes -lm

Saved fifteen seventeen twenty-two bytes thanks to ceilingcat.
Saved nine bytes; removing return A;.

float*f(A,l,k,j)float*A;{for(float B[l*l],S,M=0,m=1;fabs(m-M)>1e-7;wmemcpy(A,B,l*l))for(M=m,m=0,k=l*l;k--;)for(S=j=0;j<l;)m=fmax(m,fdim(A[k],B[k]=S+=A[k/l*l+j]*A[k%l+j++*l]));}

Try it online!

@ceilingcat Counting the compiler flag bytes, this results in 192 again. Included your suggestion nonetheless.

@ceilingcat Thank you.

k/q, 10 bytes
k/q because the program is identical in both languages. The code is really just idiomatic k/q.
{$[x]/[x]}

Explanation
{..} is out lambda syntax, with x as an implicit parameter
$[x] has $ as the binary matrix multiplication operator, providing only one parameters creates a unary operator that left multiplies by the Markov Matrix
/[x] applies the left multiplication until convergence, starting with x itself.

Python 3, 75 61 bytes
f=lambda n:n if allclose(n@n,n)else f(n@n)
from numpy import*

Try it online!
In test cases there are float inaccuracies, so the values may differ by a bit from the exact fractions.
PS. numpy.allclose() is used because numpy.array_equal() is longer and prone to float inaccuracies.
-14 bytes Thanks HyperNeutrino ;) Oh yes I forgot the @ operator ;P

Use dot instead of matmul :D

Actually, take numpy arrays as input and do x=n@n :P https://tio.run/##lVDBasMwDL33KwS7xCPgxk5iaCnsP4wPYYtZIHGCm0Ly9Zlkt01Tytgu0pP8niy9YR6/eyeXxfq@A3fphhmabuj9@L77qi3YxLHDdHIf7jj4xo1YNhaqtv1s@3OdTKljdXuukTexxSaV99WcaK14tk8hx2hS0DJUJVWGMXgDrXOu6F3FZ8QYjNmtEwQviFBEAuIM8Z/VGRekEES445v69eNGLVMQXBJBEMbGf9R0rQhRXh3IQ1WsPmCvuDNoxoM3At2TNGKTSVKWsbPNwYUrd5uf9lK01urcDdP3Km4ZcaA9HBwdiDaEq39tmOUH

59 bytes

Added back the f= at front because it is recursively called ;)

Oh yeah you're right :) good call!

Java 8, 356 339 bytes
import java.math.*;m->{BigDecimal t[][],q;RoundingMode x=null;for(int l=m.length,f=1,i,k;f>0;m=t.clone()){for(t=new BigDecimal[l][l],i=l*l;i-->0;)for(f=k=0;k<l;t[i/l][i%l]=(q!=null?q:q.ZERO).add(m[i/l][k].multiply(m[k++][i%l])))q=t[i/l][i%l];for(;++i<l*l;)f=t[i/l][i%l].setScale(9,x.UP).equals(m[i/l][i%l].setScale(9,x.UP))?f:1;}return m;}

-17 bytes thanks to @ceilingcat.
Definitely not the right language.. Damn floating point precision..
Explanation:
Try it online.
import java.math.*;     // Required import for BigDecimal and RoundingMode
m->{                    // Method with BigDecimal-matrix as both parameter and return-type
  BigDecimal t[][],q;   //  Temp BigDecimal-matrix
  RoundingMode x=null;  //  Static RoundingMode value to reduce bytes
  for(int l=m.length,   //  The size of the input-matrix
          f=1,          //  Flag-integer, starting at 1
          i,k;          //  Index-integers
      f>0;              //  Loop as long as the flag-integer is still 1
      m=t.clone()){     //    After every iteration: replace matrix `m` with `t`
    for(t=new BigDecimal[l][l],
                        //   Reset matrix `t`
        i=l*l;i-->0;)   //   Inner loop over the rows and columns
      for(f=k=0;        //    Set the flag-integer to 0
          k<l           //    Inner loop to multiply
          ;             //      After every iteration:
           t[i/l][i%l]=(q!=null?q:q.ZERO).add(
                        //       Sum the value at the current cell in matrix `t` with:
             m[i/l][k]  //        the same row, but column `k` of matrix `m`,
             .multiply(m[k++][i%l])))
                        //        multiplied with the same column, but row `k` of matrix `m`
        q=t[i/l][i%l];  //     Set temp `q` to the value of the current cell of `t`
    for(;++i<l*l;)      //   Loop over the rows and columns again
      f=t[i/l][i%l].setScale(9,x.UP).equals(m[i/l][i%l].setScale(9,x.UP))?
                        //    If any value in matrices `t` and `m` are the same:
         f              //     Leave the flag-integer unchanged
        :               //    Else (they aren't the same):
         1;}            //     Set the flag-integer to 1 again
  return m;}            //  Return the modified input-matrix `m` as our result

Why is the main function so verbose?

@user202729 Because float/double don't have the proper floating point precision, java.math.BigDecimal should be used instead. And instead of simply +-*/, BigDecimals use .add(...), .subtract(...), .multiply(...), .divide(...). So something as simply as 7/10 becomes new BigDecimal(7).divide(new BigDecimal(10)). In addition, the ,scale,RoundingMode in the divide are required for values with 'infinite' decimal values (like 1/3 being 0.333...). The main method can of course be golfed, but I didn't bother when I did a search&replace to convert the floats to BigDecimals.

@ceilingcat Thanks!