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


function NumberReversalGame
    list = randperm(9);
    while issorted(list)
        list = randperm(9);
    end
    fprintf('Given a list of numbers, try to put them into ascending order\n')
    fprintf('by sequentially reversing everything left of a point you choose\n')
    fprintf('in the array. Try to do it in as few reversals as possible.\n')
    fprintf('No input will quit the game.\n')
    fprintf('Position Num:%s\n', sprintf(' %d', 1:length(list)))
    fprintf('Current List:%s', sprintf(' %d', list))
    pivot = 1;
    nTries = 0;
    while ~isempty(pivot) && ~issorted(list)
        pivot = input('    Enter position of reversal limit: ');
        if pivot
            list(1:pivot) = list(pivot:-1:1);
            fprintf('Current List:%s', sprintf(' %d', list))
            nTries = nTries+1;
        end
    end
    if issorted(list)
        fprintf('\nCongratulations! You win! Only %d reversals.\n', nTries)
    else
        fprintf('\nPlay again soon!\n')
    end
end