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


int  Taken, I, Digit, Num, Score, Rev, Temp;
char List(9);
include c:\cxpl\codes;
                        \make jumbled list of digits 1 to 9
[loop   [Taken:= 0;     \bit array indicates which digits are taken
        for I:= 0 to 9-1 do
                [repeat Digit:= Ran(9)+1 until (Taken & 1<<Digit) = 0;
                Taken:= Taken + 1<<Digit;       \mark digit as taken
                List(I):= Digit;                \add digit to the list
                ];
for I:= 0 to 9-2 do if List(I) > List(I+1) then quit;
];                      \quit loop when digits are not in ascending order
Score:= 0;
loop    [for I:= 0 to 9-1 do [IntOut(0, List(I));  ChOut(0, ^ )];
        Num:= 0;  for I:= 0 to 9-1 do Num:= Num*10 + List(I);
        if Num = 123456789 then quit;
        Text(0, "^M^JReverse how many digits? ");  Rev:= IntIn(0);
        for I:= 0 to Rev/2-1 do
            [Temp:= List(I);  List(I):= List(Rev-1-I);  List(Rev-1-I):= Temp];
        Score:= Score+1;
        ];
Text(0, "^M^JCongrats! You did it in "); IntOut(0, Score);
Text(0, " moves!!^M^J");
]