.+,(.+)
1$&$*0;$&$*11;$1$*,1,
+`1;1*,(((1)|,)*)
;$1$#3$*1,
+`^(1+)0
$1$1
r`\2;;(1*,)*(1*),$
1
Try it online! Link includes test cases. Explanation:
.+,(.+)
1$&$*0;$&$*11;$1$*,1,
Create 2ⁿ
in binary, n+1
in unary, then a list of k
0
s and a 1
.
+`1;1*,(((1)|,)*)
;$1$#3$*1,
Repeat n+1
times, drop the first element of the list, and append the sum of the remaining elements. This calculates the n+1
th k-bonacci number.
+`^(1+)0
$1$1
Convert the 2ⁿ
from binary into unary.
r`\2;;(1*,)*(1*),$
Subtract the n+1
th k-bonacci number from 2ⁿ
.
1
Convert to decimal.
Rather than trying to count the number of n
coin tosses with at least k
tails in a row, it's easier to consider the number of n
coin tosses that do not have k
tails in a row. By considering them grouped by the number of tails that they end with, it's possible to determine a recurrence relation for the number of rows. For example, with k=3
:
- For
0
coin tosses, 1
ends in 0
tails, 0
end in 1
tails, and 0
end in 2
tails. Total 1
matching row.
- For
1
coin toss, 1
ends in 0
tails, 1
ends in 1
tails, and 0
end in 2
tails. Total 2
matching rows.
- For
2
coin tosses, 2
end in 0
tails, 1
ends in 1
tails, and 1
ends in 2
tails. Total 4
matching rows.
- For
3
coin tosses, 4
end in 0
tails, 2
end in 1
tails, and 1
ends in 2
tails. Total 7
matching rows.
- For
4
coin tosses, 7
end in 0
tails, 4
end in 1
tails, and 2
end in 2
tails. Total 13
matching rows.
- For
n
coin tosses:
- The number that end in
0
tails is the total for n-1
coin tosses, since the value is simply that plus an extra toss of heads.
- The number that end in
1
tails is the number that end in 0
tails for n-1
coin tosses, with each row having an extra toss of tails. However, this is also the total for n-2
coin tosses.
- The number that end in
2
tails is the number that end in 1
tails for n-1
coin tosses, with each row having an extra toss of tails. Recursively, we see that this is also the total for n-3
coin tosses.
- The total is the sum of these which is also the total of the previous three totals. Thus, this forms a
3
-binacci sequence.
In general, the number of n
coin tosses that do not have k
tails in a row is a k
-binacci sequence.
The number of n
coin tosses with at least k
tails in a row plus the number of n
coin tosses that do not have k
tails in a row is of course the total possible number of rows, 2ⁿ
.