I have this programming prompt where I have been asked to find the number of permutations of a 32 coin toss sequence that do not have three consecutive heads in a row.
I have been tasked to find this with dynamic programming and I am having a hell of a time trying to figure out the recursive algorithm.
I have tried a two variable approach where I try and keep track of whether the previous two flips were heads or tails and then incrementing based upon that. I have also tried breaking it into sub-problems where I start with a singular toss and then work my way up the full 32 tosses.
And I'm having a hard time visualizing how to approach this and figuring out how to keep track of everything as the algorithm commences.
Any help would be greatly appreciated.
Let $x(n)$ be the number of $n$-terms sequences of heads and tails, avoiding three consecutive heads.
The goal is to compute $x(32)$ via dynamic programming.
I'll do it in two different ways . . .
Method $(1)$:$\;1$-variable recursion.
By direct calculation, $$x(0)=1,\;\;x(1)=2,\;\;x(2)=4$$ and for $n \ge 3$, we get $$x(n)=x(n-1)+x(n-2)+x(n-3)$$ Explanation:
Call a sequence of heads and tails "qualifying" if it avoids three consecutive heads.
Assuming $n \ge 3$, an $n$-term sequence of heads and tails is qualifying if and only if it has one of the forms \begin{align*} &Ts'\\[4pt] &HTs''\\[4pt] &HHTs'''\\[4pt] \end{align*} where $s',s'',s'''$ are qualifying sequences of lengths $n-1,n-2,n-3$, respectively.
Based on the above recursion, we get the following dynamic program, expressed as pseudocode . . .
Method $(2)$:$\;2$-variable recursion.
We have $x(n) = f(0,n)$, where $f(h,n)$ is the number of qualifying $n$-term sequences, assuming $h$ consecutive heads are already in progress.
Then $f(h,n)$ satisfies the recursion \begin{align*} &\text{if}\;h \ge 3,\;\text{then}\\[4pt] &\;\;\;\;f(h,n) = 0\\[4pt] &\text{else if}\;n = 0,\;\text{then}\\[4pt] &\;\;\;\;f(h,n) = 1\\[4pt] &\text{else}\\[4pt] &\;\;\;\;f(h,n) = f(0,n-1)+f(h+1,n-1)\\[4pt] &\text{end if}\\[4pt] \end{align*} Explanation:
Based on the above recursion, we get the following dynamic program, expressed as pseudocode . . .
With either of the two methods, we get $x(32) = 334745777$.