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


PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
  BYTE i,j,tmp
 
  i=size-1
  WHILE i>0
  DO
    j=Rand(i+1)
    tmp=tab(i)
    tab(i)=tab(j)
    tab(j)=tmp
    i==-1
  OD
RETURN
 
BYTE FUNC IsSorted(BYTE ARRAY tab BYTE size)
  BYTE i
 
  FOR i=0 TO size-2
  DO
    IF tab(i)>tab(i+1) THEN
      RETURN (0)
    FI
  OD
RETURN (1)
 
PROC Swap(BYTE ARRAY tab BYTE size,count)
  BYTE i,j,tmp
 
  i=0 j=count-1
  WHILE i<j
  DO
    tmp=tab(i)
    tab(i)=tab(j)
    tab(j)=tmp
    i==+1 j==-1
  OD
RETURN
 
PROC Main()
  DEFINE SIZE="9"
  BYTE ARRAY a(SIZE)
  BYTE i,j,n,tmp
  BYTE LMARGIN=$52,oldLMARGIN
 
  oldLMARGIN=LMARGIN
  LMARGIN=0 ;remove left margin on the screen
  Put(125) PutE() ;clear the screen
 
  FOR i=0 TO SIZE-1
  DO
    a(i)=i+1
  OD
  KnuthShuffle(a,SIZE)
 
  i=0
  DO
    PrintF("%B: ",i)
    FOR j=0 TO SIZE-1
    DO
      PrintB(a(j))
    OD
    IF IsSorted(a,SIZE) THEN
      EXIT
    FI
    PrintF(" How many to flip (2-%B)? ",SIZE)
    n=InputB()
    IF n>=2 AND n<=SIZE THEN
      Swap(a,SIZE,n)
      i==+1
    FI
  OD
 
  PrintF("%E%EYou solved it in %B moves!",i)
 
  LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN