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


 
import "prelude.eg"
import "io.ego"
import "random.ego"
 
using System
using IO
using List
using Math
 
def swap =
    [ (I J) XX -> insert I (nth J XX) (insert J (nth I XX) XX) ]
 
def shuffle =
    [ XX ->
        let INDICES = reverse (fromto 0 ((length XX) - 1)) in
        let SWAPS = map [ I -> I (between 0 I) ] INDICES in
            foldr [I J -> swap I J] XX SWAPS ]
 
def prompt =
    [ XX TURN ->
        let _ = print TURN ". " in
        let _ = map [ X -> print X " " ] XX in
        let _ = print " : " in
            toint getline ]
 
def game =
    [ GOAL SHUFFLE TURN ->
        if SHUFFLE == GOAL then
            let _ = print "the goal was " in
            let _ = map [ X -> print X " " ] GOAL in
                print "\nit took you " TURN " turns\n"
        else
            let N = prompt SHUFFLE TURN in
            let YY = (reverse (take N SHUFFLE)) ++ (drop N SHUFFLE) in
                game GOAL YY (TURN + 1) ]
 
def main = 
    let XX = fromto 1 9 in game XX (shuffle XX) 0