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.