Task

Given a jumbled list of the numbers   1   to   9   that are definitely   not   in
ascending order.

Show the list,   and then ask the player how many digits from the
left to reverse.

Reverse those digits,   then ask again,   until all the digits end up in ascending order.



The score is the count of the reversals needed to attain the ascending order.



Note: Assume the player's input does not need extra validation.



Related tasks

   Sorting algorithms/Pancake sort
   Pancake sorting.
   Topswops


 
Module Number_Reversal_Game {
      PRINT "Given a jumbled list of the numbers 1 to 9,"
      PRINT "you must select how many digits from the left to reverse."
      PRINT "Your goal is to get the digits in order with 1 on the left and 9 on the right."
      \\ work on a new stack - old stack parked, and attached at the exit of this block
      Stack New {
            Data 1,2,3,4,5,6,7,8,9
            \\ Create jumbled list
            For i=1 to 30: Reverse(Random(2,9)):Next i
            Tries=0
            fin=false
           Repeat {
            \\ Show Stack
                  Stack
                  Try ok {
                        INPUT " -- How many numbers should be flipped:", flp%
                  }
                  if not Ok then print: Restart
                  if flp%<2 or flp%>9 then Restart
                  Reverse(flp%)
                  Tries++
                  CheckStack(&fin)
            } until Fin
            \\ show stack again
            Stack
            PRINT "You took "; tries; " tries to put the digits in order."
      }
      Sub Reverse(n)
            Shift 1, -n       ' shift one item nth times in reverse
      End Sub
      Sub CheckStack(&ok)
            ok=true
            if stack.size<2 then exit sub
            Local i
            For i=2 to stack.size {
                        ok=stackitem(i)-stackitem(i-1)=1
                        if ok else exit
            }
      End Sub
}
Number_Reversal_Game
 