Flipping Coins

Sometimes people post their homework problems on stackoverflow.com I don’t answer homework problems, but I do like to try to figure them out.

Problem description: Take a stack of coins all heads up. Upturn the topmost coin, place back on the stack and then proceed: take the top 2 coins and upturn as a single stack (tail, head becomes when upturned and placed back on the stack tail, head (the two coins are flipped as if glued together)). Now in the same way flip the top 3 coins and place back on the stack (you get: tail, tail, head (and if there were 4 coins that would be tail, tail, tail, head). When you upturn the whole stack begin again with the first coin. Continue until you return to a stack with all heads up.

Here’s what I came up with:

Sub FlipCoin()
   
    ‘Stack a number of coins all heads up
   ‘flip the first coin and put on the stack
   ‘flip the first and second coin as a unit and put on the stack
   ‘flip the fist n coins as a unit and put on the stack
   ‘repeat flipping the first coin
   ‘stop when all coins are heads up
   
    Dim i As Long, j As Long
    Dim aCoins() As String
    Dim lCount As Long
    Dim dMidPoint As Double
    Dim sTemp As String
    Dim bAllHeads As Boolean
   
    Const lCOINS As Long = 6
   
    ReDim aCoins(1 To lCOINS)
   
    ‘set all coins to heads
   For i = 1 To lCOINS
        aCoins(i) = “H”
    Next i
   
    lCount = 0
    Debug.Print lCount, Join(aCoins, “,”)
   
    Do
        For i = 1 To lCOINS
            ‘flip the first j coins
           For j = 1 To i
                If aCoins(j) = “H” Then
                    aCoins(j) = “T”
                Else
                    aCoins(j) = “H”
                End If
            Next j
           
            ‘swap coins around the midpoint
           dMidPoint = i / 2
            For j = 1 To Int(dMidPoint)
                sTemp = aCoins(j)
                aCoins(j) = aCoins(i – (j – 1))
                aCoins(i – (j – 1)) = sTemp
            Next j
           
            lCount = lCount + 1
            Debug.Print lCount, Join(aCoins, “,”)
           
            ‘check for tails
           bAllHeads = InStr(1, Join(aCoins, “,”), “T”) = 0
            If bAllHeads Then Exit Do
        Next i
    Loop Until bAllHeads
   
End Sub

I only tested it to six coins. I thought the graph would be prettier.

Posted in Uncategorized

5 thoughts on “Flipping Coins

  1. I’ve been bashed over the head with the following advice by professors in the past, and I think it bears repeating here:

    “Always label your axes!”

    I think that the horizontal axis represents the number of coins in a stack and the vertical axis represents the number of flips required to return all coins to the original orientation…correct?

Leave a Reply

Your email address will not be published. Required fields are marked *