% This program uses the random number generator from PCLU's
% 'misc.lib'

% Shuffle the given array. Every item ends up in a different place,
% so if given the numbers in ascending order, it is guaranteed that
% they will not still be in ascending order at the end.
jumble = proc [T: type] (a: array[T])
    for i: int in int$from_to_by(array[T]$high(a), array[T]$low(a)+1, -1) do
        j: int := array[T]$low(a) + random$next(i - array[T]$low(a))
        x: T := a[i]
        a[i] := a[j]
        a[j] := x
    end
end jumble

% Is the array sorted?
win = proc (a: array[int]) returns (bool)
    for i: int in array[int]$indexes(a) do
        if i ~= a[i] then return(false) end
    end
    return(true)
end win

% Reverse the first N items of the array
reverse = proc (n: int, a: array[int])
    for i: int in int$from_to(1, n/2) do
        j: int := n-i+1
        x: int := a[j]
        a[j] := a[i]
        a[i] := x
    end
end reverse

% Play the game
start_up = proc ()
    po: stream := stream$primary_output()
    pi: stream := stream$primary_input()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))
    score: int := 0
    nums: array[int] := array[int]$[1,2,3,4,5,6,7,8,9]
    jumble[int](nums)
    while ~win(nums) do
        for i: int in array[int]$elements(nums) do
            stream$puts(po, int$unparse(i))
        end
        stream$puts(po, ": reverse how many? ")
        n: int := int$parse(stream$getl(pi))
        reverse(n, nums)
        score := score + 1
    end
    for i: int in array[int]$elements(nums) do
        stream$puts(po, int$unparse(i))
    end
    stream$putl(po, "\nScore = " || int$unparse(score))
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. REVERSAL.
       AUTHOR.  Bill Gunshannon
       INSTALLATION.  Home.
       DATE-WRITTEN.  11 December 2021
      ****************************************************************
      ** Program Abstract:
      **   Use a Knuth Shuffle to reate our out ot sort array.
      **   Use a procedure called "reverse" to pancake sort the array.
      ****************************************************************

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01 RNUM               PIC 9.
       01 TRIES              PIC 99    VALUE 0.
       01 ANSWER     PIC 9(9)  VALUE 123456789.
       01 TBL-LEN    PIC 9    VALUE 9.
       01 TBL.
          05  TZ PIC 9(9).
          05  TA REDEFINES TZ
                 PIC 9 OCCURS 9 TIMES.

       PROCEDURE DIVISION.

       MAIN-pROGRAM.
           MOVE ANSWER TO TBL

           CALL 'KNUTH-SHUFFLE'
                 USING  BY REFERENCE TBL
           END-CALL.

           DISPLAY "TABLE after shuffle: " TBL.

           PERFORM UNTIL TBL = ANSWER
               ADD 1 TO TRIES
               DISPLAY "How many to reverse? "
               ACCEPT RNUM

               CALL 'REVERSE' USING BY CONTENT RNUM,
                      BY REFERENCE TBL
               END-CALL

               DISPLAY "Try #" TRIES "  " TBL
           END-PERFORM.
           DISPLAY "Congratulations.  You did it!"

           STOP RUN.
       END PROGRAM REVERSAL.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. KNUTH-SHUFFLE.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  I                       PIC 9(9).
       01  J                       PIC 9(9).
       01  TEMP                    PIC 9(9).
       01  tABLE-lEN               PIC 9  value 9.

       LINKAGE SECTION.
       01  TTABLE-AREA.
           03  TTABLE              PIC 9 OCCURS 9 TIMES.

       PROCEDURE DIVISION USING ttable-area.
           MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (11:6)) TO I

           PERFORM VARYING i FROM Table-Len BY -1 UNTIL i = 0
               COMPUTE j =
                   FUNCTION MOD(FUNCTION RANDOM * 10000, Table-Len) + 1

               MOVE ttable (i) TO temp
               MOVE ttable (j) TO ttable (i)
               MOVE temp TO ttable (j)
           END-PERFORM.

           GOBACK.
           END PROGRAM KNUTH-SHUFFLE.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. REVERSE.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  I                       PIC 9.
       01  J                       PIC 9.
       01  X                       PIC 9.
       01  LOOP-IDX                PIC 9.

       LINKAGE SECTION.
       01  IDX        PIC 9.
       01  TTABLE-AREA.
           03  TTABLE              PIC 9 OCCURS 9 TIMES.

       PROCEDURE DIVISION USING IDX, TTABLE-AREA.

       DIVIDE IDX BY 2 GIVING LOOP-IDx

       MOVE 1 TO I
       MOVE IDX TO J

       PERFORM LOOP-IDX TIMES
           MOVE TTABLE(I) TO X
           MOVE TTABLE(J) TO TTABLE(I)
           MOVE X TO TTABLE(J)
           ADD 1 TO I
           SUBTRACT 1 FROM J
       END-PERFORM.

       GOBACK.
       END PROGRAM REVERSE.


(defun shuffle! (vector)
  (loop for i from (1- (length vector)) downto 1
       do (rotatef (aref vector i)
                   (aref vector (random i)))))

(defun slice (vector start &optional end)
  (let ((end (or end (length vector))))
    (make-array (- end start)
                :element-type (array-element-type vector)
                :displaced-to vector
                :displaced-index-offset start)))

(defun orderedp (seq)
  (apply #'<= (coerce seq 'list)))

(defun prompt-integer (prompt)
  (format t "~A: " prompt)
  (finish-output)
  (clear-input)
  (parse-integer (read-line)))

(defun game ()
  (let ((numbers (vector 1 2 3 4 5 6 7 8 9)))
    (shuffle! numbers)
    (let ((score
           (do ((score 0 (1+ score)))
               ((orderedp numbers) score)
             (format t "~A~%" numbers)
             (let* ((n (prompt-integer "How many numbers to reverse"))
                    (slice (slice numbers 0 n)))
               (replace slice (nreverse slice))))))
      (format t "~A~%Congratulations, you did it in ~D reversals!~%" numbers score))))


SIZE = 9
ordered = (1..SIZE).to_a
shuffled = (1..SIZE).to_a

while shuffled == ordered
  shuffled.shuffle!
end

score = 0
until shuffled == ordered
  print "#{shuffled} Enter items to reverse: "

  next unless guess = gets
  next unless num = guess.to_i?
  next if num < 2 || num > SIZE

  shuffled[0, num] = shuffled[0, num].reverse
  score += 1
end

puts "#{shuffled} Your score: #{score}"


import std.stdio, std.random, std.string, std.conv, std.algorithm,
       std.range;

void main() {
    auto data = iota(1, 10).array;
    do data.randomShuffle;
    while (data.isSorted);

    int trial;
    while (!data.isSorted) {
        writef("%d: %s How many numbers to flip? ", ++trial, data);
        data[0 .. readln.strip.to!uint].reverse;
    }
    writefln("\nYou took %d attempts.", trial);
}


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


class
	APPLICATION

create
	make

feature {NONE}

	make
			-- Plays Number Reversal Game.
		local
			count: INTEGER
		do
			initialize_game
			io.put_string ("Let's play the number reversal game.%N")
			across
				numbers as ar
			loop
				io.put_string (ar.item.out + "%T")
			end
			from
			until
				is_sorted (numbers, 1, numbers.count)
			loop
				io.put_string ("%NHow many numbers should be reversed?%N")
				io.read_integer
				reverse_array (io.last_integer)
				across
					numbers as ar
				loop
					io.put_string (ar.item.out + "%T")
				end
				count := count + 1
			end
			io.put_string ("%NYou needed " + count.out + " reversals.")
		end

feature {NONE}

	initialize_game
			-- Array with numbers from 1 to 9 in a random unsorted order.
		local
			random: V_RANDOM
			item, i: INTEGER
		do
			create random
			create numbers.make_empty
			from
				i := 1
			until
				numbers.count = 9 and not is_sorted (numbers, 1, numbers.count)
			loop
				item := random.bounded_item (1, 9)
				if not numbers.has (item) then
					numbers.force (item, i)
					i := i + 1
				end
				random.forth
			end
		end

	numbers: ARRAY [INTEGER]

	reverse_array (upper: INTEGER)
			-- Array numbers with first element up to nth element reversed.
		require
			upper_positive: upper > 0
			ar_not_void: numbers /= Void
		local
			i, j: INTEGER
			new_array: ARRAY [INTEGER]
		do
			create new_array.make_empty
			new_array.deep_copy (numbers)
			from
				i := 1
				j := upper
			until
				i > j
			loop
				new_array [i] := numbers [j]
				new_array [j] := numbers [i]
				i := i + 1
				j := j - 1
			end
			numbers := new_array
		end

	is_sorted (ar: ARRAY [INTEGER]; l, r: INTEGER): BOOLEAN
			-- Is Array 'ar' sorted in ascending order?
		require
			ar_not_empty: not ar.is_empty
		do
			Result := True
			across
				1 |..| (r - 1) as c
			loop
				if ar [c.item] > ar [c.item + 1] then
					Result := False
				end
			end
		end

end


import system'routines;
import extensions;

public program()
{
    var sorted := Array.allocate(9).populate:(n => n + 1 );
    var values := sorted.clone().randomize:9;

    while (sorted.sequenceEqual:values)
    {
        values := sorted.randomize:9
    };

    var tries := new Integer();
    until (sorted.sequenceEqual:values)
    {
        tries.append:1;

        console.print("# ",tries," : LIST : ",values," - Flip how many?");

        values.sequenceReverse(0, console.readLine().toInt())
    };

    console.printLine("You took ",tries," attempts to put the digits in order!").readChar()
}


defmodule Number_reversal_game do
  def start( n ) when n > 1 do
    IO.puts "Usage: #{usage(n)}"
    targets = Enum.to_list( 1..n )
    jumbleds = Enum.shuffle(targets)
    attempt = loop( targets, jumbleds, 0 )
    IO.puts "Numbers sorted in #{attempt} atttempts"
  end

  defp loop( targets, targets, attempt ), do: attempt
  defp loop( targets, jumbleds, attempt ) do
    IO.inspect jumbleds
    {n,_} = IO.gets("How many digits from the left to reverse? ") |> Integer.parse
    loop( targets, Enum.reverse_slice(jumbleds, 0, n), attempt+1 )
  end

  defp usage(n), do: "Given a jumbled list of the numbers 1 to #{n} that are definitely not in ascending order, show the list 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."
end

Number_reversal_game.start( 9 )


-module( number_reversal_game ).

-export( [task/0, start/1] ).

start( N ) when N > 1 ->
	io:fwrite( "Usage: ~s~n", [usage(N)] ),
	Targets = lists:seq( 1, N ),
	Jumbleds = [X||{_,X} <- lists:sort([ {random:uniform(), Y} || Y <- Targets])],
	Attempt = loop( Targets, Jumbleds, 0 ),
	io:fwrite( "Numbers sorted in ~p atttempts~n", [Attempt] ).

task() -> start( 9 ).

loop( Targets, Targets, Attempt ) -> Attempt;
loop( Targets, Jumbleds, Attempt ) ->
	io:fwrite( "~p~n", [Jumbleds] ),
	{ok,[N]} = io:fread( "How many digits from the left to reverse? ", "~d" ),
	{Lefts, Rights} = lists:split( N, Jumbleds ),
	loop( Targets, lists:reverse(Lefts) ++ Rights, Attempt + 1 ).

usage(N) -> io_lib:format( "Given a jumbled list of the numbers 1 to ~p that are definitely not in ascending order, show the list 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.", [N] ).


include get.e

function accending(sequence s)
    for i = 1 to length(s)-1 do
        if s[i]>s[i+1] then
            return 0
        end if
    end for
    return 1
end function

puts(1,"Given a jumbled list of the numbers 1 to 9,\n")
puts(1,"you must select how many digits from the left to reverse.\n")
puts(1,"Your goal is to get the digits in order with 1 on the left and 9 on the right.\n")

sequence nums
nums = repeat(0,9)
integer n,flp,tries,temp

-- initial values
for i = 1 to 9 do
    nums[i] = i
end for

while accending(nums) do -- shuffle
    for i = 1 to 9 do
        n = rand(9)
        temp = nums[n]
        nums[n] = nums[i]
        nums[i] = temp
    end for
end while

tries = 0
while 1 do
    printf(1,"%2d : ",tries)
    for i = 1 to 9 do
        printf(1,"%d ",nums[i])
    end for

    if accending(nums) then
        exit
    end if

    flp = prompt_number(" -- How many numbers should be flipped? ",{1,9})
    for i = 1 to flp/2 do
        temp = nums[i]
        nums[i] = nums[flp-i+1]
        nums[flp-i+1] = temp
    end for

    tries += 1
end while

printf(1,"\nYou took %d tries to put the digits in order.", tries)


let rand = System.Random()

while true do
  let rec randomNums() =
    let xs = [|for i in 1..9 -> rand.Next(), i|] |> Array.sort |> Array.map snd
    if xs = Array.sort xs then randomNums() else xs

  let xs = randomNums()

  let suffix = function | 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th"

  let rec move i =
    printf "\n%A\n\nReverse how many digits from the left in your %i%s move? : " xs i (suffix i)
    let n = stdin.ReadLine() |> int
    Array.blit (Array.rev xs.[0..n-1]) 0 xs 0 n
    if xs <> Array.sort xs then
        move (i+1)
    else
        printfn "\nYou took %i moves to put the digits in order!\n" i

  move 1


USING: formatting io kernel math math.parser math.ranges
namespaces random sequences strings ;
IN: rosetta.number-reversal

: make-jumbled-array ( -- sorted jumbled )
    CHAR: 1 CHAR: 9 [a,b] [ 1string ] map dup clone randomize
    [ 2dup = ] [ randomize ] while ;

SYMBOL: trials

: prompt ( jumbled -- n )
    trials get "#%2d: " printf
    ", " join write
    "   Flip how many? " write flush
    readln string>number ;

: game-loop ( sorted jumbled -- )
    2dup = [
        2drop trials get
        "\nYou took %d attempts to put the digits in order!\n" printf
        flush
    ] [
        trials [ 1 + ] change
        dup dup prompt head-slice reverse! drop
        game-loop
    ] if ;

: play ( -- )
    0 trials set
    make-jumbled-array game-loop ;


include random.fs

variable flips
create nums 9 cells allot

: .array ( addr len -- ) 0 ?do dup @ . cell+ loop drop ;

: shuffle ( addr len -- )
  2 swap do
    dup i random cells +
    over @ over @  swap
    rot  ! over !
    cell+
  -1 +loop drop ;

: sorted? ( addr len -- )
  1- cells bounds ?do
    i [email protected] < if unloop false exit then
  cell +loop true ;

: init
  0 flips !
  nums 10 1 do
    i over !  cell+
  loop drop
  begin nums 9 shuffle nums 9 sorted? 0= until
  cr nums 9 .array ;

: reverse ( addr len -- )
  1- cells bounds
  begin 2dup >
  while over @ over @ >r over ! over r> swap !
        cell+ swap 1 cells - swap
  repeat 2drop ;

: flip ( n -- )
  dup 2 10 within 0= if . ." must be within 2 to 9" exit then
  nums swap reverse
  1 flips +!
  nums 9 sorted? if
    cr ." Got it in " flips @ . ." tries!"
  else
    cr nums 9 .array
  then ;

init
1 2 8 5 7 6 9 4 3  ok
7 flip
9 6 7 5 8 2 1 4 3  ok


program Reversal_game
  implicit none

  integer :: list(9) = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /)
  integer :: pos, attempts = 0

  call random_seed
  do while (sorted(list))
    call Shuffle(list)
  end do
  write(*, "(9i5)") list
  write(*,*)
  do while (.not. Sorted(list))
    write(*, "(a)", advance="no") "How many numbers from the left do you want to reverse? : "
    read*, pos
    attempts = attempts + 1
    list(1:pos) = list(pos:1:-1)
    write(*, "(9i5)") list
    write(*,*)
  end do
  write(*,*)
  write(*, "(a,i0,a)") "Congratulations! Solved in ", attempts, " attempts"

contains

subroutine Shuffle(a)
  integer, intent(inout) :: a(:)
  integer :: i, randpos, temp
  real :: r

  do i = size(a), 2, -1
    call random_number(r)
    randpos = int(r * i) + 1
    temp = a(randpos)
    a(randpos) = a(i)
    a(i) = temp
  end do
end subroutine

function Sorted(a)
  logical :: Sorted
  integer, intent(in) :: a(:)
  integer :: i

  do i = 1, size(a)-1
    if(list(i+1) /= list(i)+1) then
      Sorted = .false.
      return
    end if
  end do
  Sorted = .true.
end function

end program


package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    var k []int
    for {
        k = rand.Perm(9)
        for i, r := range k {
            if r == 0 {
                k[i] = 9
            }
        }
        if !sort.IntsAreSorted(k) {
            break
        }
    }
    fmt.Println("Sort digits by reversing a number of digits on the left.")
    var n, score int
    for {
        fmt.Print("Digits: ", k, ". How many to reverse? ")
        i, _ := fmt.Scanln(&n)
        score++
        if i == 0 || n < 2 || n > 9 {
            fmt.Println("\n(Enter a number from 2 to 9)")
            continue
        }
        for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
            k[l], k[r] = k[r], k[l]
        }
        if sort.IntsAreSorted(k) {
            fmt.Print("Digits: ", k, ".\n")
            fmt.Print("Your score: ", score, ".  Good job.\n")
            return
        }
    }
}


sorted = [*(1..9)]
arr    = sorted.clone()

void flipstart(n) { arr[0..<n] = arr[0..<n].reverse() }

int steps = 0
while (arr==sorted) Collections.shuffle(arr)
while (arr!=sorted) {
    println arr.join(' ')
    print 'Reverse how many? '
    def flipcount = System.in.readLine()
    flipstart( flipcount.toInteger() )
    steps += 1
}
println "Done! That took you ${steps} steps"


import Data.List
import Control.Arrow
import Rosetta.Knuthshuffle

numberRevGame = do
  let goal = [1..9]

      shuffle xs =
	if xs /= goal then return xs
		    else shuffle =<< knuthShuffle xs

      prefixFlipAt k = uncurry (++). first reverse. splitAt k

      prompt r ry = do
	 putStr $ show r ++ ". " ++ concatMap (flip (++) " ". show) ry
		   ++ " How many to flip? "
	 answ <- getLine
	 let n = read answ
	 if n<10 && 0<n then return n
	    else do
	      putStrLn "Error. The number should be between 0 and 10. Try again"
	      prompt r ry

      playNRG r nrs =
	if nrs == goal then do
	  putStrLn $ "The answer is: " ++ concatMap (flip (++) " ". show) nrs
	  putStrLn $ "It took you " ++ show r ++ " attempts to sort the numbers."
	  putStrLn ""
		else do
		  answ <- prompt r nrs
		  playNRG (succ r) (prefixFlipAt answ nrs)

  start <- shuffle goal

  playNRG 1 start


   WRITE(Messagebox) "You took ", Reversals(), " attempts"

FUNCTION Reversals()
  DIMENSION digits(9), temp(9)

  digits = 0
  DO i = 1, 9 ! create the shuffled digits
 1   x = CEILING( RAN(9) )
     IF( INDEX(digits, x) ) GOTO 1 ! HicEst has no WHILE
     digits(i) = x
  ENDDO

  DO Reversals = 1, 1E6 ! HicEst needs an upper bound
     DLG(NameEdit=Flips, DNum, MIn=0, MAx=9, Text=digits)
     DO j = 1, Flips/2
        swap = digits(j)
        digits(j) = digits(Flips+1-j)
        digits(Flips+1-j) = swap
     ENDDO
     temp = digits($+1) > digits($) ! $ = left side index
     IF( SUM(temp) == 8 ) RETURN
  ENDDO
END


procedure main(cq)                                             # Number Reversal Game
local x,nums,R,flips

$define PROTECT ["WIN","ASK"]
$define MAGIC   ["xyzzy","abracadabra","hocus","pocus","presto","changeo","open","sesame","irs"]

put(cq,"game")                                                 # start command queue - use command line
rule := string(&digits--'0')                                   # ruler and move commands
every put(protected := [], map(!PROTECT))                      # protected commands
every put(magic := [], !MAGIC)

while x := get(cq) | "MOVE" do {                               # command from queue or ask for move
   case x of {
      "help" | "h" | "?" :                                     # --- start of user facing commands ---
         write("Input a position.  The list will be flipped left to right at that point.\n",
	       "You win when the list is sorted.\n",
	       "Commands:\n",
               "   help, h, ? - shows this\n",
               "   new, g     - new game\n",
               "   ruler, r   - shows a ruler\n",
               "   show, s    - shows the list\n",
               "   <n>        - flips the list at ruler position n\n",
               "   quit, q    - quit\n",
               "and various magic words.\n"
               ) & put(cq,"rule")
      "game" | "g" | "new"  : {
         put(cq,"help")
         flips := 0
         nums := rule
         until nums ~== rule do
         every !nums :=: ?nums                                 # shuffle
         }
      "rule" | "ruler" | "r" :
         put(cq,"show") & every writes(" " || " " | !(if /mirror then rule else reverse(rule)) | "\n")
      "show" | "s" :
         every writes(" " || "=" | !nums | " =\n")
      !rule : {                                                #  0 - 9 for flipping
         if /mirror then nums[1+:x] := reverse(nums[1+:x])
         else nums[0-:x] := reverse(nums[0-:x])
         flips +:= 1
         put(cq,if nums == rule then "WIN" else "show")
         }
      "quit" | "q" :
         break write("Goodbye.")
      !magic:                                                  # --- start of magic
         write("That has no power here.  Try again!")
      "magic" | "mirror" | "m" : {
         mirror := if /mirror then 1 else &null
         write("Wait! What is this? The writing has reversed.")
         }
      !protected:                                              # --- Start of internal (upper case) and protected commands
         put(cq,?rule) & write("Tisk, Tisk, don't try and cheat.  Take a random penalty flip!")
      "MOVE" :
         put(cq,ask("Command? : ") )
      "WIN" :
         put(cq,"ASK") & write("Congratulations you won in ",flips," flips!")
      "ASK" :
         put(cq,case ask("Play another game? : ") of { "y"|"yes" : "game"; "n"|"no" : "quit"; default : "ASK" } )
      default:                                                 # --- say what?
         write("Sorry I don't know that command, try help?")
      }
   }
end

procedure ask(s)                       #: ask for input with prompt s and return the 1st word in lower case
writes(\s)
map(trim(read())) ? return tab(upto(' ')|0)
end


Number Reversal Game is a room.

The current list is a list of numbers that varies.

When play begins:
	now the current list is a shuffled list from 1 to 9;
	now the command prompt is "Current list: [current list in brace notation].[line break]How many items to flip? ".

Definition: a list of numbers (called L) is sorted:
	repeat with N running from 1 to the number of entries in L:
		if entry N in L is not N, no;
	yes.

To decide which list of numbers is a shuffled list from (min - number) to (max - number):
	let result be a list of numbers;
	repeat with N running from min to max:
		add N to result;
	while true is true:
		sort result in random order;
		if result is not sorted, decide on result.

Flipping is an action applying to one number. Understand "[number]" as flipping.

Carry out flipping:
	let N be the number understood;
	let L be the current list;
	truncate the current list to the first N entries;
	reverse the current list;
	truncate L to the last (number of entries in L minus N) entries;
	add L to the current list.

Report flipping: say "".

Every turn:
	if the current list is sorted, end the story saying "You have won".

This is the new print final score rule:
	say "It took you [turn count] flip[s] to sort the list."

The new print final score rule is listed instead of the print final score rule in the for printing the player's obituary rules.


withRange := method( a, z,
    Range clone setRange(a,z)
)
sorted := withRange(1,9) asList
numbers := sorted clone shuffle
while( numbers==sorted, numbers = numbers shuffle)

steps :=0
stdin := File standardInput
while( numbers != sorted,
    writeln(numbers join(" "))
    write("Reverse how many? ")
    flipcount := stdin readLine asNumber
    withRange(0, ((flipcount-1)/2) floor) foreach( i,
        numbers swapIndices(i,flipcount-1-i)
    )
    steps = steps+1
)
writeln("Done! That took you ", steps, " steps")


100 PROGRAM "Reversal.bas"
110 RANDOMIZE
120 NUMERIC NR(1 TO 9)
130 LET TRIES=0
140 TEXT :PRINT "Given a jumbled list of the numbers 1 to 9, you must select how many digits from the left to reverse.":PRINT "Your goal is to get the digits in order with 1 on the left and 9 on the right.":PRINT
150 FOR I=1 TO 9
160   LET NR(I)=I
170 NEXT
180 DO
190   FOR I=2 TO 9
200     LET N=RND(I)+1
210     IF N<>I THEN CALL SWAP(N,I)
220   NEXT
230 LOOP WHILE ORDERED
240 DO
250   PRINT USING "##: ":TRIES;
260   FOR I=1 TO 9
270     PRINT NR(I);
280   NEXT
290   PRINT
300   IF ORDERED THEN EXIT DO
310   DO
320     INPUT PROMPT "How many numbers should be flipped? ":FLIP
330   LOOP WHILE FLIP<2 OR FLIP>9
340   FOR I=1 TO FLIP/2
350     CALL SWAP(I,FLIP-I+1)
360   NEXT
370   LET TRIES=TRIES+1
380 LOOP
390 PRINT :PRINT "You took";TRIES;"tries to put the digits in order."
400 DEF SWAP(A,B)
410   LET T=NR(A):LET NR(A)=NR(B):LET NR(B)=T
420 END DEF
430 DEF ORDERED
440   LET ORDERED=-1
450   FOR J=1 TO 8
460     IF NR(J)>NR(J+1) THEN LET ORDERED=0:EXIT FOR
470   NEXT
480 END DEF


require 'misc'                      NB. for the verb prompt

INTRO=: noun define
Number Reversal Game
Flip groups of numbers from the left of the list until
the numbers are sorted in ascending order.
)

reversegame=: verb define
  whilst. (-: /:~)nums do.
    nums=. 1+9?9                    NB. 1-9 in random order
  end.
  score=. 0
  smoutput INTRO                    NB. Display instructions
  while. -.(-: /:~)nums do.
    score=. 1+ score                NB. increment score
    nnum=. 0".prompt (":score),': ',(":nums),' How many numbers to flip?: '
    if. 0 = #nnum do. return. end.  NB. exit on ENTER without number
    nums=. (C.i.-nnum) C. nums      NB. reverse first nnum numbers
  end.
  'You took ',(": score), ' attempts to put the numbers in order.'
)


import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class ReversalGame {
    private List<Integer> gameList;

    public ReversalGame() {
        initialize();
    }

    public void play() throws Exception {
        int i = 0;
        int moveCount = 0;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println(gameList);
            System.out.println("Please enter a index to reverse from 2 to 9. Enter 99 to quit");
            i = scanner.nextInt();
            if (i == 99) {
                break;
            }
            if (i < 2 || i > 9) {
                System.out.println("Invalid input");
            } else {
                moveCount++;
                reverse(i);
                if (isSorted()) {
                    System.out.println("Congratulations you solved this in " + moveCount + " moves!");
                    break;
                }
            }

        }
        scanner.close();
    }

    private void reverse(int position) {
        Collections.reverse(gameList.subList(0, position));
    }

    private boolean isSorted() {
        for (int i=0; i < gameList.size() - 1; ++i) {
            if (gameList.get(i).compareTo(gameList.get(i + 1)) > 0) {
                return false;
            }
        }
        return true;
    }

    private void initialize() {
        this.gameList = new ArrayList<Integer>(9);
        for (int i=1; i < 10; ++i) {
            gameList.add(i);
        }
        while (isSorted()) {
            Collections.shuffle(gameList);
        }
    }

    public static void main(String[] args) {
        try {
            ReversalGame game = new ReversalGame();
            game.play();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}


# Input: the initial array
def play:
  def sorted: . == sort;

  def reverse(n):  (.[0:n] | reverse)  + .[n:];

  def prompt: "List: \(.list)\nEnter a pivot number: ";

  def report: "Great! Your score is \(.score)";

  {list: ., score: 0}
  | (if .list | sorted then "List was sorted to begin with."
     else
     prompt,
     ( label $done
     | foreach inputs as $n (.;
         .list |= reverse($n) | .score +=1;
         if .list | sorted then report, break $done else prompt end ))
     end);


# v0.6

function numrevgame()
    l = collect(1:9)
    while issorted(l) shuffle!(l) end
    score = 0
    println("# Number reversal game")
    while !issorted(l)
        print("$l\nInsert the index up to which to revert: ")
        n = parse(Int, readline())
        reverse!(l, 1, n)
        score += 1
    end
    println("$l... You won!\nScore: $score")
    return score
end

numrevgame()


// version 1.1.2

fun isAscending(a: IntArray): Boolean {
    for (i in 0..8) if (a[i] != i + 1) return false
    return true
}

fun main(args: Array<String>) {
    val r = java.util.Random()
    var count = 0
    val numbers = IntArray(9)
    numbers[0] = 2 + r.nextInt(8) // this will ensure list isn't ascending
    for (i in 1..8) {
        var rn: Int
        do {
            rn = 1 + r.nextInt(9)
        } while (rn in numbers)
        numbers[i] = rn
    }
    println("Here's your first list : ${numbers.joinToString()}")
    while (true) {
        var rev: Int
        do {
            print("How many numbers from the left are to be reversed : ")
            rev = readLine()!!.toInt()
        } while (rev !in 2..9)
        count++
        var i = 0
        var j = rev - 1
        while (i < j) {
            val temp = numbers[i]
            numbers[i++] = numbers[j]
            numbers[j--] = temp
        }
        if (isAscending(numbers)) {
            println("Here's your final list : ${numbers.joinToString()}")
            break
        }
        println("Here's your list now   : ${numbers.joinToString()}")
    }
    println("So you've completed the game with a score of $count")
}


-- Initialisation
math.randomseed(os.time())
numList = {values = {}}

-- Check whether list contains n
function numList:contains (n)
  for k, v in pairs(self.values) do
    if v == n then return true end
  end
  return false
end

-- Check whether list is in order
function numList:inOrder ()
  for k, v in pairs(self.values) do
    if k ~=v then return false end
  end
  return true
end

-- Create necessarily out-of-order list
function numList:build ()
  local newNum
  repeat
    for i = 1, 9 do
      repeat
        newNum = math.random(1, 9)
      until not numList:contains(newNum)
      table.insert(self.values, newNum)
    end
  until not numList:inOrder()
end

-- Display list of numbers on one line
function numList:show ()
  for k, v in pairs(self.values) do
    io.write(v .. " ")
  end
  io.write(":\t")
end

-- Reverse n values from left
function numList:reverse (n)
  local swapList = {}
  for k, v in pairs(self.values) do
    table.insert(swapList, v)
  end
  for i = 1, n do
    swapList[i] = self.values[n + 1 - i]
  end
  self.values = swapList
end

-- Main procedure
local score = 0
print("\nRosetta Code Number Reversal Game in Lua")
print("========================================\n")
numList:build()
repeat
  numList:show()
  numList:reverse(tonumber(io.read()))
  score = score + 1
until numList:inOrder()
numList:show()
print("\n\nW00t!  You scored:", score)


Module Number_Reversal_Game {
      PRINT "Given a jumbled list of the numbers 1 to 9,"
      PRINT "you must select how many digits from the left to reverse."
      PRINT "Your goal is to get the digits in order with 1 on the left and 9 on the right."
      \\ work on a new stack - old stack parked, and attached at the exit of this block
      Stack New {
            Data 1,2,3,4,5,6,7,8,9
            \\ Create jumbled list
            For i=1 to 30: Reverse(Random(2,9)):Next i
            Tries=0
            fin=false
           Repeat {
            \\ Show Stack
                  Stack
                  Try ok {
                        INPUT " -- How many numbers should be flipped:", flp%
                  }
                  if not Ok then print: Restart
                  if flp%<2 or flp%>9 then Restart
                  Reverse(flp%)
                  Tries++
                  CheckStack(&fin)
            } until Fin
            \\ show stack again
            Stack
            PRINT "You took "; tries; " tries to put the digits in order."
      }
      Sub Reverse(n)
            Shift 1, -n       ' shift one item nth times in reverse
      End Sub
      Sub CheckStack(&ok)
            ok=true
            if stack.size<2 then exit sub
            Local i
            For i=2 to stack.size {
                        ok=stackitem(i)-stackitem(i-1)=1
                        if ok else exit
            }
      End Sub
}
Number_Reversal_Game


Module[{array = [email protected], score = 0},
 While[array == [email protected], array = [email protected]@9];
 While[array != [email protected],
  [email protected]; (array[[;; #]] = [email protected][[;; #]]) &@
   Input["How many digits would you like to reverse?"]; score++];
 [email protected]; Print["Your score:", score]]


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


import random, rdstdin, strutils, algorithm
randomize()

proc isSorted[T](s: openarray[T]): bool =
  var last = low(T)
  for c in s:
    if c < last:
      return false
    last = c
  return true

proc toString[T](s: openarray[T]): string =
  result = ""
  for i, x in s:
    if i > 0:
      result.add " "
    result.add($x)

echo """number reversal game
    Given a jumbled list of the numbers 1 to 9
    Show the list.
    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."""

var data = @[1,2,3,4,5,6,7,8,9]
var trials = 0
while isSorted data:
  shuffle data
while not isSorted data:
  inc trials
  var flip = parseInt readLineFromStdin(
    "#" & $trials & ": List: '" & toString(data) & "' Flip how many?: ")
  reverse(data, 0, flip - 1)

echo "You took ", trials, " attempts to put the digits in order!"


let swap ar i j =
  let tmp = ar.(i) in
  ar.(i) <- ar.(j);
  ar.(j) <- tmp

let shuffle ar =
  for i = pred(Array.length ar) downto 1 do
    let j = Random.int (i + 1) in
    swap ar i j
  done

let reversal ar n =
  for i = 0 to pred(n/2) do
    let j = (pred n) - i in
    swap ar i j
  done

let sorted ar =
  try
    let prev = ref ar.(0) in
    for i = 1 to pred(Array.length ar) do
      if ar.(i) < !prev then raise Exit;
      prev := ar.(i)
    done;
    (true)
  with Exit ->
    (false)

let () =
  print_endline "\
  Number Reversal Game
  Sort the numbers in ascending order by repeatedly
  flipping sets of numbers from the left.";
  Random.self_init();
  let nums = Array.init 9 (fun i -> succ i) in
  while sorted nums do shuffle nums done;
  let n = ref 1 in
  while not(sorted nums) do
    Printf.printf "#%2d: " !n;
    Array.iter (Printf.printf " %d") nums;
    print_newline();
    let r = read_int() in
    reversal nums r;
    incr n;
  done;
  print_endline "Congratulations!";
  Printf.printf "You took %d attempts to put the digits in order.\n" !n;
;;


import: console

: reversalGame
| l n |
   doWhile: [
      ListBuffer new ->l
      while(l size 9 <>) [ 9 rand dup l include ifFalse: [ l add ] else: [ drop ] ]
      l sort l ==
      ]

   0 while(l sort l <>) [
      System.Out "List is " << l << " ==> how many digits from left to reverse : " <-
      System.Console askln asInteger dup ifNull: [ drop continue ] ->n
      1+ l left(n) reverse l right(l size n -) + ->l
      ]
   "You won ! Your score is :" . println ;


declare
  proc {Main}
     proc {Loop N Xs}
        if {Not {IsSorted Xs}} then
           Num NewXs
        in
           {System.printInfo N#": "}
           {System.print Xs}
           {System.printInfo " -- Reverse how many? "}
           Num = {String.toInt {ReadLine}}
           NewXs = {Append
                    {Reverse {List.take Xs Num}}
                    {List.drop Xs Num}}
           {Loop N+1 NewXs}
        else
           {System.showInfo "You took "#N#" tries to put the digits in order."}
        end
     end
     fun {EnsureShuffled Xs}
        Ys = {Shuffle Xs}
     in
        if {Not {IsSorted Ys}} then Ys
        else {EnsureShuffled Xs}
        end
     end
  in
     {Loop 0 {EnsureShuffled {List.number 1 9 1}}}
  end

  fun {IsSorted Xs}
     {Sort Xs Value.'<'} == Xs
  end

  local
     class TextFile from Open.file Open.text end
     StdIn = {New TextFile init(name:stdin)}
  in
     fun {ReadLine}
        {StdIn getS($)}
     end
  end

  fun {Shuffle Xs}
     {FoldL Xs
      fun {$ Z _}
         {Pick {Diff Xs Z}}|Z
      end
      nil}
  end

  fun {Pick Xs}
     {Nth Xs {OS.rand} mod {Length Xs} + 1}
  end

  fun {Diff Xs Ys}
     {FoldL Ys List.subtract Xs}
  end
in
  {Main}


game()={
  my(v=numtoperm(9,random(9!-1)),score,in,t); \\ Create vector with 1..9, excluding the one sorted in ascending order
  while(v!=vecsort(v),
    print(concat(concat([""],v)));
    in=input();
    for(i=0,in\2-1,
      t=v[9-i];
	  v[9-i]=v[10-in+i];
	  v[10-in+i]=t
    );
    score++
  );
  score
};


program NumberReversalGame;

procedure PrintList(list: array of integer);
var
    i: integer;
begin
    for i := low(list) to high(list) do
    begin
        Write(list[i]);
        if i < high(list) then Write(', ');
    end;
    WriteLn;
end;

procedure Swap(var list: array of integer; i, j: integer);
var
    buf: integer;
begin
    buf := list[i];
    list[i] := list[j];
    list[j] := buf;
end;

procedure ShuffleList(var list: array of integer);
var
    i, j, n: integer;
begin
    Randomize;

    for n := 0 to 99 do
    begin
        i := Random(high(list)+1);
        j := Random(high(list)+1);
        Swap(list, i, j);
    end;
end;

procedure ReverseList(var list: array of integer; j: integer);
var
    i: integer;
begin
    i := low(list);

    while i < j do
    begin
        Swap(list, i, j);
        i += 1;
        j -= 1;
    end;
end;

function IsOrdered(list: array of integer): boolean;
var
    i: integer;
begin
    IsOrdered := true;
    i:= high(list);

    while i > 0 do
    begin
        if list[i] <> (list[i-1] + 1) then
        begin
            IsOrdered:= false;
            break;
        end;
        i -= 1;
    end;
end;

var
    list: array [0..8] of integer = (1, 2, 3, 4, 5, 6, 7, 8, 9);
    n: integer;
    moves: integer;
begin

    WriteLn('Number Reversal Game');
    WriteLn;
    WriteLn('Sort the following list in ascending order by reversing the first n digits');
    WriteLn('from the left.');
    WriteLn;

    ShuffleList(list);
    PrintList(list);

    moves := 0;

    while not IsOrdered(list) do
    begin
        WriteLn('How many digits from the left will you reverse?');
        Write('> ');
        Read(n);

        ReverseList(list, n-1);
        PrintList(list);
        moves += 1;
    end;

    WriteLn;
    WriteLn('Congratulations you made it in just ', moves, ' moves!');
    WriteLn;
end.


use List::Util qw(shuffle);

my $turn = 0;
my @jumble = shuffle 1..9;

while ( join('', @jumble) eq '123456789' ) {
    @jumble = shuffle 1..9;
}

until ( join('', @jumble) eq '123456789' ) {
    $turn++;
    printf "%2d: @jumble - Flip how many digits ? ", $turn;

    my $d = <>;

    @jumble[0..$d-1] = reverse @jumble[0..$d-1];
}

print "    @jumble\n";
print "You won in $turn turns.\n";


puts(1,"Given a jumbled list of the numbers 1 to 9,\n")
puts(1,"you must select how many digits from the left to reverse.\n")
puts(1,"Your goal is to get the digits in order with 1 on the left and 9 on the right.\n")

constant inums = tagset(9)
sequence nums
integer turns = 0, flip

while 1 do
    nums = shuffle(inums)
    if nums!=inums then exit end if
end while

while 1 do
    printf(1,"%2d : %d %d %d %d %d %d %d %d %d ",turns&nums)
    if nums=inums then exit end if
    flip = prompt_number(" -- How many numbers should be flipped? ",{1,9})
    nums[1..flip] = reverse(nums[1..flip])
    turns += 1
end while

printf(1,"\nYou took %d turns to put the digits in order.", turns)


class ReversalGame {
    private $numbers;

    public function __construct() {
        $this->initialize();
    }

    public function play() {
        $i = 0;
        $moveCount = 0;
        while (true) {
            echo json_encode($this->numbers) . "\n";
            echo "Please enter an index to reverse from 2 to 9. Enter 99 to quit\n";
            $i = intval(rtrim(fgets(STDIN), "\n"));
            if ($i == 99) {
                break;
            }
            if ($i < 2 || $i > 9) {
                echo "Invalid input\n";
            } else {
                $moveCount++;
                $this->reverse($i);
                if ($this->isSorted()) {
                    echo "Congratulations you solved this in $moveCount moves!\n";
                    break;
                }
            }

        }
    }

    private function reverse($position) {
        array_splice($this->numbers, 0, $position, array_reverse(array_slice($this->numbers, 0, $position)));
    }

    private function isSorted() {
        for ($i = 0; $i < count($this->numbers) - 1; ++$i) {
            if ($this->numbers[$i] > $this->numbers[$i + 1]) {
                return false;
            }
        }
        return true;
    }

    private function initialize() {
        $this->numbers = range(1, 9);
        while ($this->isSorted()) {
            shuffle($this->numbers);
        }
    }

}

$game = new ReversalGame();
$game->play();


(load "@lib/simul.l")

(de reversalGame ()
   (let (Lst (shuffle (range 1 9))  Cnt 0)
      (while (apply < Lst)
         (setq Lst (shuffle Lst)) )
      (loop
         (printsp Lst)
         (T (apply < Lst) Cnt)
         (NIL (num? (read)))
         (setq Lst (flip Lst @))
         (inc 'Cnt) ) ) )


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;


#adding the below function to the previous users submission to prevent the small
#chance of getting an array that is in ascending order.

#Full disclosure: I am an infrastructure engineer, not a dev. My code is likely
#bad.

function generateArray{
    $fArray = 1..9 | Get-Random -Count 9
    if (-join $fArray -eq -join @(1..9)){
        generateArray
    }
    return $fArray
}
$array = generateArray

#everything below is untouched from original submission
$nTries = 0
While(-join $Array -ne -join @(1..9)){
    $nTries++
    $nReverse = Read-Host -Prompt "[$Array] -- How many digits to reverse? "
    [Array]::Reverse($Array,0,$nReverse)
}
"$Array"
"Your score: $nTries"


play :- random_numbers(L), do_turn(0,L), !.

do_turn(N, L) :-
	print_list(L),
	how_many_to_flip(F),
	flip(L,F,[],Lnew),
	succ(N,N1),
	sorted(N1,Lnew).

how_many_to_flip(F) :-
	read_line_to_codes(user_input, Line),
	number_codes(F, Line),
	between(1,9,F).

flip(L,0,C,R) :- append(C,L,R).
flip([Ln|T],N,C,R) :- dif(N,0), succ(N0,N), flip(T,N0,[Ln|C],R).

sorted(N,L) :-
	sort(L,L)
	-> print_list(L), format('-> ~p~n', N)
	; do_turn(N,L).

random_numbers(L) :- random_permutation([1,2,3,4,5,6,7,8,9],L).

print_list(L) :-
	atomic_list_concat(L, ' ', Lf),
	format('(~w) ',Lf).


Dim MyList(9)

Declare is_list_sorted()

If OpenConsole()
  Define score, indata, i, txt$

  For i=1 To 9         ;- Initiate the list
    MyList(i)=i
  Next
  While is_list_sorted()
    For i=1 To 9      ;- Do a Fisher–Yates shuffle
      Swap MyList(i), MyList(Random(i)+1)
    Next
  Wend

  ;- Start the Game
  Repeat
    score+1
    txt$=RSet(str(score), 3)+": "      ;- Show current list
    For i=1 To 9
      txt$+str(MyList(i))+" "
    Next
    Repeat                             ;- Get input & swap
      Print(txt$+"| How many numbers should be flipped? "): indata=Val(Input())
    Until indata>=1 And indata<=9      ;- Verify the input
    For i=1 To (indata/2)
      Swap MyList(i),MyList(indata-i+1)
    Next
  Until is_list_sorted()

  ;- Present result & wait for users input before closing down
  PrintN(#CRLF$+"You did it in "+str(score)+" moves")
  Print("Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Procedure is_list_sorted()
  Protected i
  Shared MyList()
  For i=1 To 9
    If MyList(i)<>i
      ProcedureReturn #False
    EndIf
  Next
  ProcedureReturn #True
EndProcedure


'''
number reversal game
    Given a jumbled list of the numbers 1 to 9
    Show the list.
    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.

'''

import random

print(__doc__)
data, trials = list('123456789'), 0
while data == sorted(data):
    random.shuffle(data)
while data != sorted(data):
    trials += 1
    flip = int(input('#%2i: LIST: %r Flip how many?: ' % (trials, ' '.join(data))))
    data[:flip] = reversed(data[:flip])

print('\nYou took %2i attempts to put the digits in order!' % trials)


  [ 0 temp put
    [] 9 times
      [ i^ 1+ join ]
    dup
    [ shuffle 2dup != until ]
    [ dup echo cr
      2dup != while
      [ $ "Reverse how many? "
        input
        $->n not iff
          drop again ]
      split dip reverse join
      1 temp tally
      again ]
     drop cr
     say "That took "
     temp take echo
     say " reversals." ]       is play ( --> )


reversalGame <- function(){
  cat("Welcome to the Number Reversal Game! \n")
  cat("Sort the numbers into ascending order by repeatedly \n",
      "reversing the first n digits, where you specify n. \n \n", sep="")

  # Generate a list that's definitely not in ascending order, per instuctions
  data <- sample(1:9, 9)
  while (all(data == 1:9)){
    cat("What were the chances...? \n")
    data <- sample(1:9, 9)
  }
  trials <- 0

  # Play the game
  while (any(data != 1:9)){
    trials <- trials + 1
    cat("Trial", sprintf("%02d", trials), " # ", data, " #  ")
    answer <- readline(paste("Flip how many? "))
    data[1:answer] <- data[answer:1]
  }

  # Victory!
  cat("Well done.  You needed", trials, "flips. \n")
}


#lang racket
(let loop ([nums (range 1 10)] [n 0])
  (cond [(apply < nums) (if (zero? n)
                            (loop (shuffle nums) 0)
                            (printf "Done in ~s steps.\n" n))]
        [else (printf "Step #~s: ~s\nFlip how many? " n nums)
              (define-values (l r) (split-at nums (read)))
              (loop (append (reverse l) r) (add1 n))]))


repeat while [<] my @jumbled-list {
    @jumbled-list = (1..9).pick(*)
}

my $turn = 0;
repeat until [<] @jumbled-list {
    my $d = prompt $turn.=succ.fmt('%2d: ') ~
                   @jumbled-list ~
                   " - Flip how many digits? "
        or exit;
    @jumbled-list[^$d] .= reverse;
}

say "    @jumbled-list[]";
say "You won in $turn turns.";


import Prelude;
import vis::Figure;
import vis::Render;

public void NumberReversalGame(){

	//generate randomlist
	L = [1..9];
	score = 0;
	randomlist = [];
	while (L != []){
		temp = takeOneFrom(L);
		randomlist += temp[0];
		L = temp[1];
	}

	// user interaction
	score = 0;
	text1 = "";
	figure =
	box(vcat([
		box(text(str(){
			return "<randomlist>";})),
		box(textfield("Insert number of digits you would like to reverse here.",
			void(str s){
				score += 1;
				n = toInt(s);
				spliced = slice(randomlist, 0, n);
				randomlist = reverse(spliced) + (randomlist - spliced);
				},
			fillColor("lightblue"))),
		box(text(str(){
			return ((randomlist == [1 .. 9]) ? "Well done! Your score: <score>." : "Keep going!");}))
				]));

	render(figure);
}


rebol []

print "NUMBER REVERSAL GAME"

tries: 0
goal: [1 2 3 4 5 6 7 8 9]
random/seed now

until [
    jumble: random goal
    jumble != goal ; repeat in the unlikely case that jumble isn't jumbled
]

while [jumble != goal] [
    prin jumble
    prin " How many to flip? "
    flip-index: to-integer input ; no validation!
    reverse/part jumble flip-index
    tries: tries + 1
]

print rejoin ["You took " tries " attempts."]


/*REXX program (a game):  reverse a jumbled set of decimal digits 'til they're in order.*/
signal on halt                                   /*allows the CBLF to  HALT the program.*/
___= copies('─', 9);      pad=left('', 9)        /*a fence used for computer's messages.*/
say ___  "This game will show you nine random unique digits  (1 ──► 9),  and you'll enter"
say ___  "one of those digits  which will reverse all the digits from the left-most digit"
say ___  "up to  (and including)  that decimal digit.  The game's objective is to get all"
say ___  "of the digits in ascending order with the fewest tries.    Here're your digits:"
ok= 123456789                                    /*the result that the string should be.*/
$=                                               /* ◄─── decimal target to be generated.*/
      do  until length($)==9;     _=random(1, 9) /*build a random unique numeric string.*/
      if pos(_, $) \== 0  then iterate           /*¬ unique? Only use a decimal dig once*/
      $=$ || _                                   /*construct a string of unique digits. */
      if $==ok  then $=                          /*string can't be in order, start over.*/
      end   /*until*/

  do  score=1  until  $==ok;           say       /* [↓]  display the digits & the prompt*/
  say ___  $   right('please enter a digit  (or  Quit):', 50)
  parse pull ox  .  1  ux . 1  x  .;   upper ux  /*get a decimal digit (maybe) from CBLF*/
  if abbrev('QUIT', ux, 1)  then signal halt     /*does the CBLF want to quit this game?*/
  if length(x)>1  then do;  say ___ pad '***error***  invalid input:  ' ox;  iterate;  end
  if x=''  then  iterate                         /*try again, CBLF didn't enter anything*/
  g=pos(x, $)                                    /*validate if the input digit is legal.*/
  if g==0  then say ___ pad '***error***  invalid digit:  '     ox
           else $=strip(reverse(left($,g))substr($,g+1))  /*reverse some (or all) digits*/
  end   /*score*/

say;    say ___  $;     say;    say center(' Congratulations! ', 70, "═");       say
say ___ pad  'Your score was' score;  exit       /*stick a fork in it,  we're all done. */
halt:  say  ___  pad  'quitting.';     exit      /*  "   "   "   "  "     "    "    "   */


# Project : Number reversal game

rever = 1:9
leftrever = []
for n = 1 to len(rever)
     rnd = random(8) + 1
     temp = rever[n]
     rever[n] = rever[rnd]
     rever[rnd] = temp
next
see rever
see nl
while true
         num = 0
         leftrever = []
         showarray(rever)
         see " : Reverse how many = "
         give r
         r = number(r)
         for n = 1 to r
               add(leftrever, rever[n])
         next
         leftrever = reverse(leftrever)
         for pos = 1 to r
               rever[pos] = leftrever[pos]
         next
         for m = 1 to len(rever)
              if rever[m] = m
                 num = num + 1
              ok
         next
         if num = len(rever)
            exit
         ok
end
see "You took " + num + " attempts." + nl

func swap(a, b)
       temp = a
       a = b
       b = temp
       return [a, b]

func showarray(vect)
       svect = ""
       for n = 1 to len(vect)
             svect = svect + vect[n] + " "
       next
       svect = left(svect, len(svect) - 1)
       see svect


ary = (1..9).to_a
ary.shuffle! while ary == ary.sort
score = 0
until ary == ary.sort
  print "#{ary.inspect} -- How many digits to reverse? "
  num = gets.to_i  # should validate input
  ary[0, num] = ary[0, num].reverse
  score += 1
end
p ary
puts "Your score: #{score}"


for i = 1 to 9  ' get numbers 1 to 9
 n(i) = i
next i
numShuffles = 3
' ----------------------------------
' shuffle numbers
' ----------------------------------
for 	i 	= 1 to 9 * numShuffles
	i1	= int(rnd(1)*9) + 1
	i2	= int(rnd(1)*9) + 1
	h2	= n(i1)
	n(i1)	= n(i2)
	n(i2)	= h2
next i

for i = 1 to 9
 a$ = a$ + str$(n(i)) + " "
next i
count = 0

[loop]
  count = count + 1
  print count;" : ";a$
    for i = 1 to 9                ' check if in sequence
      j = i * 2
      if mid$(a$,j-1,1) > mid$(a$,j,1) then goto [notOrdered]
    next i
  print "It took ";count;" tries"
end

[notOrdered]
input "How many numbers to flip:";i
i  = ((i-1) * 2) + 1
b$ = ""
for j = i to 1 step -2
   b$ = b$ + mid$(a$,j,2)
next j
a$  = b$ + mid$(a$,i + 2)
goto [loop]
end


use rand::prelude::*;
use std::io::stdin;

fn is_sorted(seq: &[impl PartialOrd]) -> bool {
    if seq.len() < 2 {
        return true;
    }
    // Look for any instance where the previous number is larger than the following
    !seq.iter()
        .zip(seq[1..].iter())
        .any(|(prev, foll)| prev > foll)
}

fn main() {
    println!(
        "Number reversal game:
    Given a jumbled list of the numbers 1 to 9, put the numbers in order.
    Each attempt you can reverse up to n digits starting from the left.
    The score is the count of the reversals needed to attain the ascending order."
    );
    let mut rng = thread_rng();

    let mut sequence: Vec<u8> = (1..10).collect();
    while is_sorted(&sequence) {
        sequence.shuffle(&mut rng);
    }

    let mut attempt = 1;
    while !is_sorted(&sequence) {
        println!(
            "Attempt {}: {:?} - How many numbers do you want to flip?",
            attempt, sequence
        );
        let flip = {
            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            input.trim().parse().unwrap()
        };
        sequence[..flip].reverse();
        attempt += 1;
    }
    println!(
        "Congrats! It took you {} attempts to sort the sequence.",
        attempt - 1 // Remove additionally counted attempt
    );
}


object NumberReversalGame extends App {
  def play(n: Int, cur: List[Int], goal: List[Int]) {
    readLine(s"""$n. ${cur mkString " "}  How many to flip? """) match {
      case null => println
      case s => scala.util.Try(s.toInt) match {
        case scala.util.Success(i) if i > 0 && i <= cur.length =>
          (cur.take(i).reverse ++ cur.drop(i)) match {
            case done if done == goal =>
              println(s"Congratulations! You solved "+goal.mkString(" "))
              println(s"Your score is $n (lower is better)")
            case next => play(n + 1, next, goal)
          }
        case _ => println(s"Choose a number between 1 and ${cur.length}")
          play(n + 1, cur, goal)
      }
    }
  }

  def play(size: Int) {
    val goal = List.range(1, size + 1)
    def init: List[Int] = scala.util.Random.shuffle(goal) match {
      case repeat if repeat == goal => init
      case done => done
    }
    play(1, init, goal)
  }

  play(9)
}


(import (scheme base)
        (scheme read)
        (scheme write)
        (srfi 1)   ; list functions
        (srfi 27)) ; random numbers

(random-source-randomize! default-random-source)

(define (make-randomised-list)
  (let ((vec (apply vector (iota 9 1))))
    (do ((c 0 (+ 1 c)))
      ((and (>= c 20)                            ; at least 20 tries
            (not (apply < (vector->list vec)))) ; ensures list not in order
       (vector->list vec))
      (let* ((i (random-integer 9)) ; swap two randomly chosen elements
             (j (random-integer 9))
             (tmp (vector-ref vec i)))
        (vector-set! vec i (vector-ref vec j))
        (vector-set! vec j tmp)))))

(define (play-game lst plays)
  (define (reverse-first n lst)
    (let-values (((start tail) (split-at lst n)))
                (append (reverse start) tail)))
  ;
  (display "List: ") (display lst) (newline)
  (display "How many numbers should be flipped? ")
  (let* ((flip (string->number (read-line)))
         (new-lst (reverse-first flip lst)))
    (if (apply < new-lst)
      (display (string-append "Finished in "
                              (number->string plays)
                              " attempts\n"))
      (play-game new-lst (+ 1 plays)))))

(play-game (make-randomised-list) 1)


$ include "seed7_05.s7i";

const proc: main is func
  local
    const array integer: sortedList is [] ( 1, 2, 3, 4, 5, 6, 7, 8, 9);
    var array integer: list is 0 times 0;
    var array integer: reversedList is 0 times 0;
    var integer: score is 0;
    var integer: index is 0;
    var integer: number is 0;
    var integer: reverse is 0;
  begin
    for number range sortedList do
      index := rand(1, succ(length(list)));
      list := list[.. pred(index)] & [] (number) & list[index ..];
    end for;
    repeat
      write("Current list: ");
      for number range list do
        write(number <& " ");
      end for;
      repeat
        write(" Digits to reverse? ");
        readln(reverse);
        if reverse < 2 or reverse > 9 then
          write("Please enter a value between 2 and 9.");
        end if;
      until reverse >= 2 and reverse <= 9;
      incr(score);
      reversedList := 0 times 0;
      for index range reverse downto 1 do
        reversedList &:= list[index];
      end for;
      list := reversedList & list[succ(reverse) ..];
    until list = sortedList;
    writeln("Congratulations, you sorted the list in " <& score <& " reversals.");
  end func;


// set the initial list of digits
set currentList to 1..9 sorted by random of a million

// make sure we don't start off already sorted
repeat while currentList equals 1..9
	sort currentList by random of a million
end repeat

// ask until it is solved
repeat while currentList isn't equal to 1..9
	add 1 to numberOfTurns
	set headline to "Turn #" & numberOfTurns & ":  You have " & currentList joined by empty

	ask "How many digits do you want to reverse?" titled headline message "On each turn, specify the number of initial digits to reverse."
	if it isn't a number then exit all -- allow the user to exit

	sort items 1 to it of currentList descending by the counter
end repeat

answer "You sorted it in " & numberOfTurns & " turns!" titled "Congratulations!"


var turn = 0;
var jumble = @(1..9).bshuffle;        # best-shuffle

for (turn; jumble != 1..9; ++turn) {
    printf("%2d: %s - Flip how many digits ? ", turn, jumble.join(' '));
    var d = read(Number) \\ break;
    jumble[0 .. d-1] = [jumble[0 .. d-1]].reverse...;
}

print "    #{jumble.join(' ')}\n";
print "You won in #{turn} turns.\n";


package require Tcl 8.5
# Simple shuffler, not very efficient but good enough for here
proc shuffle list {
    set result {}
    while {[llength $list]} {
	set i [expr {int([llength $list] * rand())}]
	lappend result [lindex $list $i]
	set list [lreplace $list $i $i]
    }
    return $result
}
# Returns the list with the prefix of it reversed
proc flipfirst {list n} {
    concat [lreverse [lrange $list 0 $n-1]] [lrange $list $n end]
}

# Core game engine; list to play with is optional argument
proc nrgame {{target "1 2 3 4 5 6 7 8 9"}} {
    set nums $target
    while {$nums eq $target} {set nums [shuffle $nums]}
    set goes 0
    while {$nums ne $target} {
	incr goes
	puts -nonewline "#${goes}: List is '[join $nums {, }]', how many to reverse? "
	flush stdout
	gets stdin n
	if {$n eq "q"} {return quit}
	# Input validation would go here
	set nums [flipfirst $nums $n]
    }
    return $goes
}

# Print some instructions and wait for the user to win
puts "Welcome to the Number Reversal Game!"
puts "------------------------------------"
puts "I'll show you a list of numbers, you need to reverse prefixes of them"
puts "to get the whole list in ascending order. A 'q' will quit early.\n"
puts ""
set outcome [nrgame]
if {$outcome ne "quit"} {
    puts "\nYou took $outcome attempts to put the digits in order."
}


RANDOMIZE

PRINT "Dada una lista aleatoria de números del 1 al 9,"
PRINT "indica cuantos dígitos de la izquierda voltear."
PRINT " El objetivo es obtener los dígitos en orden "
PRINT " con el 1 a la izquierda y el 9 a la derecha."
PRINT

DIM nums(1 to 9)
DIM temp(1 to 9)
!valores iniciales
FOR x = 1 to 9
    LET nums(x) = x
NEXT x

DO                                !barajamos
   FOR x = 9 to 2 step -1
       LET n = round(int(rnd*(x))+1)
       IF n <> x then
          !swap (nums(n), nums(x)) !no existe comado SWAP
          LET temp(n) = nums(x)
          LET nums(x) = nums(n)
          LET nums(n) = temp(n)
       END IF
   NEXT x
   FOR x = 1 to 8                 !nos aseguramos que no estén en orden
       IF nums(x) > nums(x+1) then EXIT DO
   NEXT x
LOOP

LET denuevo = -1
DO
   IF intentos < 10 then PRINT " ";
   PRINT intentos; ":";
   FOR x = 1 to 9
       PRINT nums(x);
   NEXT x

   IF (not denuevo <> 0) then EXIT DO

   INPUT prompt " -- ¿Cuántos volteamos? ": volteo
   IF volteo < 0 or volteo > 9 then LET volteo = 0

   FOR x = 1 to (ip(volteo/2))
       !swap (nums(x), nums(volteo-x+1))  !no existe SWAP
       LET temp(n) = nums(volteo-x+1)
       LET nums(volteo-x+1) = nums(x)
       LET nums(x) = temp(n)
   NEXT x

   LET denuevo = 0
   !comprobamos el orden
   FOR x = 1 to 8
       IF nums(x) > nums(x+1) then
          LET denuevo = -1
          EXIT FOR
       END IF
   NEXT x

   IF volteo > 0 then LET intentos = intentos+1
LOOP

PRINT
PRINT
PRINT "Necesitaste "; ltrim$(rtrim$(str$(intentos))); " intentos."
END


$$ MODE TUSCRIPT
numbers=RANDOM_NUMBERS (1,9,9),nr=0

SECTION check
LOOP o,n=numbers
 IF (n!=o) THEN
  DO PRINT
  EXIT
 ELSEIF (n==9&&o==9) THEN
  DO PRINT
  PRINT " You made it ... in round ",r
  STOP
 ELSE
  CYCLE
 ENDIF
ENDLOOP
ENDSECTION

SECTION print
  PRINT numbers
ENDSECTION

DO PRINT
LOOP r=1,14
IF (nr>=0&&nr<10) THEN
  ASK "Reverse - how many?": nr=""
  i=""
  LOOP n=1,nr
   i=APPEND(i,n)
  ENDLOOP
  numbers   =SPLIT (numbers)
  reverse_nr=SELECT (numbers,#i,keep_nr), reverse_nr=REVERSE(reverse_nr)
  numbers   =APPEND (reverse_nr,keep_nr), numbers   =JOIN   (numbers)
  DO check
ENDIF
ENDLOOP


print "\nWelcome to the number reversal game!\n"

print "You must put the numbers in order from 1 to 9."
print "Your only moves are to reverse groups of numbers"
print "on the left side of the list."

integer list score

# start a new game
function newgame {
	integer i j t

	# score = number of moves
	((score = 0))

	# list = array of numbers
	set -A list 1 2 3 4 5 6 7 8 9
	while true; do
		# Knuth shuffle
		((i = 9))
		while ((i > 1)); do
			# get random j from 0 to i - 1
			((j = RANDOM))
			((j < 32768 % i)) && continue
			((j %= i))

			# decrement i, swap list[i] with list[j]
			((i -= 1))
			((t = list[i]))
			((list[i] = list[j]))
			((list[j] = t))
		done
		win || break
	done
}

# numbers in order?
function win {
	integer i

	# check if list[0] == 1, list[1] == 2, ...
	((i = 0))
	while ((i < 9)); do
		((list[i] != i + 1)) && return 1
		((i += 1))
	done
	return 0
}

# reverse first $1 elements of list
function reverse {
	integer left right t

	((left = 0))
	((right = $1 - 1))
	while ((right > left)); do
		((t = list[left]))
		((list[left] = list[right]))
		((list[right] = t))
		((left += 1))
		((right -= 1))
	done
}

integer i

newgame
while true; do
	print -n "\nYour list: "
	((i = 0))
	while ((i < 8)); do
		printf "%d, " ${list[i]}
		((i += 1))
	done
	printf "%d\n" ${list[8]}

	if win; then
		print "YOU WIN!"
		printf "Your score is %d moves.\n" $score
		print -n "Would you like to play again (y/n)? "

		if read again && [[ $again = @(y|Y)* ]]; then
			newgame
		else
			print "\n\nBye!"
			exit
		fi
	else
		print -n "How many numbers to reverse? "

		if read i; then
			((score += 1))
			reverse $i
		else
			print "\n\nBye!"
			exit
		fi
	fi
done


Private Function shuffle(ByVal a As Variant) As Variant
    Dim t As Variant, i As Integer
    For i = UBound(a) To LBound(a) + 1 Step -1
        j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
        t = a(i)
        a(i) = a(j)
        a(j) = t
    Next i
    shuffle = a
End Function
Private Sub reverse(ByRef a As Variant, n As Integer)
    Dim b As Variant
    b = a
    For i = 1 To n
        a(i) = b(n + 1 - i)
    Next i
End Sub
Public Sub game()
    Debug.Print "Given a jumbled list of the numbers 1 to 9"
    Debug.Print "you must select how many digits from the left to reverse."
    Debug.Print "Your goal is to get the digits in order with 1 on the left and 9 on the right."

    inums = [{1,2,3,4,5,6,7,8,9}]
    Dim nums As Variant
    Dim turns As Integer, flip As Integer

    shuffled = False
    Do While Not shuffled
        nums = shuffle(inums)
        For i = LBound(nums) To UBound(nums)
            If nums(i) <> inums(i) Then
                shuffled = True
                Exit For
            End If
        Next i
    Loop

    Do While True
        Debug.Print turns; ":";
        For Each x In nums: Debug.Print x;: Next x
        Debug.Print
        flag = False
        For i = LBound(nums) To UBound(nums)
            If nums(i) <> inums(i) Then
                flag = True
                Exit For
            End If
        Next i
        If flag Then
            flip = InputBox(" -- How many numbers should be flipped? ")
            reverse nums, flip
            turns = turns + 1
        Else
            Exit Do
        End If
    Loop

    Debug.Print "You took"; turns; "turns to put the digits in order."
End Sub


import "/sort" for Sort
import "random" for Random
import "io" for Stdin, Stdout

var r= Random.new()
var count = 0
var numbers = [0] * 9
numbers[0] = r.int(2, 10) // this will ensure list isn't ascending
for (i in 1..8) {
    var rn
    while(true) {
        rn = r.int(1, 10)
        if (!numbers.contains(rn)) break
    }
    numbers[i] = rn
}
System.print("Here's your first list : %(numbers)")
while (true) {
    var rev
    while (true) {
        System.write("How many numbers from the left are to be reversed : ")
        Stdout.flush()
        rev = Num.fromString(Stdin.readLine())
        if (rev.type == Num && rev.isInteger && rev >= 2 && rev <= 9) break
    }
    count = count + 1
    var i = 0
    var j = rev - 1
    while (i < j) {
        var temp = numbers[i]
        numbers[i] = numbers[j]
        numbers[j] = temp
        i = i + 1
        j = j - 1
    }
    if (Sort.isSorted(numbers)) {
        System.print("Here's your final list : %(numbers)")
        break
    }
    System.print("Here's your list now   : %(numbers)")
}
System.print("So you've completed the game with a score of %(count)")


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");
]


// Rosetta Code problem: https://www.rosettacode.org/wiki/Number_reversal_game
// by Jjuanhdez, 06/2022

print "Given a jumbled list of the numbers 1 to 9,   "
print "you must select how many digits from the left "
print "to reverse. Your goal is to get the digits in "
print "order with 1 on the left and 9 on the right.\n"

dim nums(10)
dim a(10)
intentos = 0: denuevo = true: colum = 6

//valores iniciales
for i = 1 to 9
    nums(i) = i
next i

for i = 9 to 2 step -1
    n = int(ran(i)) + 1
    if n <> i then
        a(i) = nums(i)
        nums(i) = nums(n)
        nums(n) = a(i)
    fi
next i

repeat
    if intentos < 10  print " ";
    print intentos, ": ";
    for i = 1 to 9
        print nums(i), " ";
    next i

    if not denuevo  break

    input "  -- How many do we flip " volteo
    if volteo < 0 or volteo > 9  volteo = 0

    for i = 1 to int(volteo / 2)
        a(i) = nums(volteo - i + 1)
        nums(volteo - i + 1) = nums(i)
        nums(i) = a(i)
    next i

    denuevo = false
    //comprobamos el orden
    for i = 1 to 8
        if nums(i) > nums(i + 1) then
            denuevo = true
            break
        fi
    next i

    if volteo > 0  intentos = intentos + 1
until false
print "\n\n   You needed ", intentos, " attempts."
end


correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len();
correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string
attempts:=0;
while(scrambledList!=correctList){ // Repeat until the sequence is correct
   n:=ask(("[%d] %s How many numbers (from the left) should be flipped? ")
	      .fmt(attempts,scrambledList));
   try{ n=n.toInt() }catch{ println("Not a number"); continue; }
   if(not (0<=n<N)){ println("Out of range"); continue; }
   attempts+=1;
   // Reverse the first part of the string and add the second part
   scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts));


V n = 33
print(bin(n)‘ ’String(n, radix' 8)‘ ’n‘ ’hex(n))


INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit

PROC Main()
  CARD ARRAY v=[6502 1977 2021 256 1024 12345 9876 1111 0 16]
  BYTE i,LMARGIN=$52,old

  old=LMARGIN
  LMARGIN=0 ;remove left margin on the screen
  Put(125) PutE() ;clear the screen

  FOR i=0 TO 9
  DO
    PrintF("(dec) %D = (hex) %H = (oct) %O%E",v(i),v(i),v(i))
  OD

  LMARGIN=old ;restore left margin on the screen
RETURN


with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
with Ada.Text_IO;          use Ada.Text_IO;

procedure Test_Integer_Text_IO is
begin
  for I in 1..33 loop
    Put (I, Width =>3, Base=> 10);
    Put (I, Width =>7, Base=> 16);
    Put (I, Width =>6, Base=>  8);
    New_Line;
  end loop;
end Test_Integer_Text_IO;


main:(
  FOR i TO 33 DO
    printf(($10r6d," "16r6d," "8r6dl$, BIN i, BIN i, BIN i))
  OD
)


begin
    % print some numbers in hex %
    for i := 0 until 20 do write( intbase16( i ) )
end.


MsgBox % BC("FF",16,3) ; -> 100110 in base 3 = FF in hex = 256 in base 10

BC(NumStr,InputBase=8,OutputBase=10) {
  Static S = 12345678901234567890123456789012345678901234567890123456789012345
  DllCall("msvcrt\_i64toa","Int64",DllCall("msvcrt\_strtoui64","Str",NumStr,"Uint",0,"UInt",InputBase,"CDECLInt64"),"Str",S,"UInt",OutputBase,"CDECL")
  Return S
}


loop 0..33 'i ->
    print [
        pad as.binary i 6
        pad as.octal i 2
        pad to :string i 2
        pad as.hex i 2
    ]


      REM STR$ converts to a decimal string:
      PRINT STR$(0)
      PRINT STR$(123456789)
      PRINT STR$(-987654321)

      REM STR$~ converts to a hexadecimal string:
      PRINT STR$~(43981)
      PRINT STR$~(-1)


for(i=1;i<10;i++) {
  obase=10; print i," "
  obase=8; print i," "
  obase=3; print i," "
  obase=2; print i
  print "\n"
}


#include <stdio.h>

int main()
{
  int i;

  for(i=1; i <= 33; i++)
    printf("%6d %6x %6o\n", i, i, i);

  return 0;
}


using System;

namespace NonDecimalRadicesOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 42; i++)
            {
                string binary = Convert.ToString(i, 2);
                string octal = Convert.ToString(i, 8);
                string hexadecimal = Convert.ToString(i, 16);
                Console.WriteLine(string.Format("Decimal: {0}, Binary: {1}, Octal: {2}, Hexadecimal: {3}", i, binary, octal, hexadecimal));
            }

            Console.ReadKey();
        }
    }
}


#include <iostream>
#include <iomanip>

int main()
{
  for (int i = 0; i <= 33; i++)
    std::cout << std::setw(6) << std::dec << i << " "
              << std::setw(6) << std::hex << i << " "
              << std::setw(6) << std::oct << i << std::endl;

  return 0;
}


(Integer/toBinaryString 25) ; returns "11001"
(Integer/toOctalString 25)  ; returns "31"
(Integer/toHexString 25)    ; returns "19"

(dotimes [i 20]
  (println (Integer/toHexString i)))


(loop for n from 0 to 33 do
  (format t " ~6B ~3O ~2D ~2X~%" n n n n))


[ dn [ ]P ]sp
[
     2o lpx
     8o lpx
    10o lpx
    16o lpx
    17o lpx
    AP
    1+ d21>b
]sb
1 lbx


for value in 0..33 {
  for base in [2, 8, 10, 12, 16, 36] {
    def s := value.toString(base)
    print(" " * (8 - s.size()), s)
  }
  println()
}


for i = 1 to 33 do
    printf(1,"%6d %6x %6o\n",{i,i,i})
end for


let ns = [30..33]
ns |> Seq.iter (fun n -> printfn " %3o %2d %2X" n n n)


1234567 2 36 [a,b] [ >base print ] with each


: main 34 1 do cr i dec. i hex. loop ;
main
...
11 $B
...


' FB 1.05.0 Win64

Dim ui(1 To 4) As UInteger = {10, 26, 52, 100}
Print "Decimal    Hex       Octal    Binary"
Print "=======  ========   =======   ======"
For i As Integer = 1 To 4
  Print Str(ui(i)); Tab(12); Hex(ui(i)); Tab(23); Oct(ui(i)); Tab(31); Bin(ui(i))
Next

Sleep


package main

import (
    "fmt"
    "math/big"
    "strconv"
)

func main() {
    // fmt.Print formats integer types directly as bases 2, 8, 10, and 16.
    fmt.Printf("%b\n", 13)
    fmt.Printf("%o\n", 13)
    fmt.Printf("%d\n", 13)
    fmt.Printf("%x\n", 13)
    // big ints work with fmt as well.
    d := big.NewInt(13)
    fmt.Printf("%b\n", d)
    fmt.Printf("%o\n", d)
    fmt.Printf("%d\n", d)
    fmt.Printf("%x\n", d)
    // strconv.FormatInt handles arbitrary bases from 2 to 36 for the
    // int64 type.  There is also strconv.FormatUInt for the uint64 type.
    // There no equivalent for big ints.
    fmt.Println(strconv.FormatInt(1313, 19))
}


import Text.Printf

main :: IO ()
main = mapM_ f [0..33] where
  f :: Int -> IO ()
  f n = printf " %3o %2d %2X\n" n n n -- binary not supported


procedure main()
write("Non-decimal radices/Output")
every i := 255 | 2 | 5 | 16 do {
   printf("%%d = %d\n",i) # integer format
   printf("%%x = %x\n",i) # hex format
   printf("%%o = %o\n",i) # octal format
   printf("%%s = %s\n",i) # string format
   printf("%%i = %i\n",i) # image format
   }
end


public static void main(String args[]){
   for(int a= 0;a < 33;a++){
      System.out.println(Integer.toBinaryString(a));
      System.out.println(Integer.toOctalString(a));
      System.out.println(Integer.toHexString(a));
      //the above methods treat the integer as unsigned
      //there are also corresponding Long.to***String() methods for long's.

      System.out.printf("%3o %2d %2x\n",a ,a ,a); //printf like the other languages; binary not supported
   }
}


var bases = [2, 8, 10, 16, 24];
for (var n = 0; n <= 33; n++) {
    var row = [];
    for (var i = 0; i < bases.length; i++)
        row.push( n.toString(bases[i]) );
    print(row.join(', '));
}


using Primes, Printf

println("Primes ≤ $hi written in common bases.")
@printf("%8s%8s%8s%8s", "bin", "oct", "dec", "hex")
for i in primes(50)
    @printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i))
end


include ..\Utilitys.tlhy

33 [
    ( "decimal: " swap " bin: " over 8 itob reverse ) lprint nl
] for

"End " input


// version 1.1.2

fun main(args: Array<String>) {
    val bases = intArrayOf(2, 8, 10, 16, 19, 36)
    for (base in bases) print("%6s".format(base))
    println()
    println("-".repeat(6 * bases.size))
    for (i in 0..35) {
        for (base in bases) print("%6s".format(i.toString(base)))
        println()
    }
}


10 FOR i=1 TO 20
20 PRINT i,BIN$(i),HEX$(i)
30 NEXT


for i = 1, 33 do
    print( string.format( "%o \t %d \t %x", i, i, i ) )
end


Table[IntegerString[n,b], {n,[email protected]}, {b,{2,8,16,36}}] // Grid


MODULE Conv EXPORTS Main;

IMPORT IO, Fmt;

BEGIN
  FOR i := 1 TO 33 DO
    IO.Put(Fmt.Int(i, base := 10) & " ");
    IO.Put(Fmt.Int(i, base := 16) & " ");
    IO.Put(Fmt.Int(i, base := 8) & " ");
    IO.Put("\n");
  END;
END Conv.


/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.util.Formatter

loop i_ = 1 to 3
  loop n_ = 20 to 20000 by 2131
    select case i_
      when 1 then say useBif(n_)
      when 2 then say useJavaFormat(n_)
      when 3 then say useJavaNumber(n_)
      otherwise nop
      end
    end n_
  say
end i_

return

-- NetRexx doesn't have a decimal to octal conversion
method useBif(n_) public static
  d_ = '_'
  return '[Base 16='n_.d2x().right(8)',Base 10='n_.right(8)',Base 8='d_.right(8)',Base 2='n_.d2x().x2b().right(20)']'

-- Some of Java's java.lang.Number classes have conversion methods
method useJavaNumber(n_) public static
  nx = Long.toHexString(n_)
  nd = Long.toString(n_)
  no = Long.toOctalString(n_)
  nb = Long.toBinaryString(n_)
  return '[Base 16='Rexx(nx).right(8)',Base 10='Rexx(nd).right(8)',Base 8='Rexx(no).right(8)',Base 2='Rexx(nb).right(20)']'

-- Java Formatter doesn't have a decimal to binary conversion
method useJavaFormat(n_) public static
  fb = StringBuilder()
  fm = Formatter(fb)
  fm.format("[Base 16=%1$8x,Base 10=%1$8d,Base 8=%1$8o,Base 2=%2$20s]", [Object Long(n_), String('_')])
  return fb.toString()


import strutils

for i in 0..33:
  echo toBin(i, 6)," ",toOct(i, 3)," ",align($i,2)," ",toHex(i,2)


for n = 0 to 33 do
  Printf.printf " %3o %2d %2X\n" n n n (* binary not supported *)
done


printbinary(n)={
  n=binary(n);
  for(i=1,#n,print1(n[i]))
};
printdecimal(n)={
  print1(n)
};


with javascript_semantics
for i=2 to 32 by 10 do
    printf(1,"decimal:%3d hex:%3x octal:%3o binary:%7b\n",i)
end for


33 for
  dup "decimal: " print print " bin: " print 8 int>bit print nl
endfor


<?php
foreach (range(0, 33) as $n) {
  echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>


(de printNumber (N Base)
   (when (>= N Base)
      (printNumber (/ N Base) Base) )
   (let C (% N Base)
      (and (> C 9) (inc 'C 39))
      (prin (char (+ C `(char "0")))) ) )

(printNumber 26 16))
(prinl)
(printNumber 123456789012345678901234567890 36))
(prinl)


get list (n);
put skip list (n);      /* Prints N in decimal */
put skip edit (n) (B);  /* prints N as a bit string, N > 0 */


foreach ($n in 0..33) {
    "Base 2:  " + [Convert]::ToString($n, 2)
    "Base 8:  " + [Convert]::ToString($n, 8)
    "Base 10: " + $n
    "Base 10: " + [Convert]::ToString($n, 10)
    "Base 10: " + ("{0:D}" -f $n)
    "Base 16: " + [Convert]::ToString($n, 16)
    "Base 16: " + ("{0:X}" -f $n)
}


For i=105 To 115
  Bin$=RSet(Bin(i),8,"0") ;- Convert to wanted type & pad with '0'
  Hex$=RSet(Hex(i),4,"0")
  Dec$=RSet(Str(i),3)
  PrintN(Dec$+" decimal = %"+Bin$+" = $"+Hex$+".")
Next


for n in range(34):
  print " %3o %2d %2X" % (n, n, n)


# dec to oct
as.octmode(x)
# dec to hex
as.hexmode(x)
# oct or hex to dec
as.integer(x)
# or
as.numeric(x)


/*REXX pgm shows REXX's ability to show decimal numbers in binary & hex.*/

      do j=0  to 50                /*show some low-value num conversions*/
      say right(j,3)         ' in decimal is',
          right(d2b(j),12)   " in binary",
          right(d2x(j),12)   ' in hexadecimal.'
      end   /*j*/
exit                                   /*stick a fork in it, we're done.*/
/*────────────────────────────D2B subroutine────────────────────────────*/
d2b: return word(strip(x2b(d2x(arg(1))),'L',0) 0,1)  /*convert dec──►bin*/


# Project : Non Decimal radices/Output

see string(0) + nl
see string(123456789) + nl
see string(-987654321) + nl

see upper(hex(43981)) + nl
see upper(hex(-1)) + nl


fn main() {
    // To render the number as string, use format! macro instead
    println!("Binary: {:b}", 0xdeadbeefu32);
    println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
    println!("Octal: {:o}", 0xdeadbeefu32);
    println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
    println!("Decimal: {}", 0xdeadbeefu32);
    println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
    println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
    println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
    println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}


print asc("X")      ' convert to ascii
print chr$(169)     ' ascii to character
print dechex$(255)    ' decimal to hex
print hexdec("FF")    ' hex to decimal
print str$(467)     ' decimal to string
print val("27")     ' string to decimal


object Main extends App {
  val radices = List(2, 8, 10, 16, 19, 36)
  for (base <- radices) print(f"$base%6d")
  println(s"""\n${"-" * (6 * radices.length)}""")
  for (i <- BigInt(0) to 35; // BigInt has a toString(radix) method
       radix <- radices;
       eol = if (radix == radices.last) '\n' else '\0'
  ) print(f"${i.toString(radix)}%6s$eol")
}


(do ((i 0 (+ i 1)))
    ((>= i 33))
    (display (number->string i 2)) ; binary
    (display "  ")
    (display (number->string i 8)) ; octal
    (display "  ")
    (display (number->string i 10)) ; decimal, the "10" is optional
    (display "  ")
    (display (number->string i 16)) ; hex
    (newline))


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: i is 0;
  begin
    for i range 1 to 33 do
      writeln(i lpad 6 <&
              i radix 8 lpad 6 <&
              i radix 16 lpad 6);
    end for;
  end func;


1 to: 33 do: [ :i |
  ('%1 %2 %3' % { i printStringRadix: 8. i printStringRadix: 16. i printStringRadix: 2 })
  printNl.
].


let
  fun loop i =
    if i < 34 then (
      print (Int.fmt StringCvt.BIN i ^ "\t"
           ^ Int.fmt StringCvt.OCT i ^ "\t"
           ^ Int.fmt StringCvt.DEC i ^ "\t"
           ^ Int.fmt StringCvt.HEX i ^ "\n");
      loop (i+1)
    ) else ()
in
  loop 0
end


for {set n 0} {$n <= 33} {incr n} {
    puts [format " %3o %2d %2X" $n $n $n]
}


Local old
getMode("Base")→old
setMode("Base", "BIN")
Disp string(16)
setMode("Base", "HEX")
Disp string(16)
setMode("Base", "DEC")
Disp string(16)
setMode("Base", old)


include c:\cxpl\codes;
int N;
[N:= 2;
repeat  HexOut(0, N);  Text(0, "  ");
        IntOut(0, N);  CrLf(0);
        N:= N*N;
until   N=0;
]


for i = 1 to 33
  print "decimal: ", i, " hex: ", hex$(i), " bin: ", bin$(i)
next


const N=16;
var fmt=[2..N].pump(String,"%%5.%dB".fmt);  // %5.2B%5.3B%5.4B%5.5B ...
foreach n in (17){fmt.fmt(n.pump(N,List,n.fp(n)).xplode()).println()}


F nonoblocks([Int] &blocks, Int cells) -> [[(Int, Int)]]
   [[(Int, Int)]] r
   I blocks.empty | blocks[0] == 0
      r [+]= [(0, 0)]
   E
      assert(sum(blocks) + blocks.len - 1 <= cells, ‘Those blocks will not fit in those cells’)
      V (blength, brest) = (blocks[0], blocks[1..])
      V minspace4rest = sum(brest.map(b -> 1 + b))

      L(bpos) 0 .. cells - minspace4rest - blength
         I brest.empty
            r [+]= [(bpos, blength)]
         E
            V offset = bpos + blength + 1
            L(subpos) nonoblocks(&brest, cells - offset)
               V rest = subpos.map((bp, bl) -> (@offset + bp, bl))
               V vec = [(bpos, blength)] [+] rest
               r [+]= vec
   R r

F pblock(vec, cells)
   ‘Prettyprints each run of blocks with a different letter A.. for each block of filled cells’
   V vector = [‘_’] * cells
   L(bp_bl) vec
      V ch = L.index + ‘A’.code
      V (bp, bl) = bp_bl
      L(i) bp .< bp + bl
         vector[i] = I vector[i] == ‘_’ {Char(code' ch)} E Char(‘?’)
   R ‘|’vector.join(‘|’)‘|’

L(blocks, cells) [
      ([2, 1], 5),
      ([Int](), 5),
      ([8], 10),
      ([2, 3, 2, 3], 15)
      ]
   print("\nConfiguration:\n    #. ## #. cells and #. blocks".format(pblock([(Int, Int)](), cells), cells, blocks))
   print(‘  Possibilities:’)
   V nb = nonoblocks(&blocks, cells)
   L(vector) nb
      print(‘    ’pblock(vector, cells))
   print(‘  A total of #. Possible configurations.’.format(nb.len))


DEFINE MAX_BLOCKS="10"
DEFINE NOT_FOUND="255"

BYTE FUNC GetBlockAtPos(BYTE p BYTE ARRAY blocks,pos INT count)
  INT i
  FOR i=0 TO count-1
  DO
    IF p>=pos(i) AND p<pos(i)+blocks(i) THEN
      RETURN (i)
    FI
  OD
RETURN (NOT_FOUND)

PROC PrintResult(BYTE cells BYTE ARRAY blocks,pos INT count)
  BYTE i,b

  Print("[")
  FOR i=0 TO cells-1
  DO
    b=GetBlockAtPos(i,blocks,pos,count)
    IF b=NOT_FOUND THEN
      Put('.)
    ELSE
      Put(b+'A)
    FI
  OD
  PrintE("]")
RETURN

BYTE FUNC LeftMostPos(BYTE cells BYTE ARRAY blocks,pos INT count,startFrom)
  INT i

  FOR i=startFrom TO count-1
  DO
    pos(i)=pos(i-1)+blocks(i-1)+1
    IF pos(i)+blocks(i)>cells THEN
      RETURN (0)
    FI
  OD
RETURN (1)

BYTE FUNC MoveToRight(BYTE cells BYTE ARRAY blocks,pos INT count,startFrom)
  pos(startFrom)==+1
  IF pos(startFrom)+blocks(startFrom)>cells THEN
    RETURN (0)
  FI
RETURN (LeftMostPos(cells,blocks,pos,count,startFrom+1))

PROC Process(BYTE cells BYTE ARRAY blocks INT count)
  BYTE ARRAY pos(MAX_BLOCKS)
  BYTE success
  INT current

  IF count=0 THEN
    PrintResult(cells,blocks,pos,count)
    RETURN
  FI

  pos(0)=0
  success=LeftMostPos(cells,blocks,pos,count,1)
  IF success=0 THEN
    PrintE("No solutions")
    RETURN
  FI
  current=count-1
  WHILE success
  DO
    PrintResult(cells,blocks,pos,count)
    DO
      success=MoveToRight(cells,blocks,pos,count,current)
      IF success THEN
        current=count-1
      ELSE
        current==-1
        IF current<0 THEN
          EXIT
        FI
      FI
    UNTIL success
    OD
  OD
RETURN

PROC Test(BYTE cells BYTE ARRAY blocks INT count)
  BYTE CH=$02FC ;Internal hardware value for last key pressed
  INT i

  PrintB(cells) Print(" cells [")
  FOR i=0 TO count-1
  DO
    PrintB(blocks(i))
    IF i<count-1 THEN
      Put(32)
    FI
  OD
  PrintE("]")

  Process(cells,blocks,count)

  PutE()
  PrintE("Press any key to continue...")
  DO UNTIL CH#$FF OD
  CH=$FF
  PutE()
RETURN

PROC Main()
  BYTE ARRAY t1=[2 1],t2=[],t3=[8],t4=[2 3 2 3],t5=[2 3]

  Test(5,t1,2)
  Test(5,t2,0)
  Test(10,t3,1)
  Test(15,t4,4)
  Test(5,t5,2)
RETURN


;-------------------------------------------
NonoBlock(cells, blocks){
    result := [], line := ""
    for i, v in blocks
        B .= v ", "
    output := cells " cells and [" Trim(B, ", ") "] blocks`n"

    if ((Arr := NonoBlockCreate(cells, blocks)) = "Error")
        return output "No Solution`n"
    for i, v in arr
        line.= v ";"
    result[line] := true
    result := NonoBlockRecurse(Arr, result)
    output .= NonoBlockShow(result)
    return output
}
;-------------------------------------------
; create cells+1 size array, stack blocks to left with one gap in between
; gaps are represented by negative number
; stack extra gaps to far left
; for example : 6 cells and [2, 1] blocks
; returns [-2, 2, -1, 1, 0, 0, 0]
NonoBlockCreate(cells, blocks){
    Arr := [], B := blocks.Count()
    if !B									; no blocks
        return [0-cells, 0]
    for i, v in blocks{
        total += v
        Arr.InsertAt(1, blocks[B-A_Index+1])
        Arr.InsertAt(1, -1)
    }
    if (cells < total + B-1)				; not possible
        return "Error"
    Arr[1] := total + B-1 - cells
    loop % cells - Arr.Count() + 1
        Arr.Push(0)
    return Arr
}
;-------------------------------------------
; shift negative numbers from left to right recursively.
; preserve at least one gap between blocks.
; [-2, 2, -1, 1, 0, 0, 0]
; [-1, 2, -2, 1, 0, 0, 0]
NonoBlockRecurse(Arr, result, pos:= 1){
    i := pos-1
    while (i < Arr.count())
    {
        if ((B:=Arr[++i])>=0) || (B=-1 && i>1)
            continue
        if (i=Arr.count()-1)
            return result
        Arr[i] := ++B, Arr[i+2] := Arr[i+2] -1
        result := NonoBlockRecurse(Arr.Clone(), result, i)
        line := []
        for k, v in Arr
            line.=v ";"
        result[line] := true
    }
    return result
}
;-------------------------------------------
; represent positve numbers by a block of "#", negative nubmers by a block of "."
NonoBlockShow(result){
    for line in result{
        i := A_Index
        nLine := ""
        for j, val in StrSplit(line, ";")
            loop % Abs(val)
                nLine .= val > 0 ? "#" : "."
        output .= nLine "`n"
    }
    Sort, output, U
    return output
}
;-------------------------------------------


#include <stdio.h>
#include <string.h>

void nb(int cells, int total_block_size, int* blocks, int block_count,
        char* output, int offset, int* count) {
    if (block_count == 0) {
        printf("%2d  %s\n", ++*count, output);
        return;
    }
    int block_size = blocks[0];
    int max_pos = cells - (total_block_size + block_count - 1);
    total_block_size -= block_size;
    cells -= block_size + 1;
    ++blocks;
    --block_count;
    for (int i = 0; i <= max_pos; ++i, --cells) {
        memset(output + offset, '.', max_pos + block_size);
        memset(output + offset + i, '#', block_size);
        nb(cells, total_block_size, blocks, block_count, output,
           offset + block_size + i + 1, count);
    }
}

void nonoblock(int cells, int* blocks, int block_count) {
    printf("%d cells and blocks [", cells);
    for (int i = 0; i < block_count; ++i)
        printf(i == 0 ? "%d" : ", %d", blocks[i]);
    printf("]:\n");
    int total_block_size = 0;
    for (int i = 0; i < block_count; ++i)
        total_block_size += blocks[i];
    if (cells < total_block_size + block_count - 1) {
        printf("no solution\n");
        return;
    }
    char output[cells + 1];
    memset(output, '.', cells);
    output[cells] = '\0';
    int count = 0;
    nb(cells, total_block_size, blocks, block_count, output, 0, &count);
}

int main() {
    int blocks1[] = {2, 1};
    nonoblock(5, blocks1, 2);
    printf("\n");

    nonoblock(5, NULL, 0);
    printf("\n");

    int blocks2[] = {8};
    nonoblock(10, blocks2, 1);
    printf("\n");

    int blocks3[] = {2, 3, 2, 3};
    nonoblock(15, blocks3, 4);
    printf("\n");

    int blocks4[] = {2, 3};
    nonoblock(5, blocks4, 2);

    return 0;
}


using System;
using System.Linq;
using System.Text;

public static class Nonoblock
{
    public static void Main() {
        Positions(5, 2,1);
        Positions(5);
        Positions(10, 8);
        Positions(15, 2,3,2,3);
        Positions(5, 2,3);
    }

    public static void Positions(int cells, params int[] blocks) {
        if (cells < 0 || blocks == null || blocks.Any(b => b < 1)) throw new ArgumentOutOfRangeException();
        Console.WriteLine($"{cells} cells with [{string.Join(", ", blocks)}]");
        if (blocks.Sum() + blocks.Length - 1 > cells) {
            Console.WriteLine("No solution");
            return;
        }
        var spaces = new int[blocks.Length + 1];
        int total = -1;
        for (int i = 0; i < blocks.Length; i++) {
            total += blocks[i] + 1;
            spaces[i+1] = total;
        }
        spaces[spaces.Length - 1] = cells - 1;
        var sb = new StringBuilder(string.Join(".", blocks.Select(b => new string('#', b))).PadRight(cells, '.'));
        Iterate(sb, spaces, spaces.Length - 1, 0);
        Console.WriteLine();
    }

    private static void Iterate(StringBuilder output, int[] spaces, int index, int offset) {
        Console.WriteLine(output.ToString());
        if (index <= 0) return;
        int count = 0;
        while (output[spaces[index] - offset] != '#') {
            count++;
            output.Remove(spaces[index], 1);
            output.Insert(spaces[index-1], '.');
            spaces[index-1]++;
            Iterate(output, spaces, index - 1, 1);
        }
        if (offset == 0) return;
        spaces[index-1] -= count;
        output.Remove(spaces[index-1], count);
        output.Insert(spaces[index] - count, ".", count);
    }

}


#include <iomanip>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

typedef std::pair<int, std::vector<int> > puzzle;

class nonoblock {
public:
    void solve( std::vector<puzzle>& p ) {
        for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) {
            counter = 0;
            std::cout << " Puzzle: " << ( *i ).first << " cells and blocks [ ";
            for( std::vector<int>::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ )
                std::cout << *it << " ";
            std::cout << "] ";
            int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 );
            if( ( *i ).first - s < 0 ) {
                std::cout << "has no solution!\n\n\n";
                continue;
            }
            std::cout << "\n Possible configurations:\n\n";
            std::string b( ( *i ).first, '-' );
            solve( *i, b, 0 );
            std::cout << "\n\n";
        }
    }

private:
    void solve( puzzle p, std::string n, int start ) {
        if( p.second.size() < 1 ) {
            output( n );
            return;
        }
        std::string temp_string;
        int offset,
            this_block_size = p.second[0];

        int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 );
        space_need_for_others += p.second.size() - 1;

        int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 );

        std::vector<int> v1( p.second.size() - 1 );
        std::copy( p.second.begin() + 1, p.second.end(), v1.begin() );
        puzzle p1 = std::make_pair( space_need_for_others, v1 );

        for( int a = 0; a < space_for_curr_block; a++ ) {
            temp_string = n;

            if( start + this_block_size > n.length() ) return;

            for( offset = start; offset < start + this_block_size; offset++ )
                temp_string.at( offset ) = 'o';

            if( p1.first ) solve( p1, temp_string, offset + 1 );
            else output( temp_string );

            start++;
        }
    }
    void output( std::string s ) {
        char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 );
        bool f = false;
        std::cout << std::setw( 3 ) << ++counter << "\t|";
        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
            b += ( *i ) == 'o' && f ? 1 : 0;
            std::cout << ( ( *i ) == 'o' ? b : '_' ) << "|";
            f = ( *i ) == '-' ? true : false;
        }
        std::cout << "\n";
    }

    unsigned counter;
};

int main( int argc, char* argv[] )
{
    std::vector<puzzle> problems;
    std::vector<int> blocks;
    blocks.push_back( 2 ); blocks.push_back( 1 );
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.clear();
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.push_back( 8 );
    problems.push_back( std::make_pair( 10, blocks ) );
    blocks.clear();
    blocks.push_back( 2 ); blocks.push_back( 3 );
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.push_back( 2 ); blocks.push_back( 3 );
    problems.push_back( std::make_pair( 15, blocks ) );

    nonoblock nn;
    nn.solve( problems );

    return 0;
}