How many possible combinations of two digits, with one of the two only repeating, respectively, $\max x$ and $\max y$ consecutive times

combinatorics

I'm having difficulties solving a programming problem, which implies finding the number of combinations of length $n$ that only use the digits $1$ and $2$ in a maximum of $x$, respectively, $y$ consecutive times.

The length of a combination is defined as the number of digits it consists of.

E.G.:

  • Find the combinations of length $3$, where the digit $1$ doesn't repeat more than $2$ times in a row and the digit $2$ doesn't repeat more than $1$ time in a row.

    Answer: 4

    Explanation: The following sequences can be created using the rule above: 112, 121, 211, 212

Please explain the forumla of this concept. Thank you!

Best Answer

This question is very hard to solve analytically, however, I believe it is a problem on dynamic programming.

Let's say we have two arrays X and Y of sizes $x$ and $y$. X[i] will contain the number of sequences that end with i+1 ones (if indexing starts with 0). Similarly, Y[i] will contain the number of sequences that end with i+1 twos.

Let's say $x=2$ and $y=3$. We start with arrays X=[1,0] and Y=[1,0,0]. It corresponds that we have only 1 sequence of length $n=1$ ending with 1 and 1 sequence of length $n=1$ ending with 2.

For each sequence that ends with 1 we can append 2 to get proper sequence (and vice versa). However, for each sequence that ends in 1 we can append 1 only if the number of 1s is less than $x$.

Thus, the rules of transitions are:

dX[0] = sum of Y
dY[0] = sum of X

for i from 1 to x-1:
    dX[i] = X[i-1]
for i from 1 to y-1:
    dY[i] = Y[i-1]

for i from 0 to x-1:
    X[i] += dX[i]
for i from 0 to y-1:
    Y[i] += dY[i]

This is outline of the code. Implementation might be more efficient.