-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
KolakoskiSequence.cs
46 lines (42 loc) · 1.13 KB
/
KolakoskiSequence.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Sequences;
/// <summary>
/// <para>
/// Kolakoski sequence; n-th element is the length of the n-th run in the sequence itself.
/// </para>
/// <para>
/// Wikipedia: https://en.wikipedia.org/wiki/Kolakoski_sequence.
/// </para>
/// <para>
/// OEIS: https://oeis.org/A000002.
/// </para>
/// </summary>
public class KolakoskiSequence : ISequence
{
/// <summary>
/// Gets Kolakoski sequence.
/// </summary>
public IEnumerable<BigInteger> Sequence
{
get
{
yield return 1;
yield return 2;
yield return 2;
var queue = new Queue<int>();
queue.Enqueue(2);
var nextElement = 1;
while (true)
{
var nextRun = queue.Dequeue();
for (var i = 0; i < nextRun; i++)
{
queue.Enqueue(nextElement);
yield return nextElement;
}
nextElement = 1 + nextElement % 2;
}
}
}
}