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


 
digits: procedure options (main); /* 23 April 2010 */
   declare s character (9) varying;
   declare i fixed binary;
   declare digit character (1);
 
restart:
   put skip list ('In this game, you are given a group of digits.');
   put skip list ('You will specify one of those digits.');
   put skip list ('The computer will then reverse the digits up to the one you nominate.');
   put skip list ('Your task is to repeat this process a number of times until all the digits');
   put skip list ('are in order, left to right, 1 to 9.');
   put skip list ('Here are your digits');
 
redo:
   s = '';
   do until (length(s) = 9);
      digit = trim ( fixed(trunc (1+random()*9) ) );
      if index(s, digit) = 0 then s = s || digit;
   end;
   if s = '123456789' then go to redo;
 
loop:
   do forever;
      put skip list (s);
      if s = '123456789' then leave;
      get edit (digit) (a(1));
      i = index(s, digit);
      if i = 0 then do; put skip list ('invalid request'); iterate loop; end;
      s = reverse( substr(s, 1, i) ) || substr(s, i+1, length(s)-i);
   end;
   put skip list ('Congratulations');
   go to restart;
end digits;
 