Number reversal game: Difference between revisions

added Easylang
(→‎{{header|XPL0}}: added zkl)
(added Easylang)
 
(88 intermediate revisions by 40 users not shown)
Line 1:
{{task|Games}}
[[Category:Puzzles]]
 
;Task:
Given a jumbled list of the numbers   '''1'''   to   '''9'''   that are definitely   ''not''   in
ascending order.
 
Line 17 ⟶ 18:
 
 
;Related tasks:
;Cf.
*   [[Sorting algorithms/Pancake sort]]
*   [[wp:Pancake sorting|Pancake sorting]].
*   [[Topswops]]
<br><br>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">rawio: equ 6
org 100h
;;; Initialize RNG from keypresses
lxi d,keys
call puts
mvi b,4 ; 4*4 = 16 bytes
rndini: mvi c,4
lxi h,rnddat
rndin2: push b
push h
rndkey: call keyin ; Get key
ana a
jz rndkey
pop h
pop b
xra m ; XOR into random data
mov m,a
inx h
dcr c
jnz rndin2
dcr b
jnz rndini
lxi d,done
call puts
;;; Create and shuffle array of numbers
mvi a,'1' ; Start at 1
mvi b,9 ; 9 items
lxi h,list
mklst: mov m,a ; Store item
inr a ; Increment item
inx h ; Increment pointer
dcr b ; One fewer list
jnz mklst
mov m,b ; Zero-terminate the list
lxi d,list+8
shuf: call rande ; Shuffle the list. E = high, L = low
mov l,a
ldax d ; Load current number
mov b,m ; Load number to swap with
mov m,a ; Store first number
mov a,b ; Store second number
stax d
dcr e ; Move pointer back
jnz shuf ; Keep going until list is shuffled
lxi h,0 ; Keep score on stack
push h
;;; Game loop
game: lxi d,list ; Print current state
call puts
lxi d,list
ldax d
check: mov b,a ; Check if list is sorted (done)
inx d
ldax d
ana a ; Reached end of list?
jz win ; Then the list is in order
cmp b ; Larger than previous?
jnc check ; Then keep going
lxi d,prompt
call puts ; Ask for a number
call getnum
mov b,a ; B = high number
dcr b
mvi c,0 ; C = low number
mvi h,listhi
swap: mov l,c ; Load high number in D
mov d,m
mov l,b ; Load high number in E
mov e,m
mov m,d ; Store low number in high place
mov l,c
mov m,e ; Store high number in low place
dcr b ; Decrement high index
inr c ; Increment low index
mov a,c ; Low < high?
cmp b
jc swap ; Then keep swapping
lxi d,nl ; Print newline
call puts
pop h ; Increment score
inx h
push h
jmp game
win: lxi d,winmsg
call puts ; Print win message
lxi h,score
xthl ; Retrieve score and push score output buffer
lxi b,-10 ; Divisor
digit: lxi d,-1 ; Quotient
dgdiv: inx d ; Find digit
dad b
jc dgdiv
mvi a,'0'+10
add l ; Store digit
pop h ; Get pointer
dcx h ; Decrement pointer
mov m,a ; Write digit to memory
push h ; Store pointer
xchg ; Continue with quotient
mov a,h ; Done yet?
ora l
jnz digit ; If not keep going
pop d ; Retrieve pointer
;;; Print 0-terminated string
puts: ldax d ; Get character
ana a ; Is it zero?
rz ; Then stop
inx d ; Otherwise, increment buffer pointer
push d ; Save buffer pointer
mov e,a ; Print character
call io
pop d ; Restore buffer pointer
jmp puts ; Next character
;;; Read 1-9 key
gnerr: mvi e,7
call io
getnum: call keyin
ana a
jz getnum ; If no key, wait for one
cpi '1'
jc gnerr ; Not valid - beep and try again
cpi '9'+1
jnc gnerr
push psw ; Valid - echo
mov e,a
call io
pop psw
sui '0'
ret
keyin: mvi e,0FFh ; Read key
io: mvi c,rawio ; CP/M raw I/O call
jmp 5
;;; Random number up to E
rande: call rand
ani 15
cmp e
jnc rande
ret
;;; RNG
rand: push h! lxi h,rnddat! inr m! mov a,m! inx h! xra m! inx h! xra m
mov m,a! inx h! add m! mov m,a! rar! dcx h! xra m! dcx h! add m
mov m,a! pop h
ret
prompt: db 9,' - Reverse how many? ',0
keys: db 'Please press some keys to seed the RNG...',0
done: db 'done.'
nl: db 13,10,0
winmsg: db 13,10,'You win! Score = ',0
db '*****'
score: db 13,10,0
listhi: equ $/256+1
list: equ listhi*256
rnddat: equ list+16
</syntaxhighlight>
{{out}}
<pre>Please press some keys to seed the RNG...done.
295671438 - Reverse how many? 2
925671438 - Reverse how many? 9
834176529 - Reverse how many? 8
256714389 - Reverse how many? 4
765214389 - Reverse how many? 7
341256789 - Reverse how many? 2
431256789 - Reverse how many? 4
213456789 - Reverse how many? 2
123456789
You win! Score = 8</pre>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V data = Array(‘139275486’)
V trials = 0
 
L data != sorted(data)
trials++
V flip = Int(input(‘###2: LIST: '#.' Flip how many?: ’.format(trials, data.join(‘ ’))))
data.reverse_range(0 .< flip)
 
print("\nYou took #. attempts to put the digits in order!".format(trials))</syntaxhighlight>
 
{{out}}
<pre>
# 1: LIST: '1 3 9 2 7 5 4 8 6' Flip how many?: 9
# 2: LIST: '6 8 4 5 7 2 9 3 1' Flip how many?: 6
# 3: LIST: '2 7 5 4 8 6 9 3 1' Flip how many?: 8
# 4: LIST: '3 9 6 8 4 5 7 2 1' Flip how many?: 7
# 5: LIST: '7 5 4 8 6 9 3 2 1' Flip how many?: 3
# 6: LIST: '4 5 7 8 6 9 3 2 1' Flip how many?: 6
# 7: LIST: '9 6 8 7 5 4 3 2 1' Flip how many?: 2
# 8: LIST: '6 9 8 7 5 4 3 2 1' Flip how many?: 4
# 9: LIST: '7 8 9 6 5 4 3 2 1' Flip how many?: 3
#10: LIST: '9 8 7 6 5 4 3 2 1' Flip how many?: 9
 
You took 10 attempts to put the digits in order!
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
BYTE i,j,tmp
 
i=size-1
WHILE i>0
DO
j=Rand(i+1)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
 
BYTE FUNC IsSorted(BYTE ARRAY tab BYTE size)
BYTE i
 
FOR i=0 TO size-2
DO
IF tab(i)>tab(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
 
PROC Swap(BYTE ARRAY tab BYTE size,count)
BYTE i,j,tmp
 
i=0 j=count-1
WHILE i<j
DO
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==+1 j==-1
OD
RETURN
 
PROC Main()
DEFINE SIZE="9"
BYTE ARRAY a(SIZE)
BYTE i,j,n,tmp
BYTE LMARGIN=$52,oldLMARGIN
 
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
 
FOR i=0 TO SIZE-1
DO
a(i)=i+1
OD
KnuthShuffle(a,SIZE)
 
i=0
DO
PrintF("%B: ",i)
FOR j=0 TO SIZE-1
DO
PrintB(a(j))
OD
IF IsSorted(a,SIZE) THEN
EXIT
FI
PrintF(" How many to flip (2-%B)? ",SIZE)
n=InputB()
IF n>=2 AND n<=SIZE THEN
Swap(a,SIZE,n)
i==+1
FI
OD
 
PrintF("%E%EYou solved it in %B moves!",i)
 
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Number_reversal_game.png Screenshot from Atari 8-bit computer]
<pre>
0: 987152346 How many to flip (2-9)? 9
1: 643251789 How many to flip (2-9)? 6
2: 152346789 How many to flip (2-9)? 2
3: 512346789 How many to flip (2-9)? 5
4: 432156789 How many to flip (2-9)? 4
5: 123456789
 
You solved it in 5 moves!
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
Line 100 ⟶ 388:
Integer'Image(Count) & " tries.");
end NumberReverse;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
Using code from the [[Knuth shuffle#ALGOL 68|Knuth shuffle]] task.
<syntaxhighlight lang="algol68">
BEGIN # play the number reversal game #
 
CO begin code from the Knuth shuffle task CO
PROC between = (INT a, b)INT :
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
);
 
PROC knuth shuffle = (REF[]INT a)VOID:
(
FOR i FROM LWB a TO UPB a DO
INT j = between(LWB a, UPB a);
INT t = a[i];
a[i] := a[j];
a[j] := t
OD
);
CO end code from the Knuth shuffle task CO
 
[]INT ordered digits = ( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
[ 1 : 9 ]INT digits := ordered digits;
knuth shuffle( digits );
 
# ignore invalid data in stand in #
on value error( stand in, ( REF FILE f )BOOL: TRUE );
 
PROC print digits = VOID: # prints the digits #
BEGIN
print( ( "The digits are:" ) );
FOR i TO 9 DO print( ( whole( digits[ i ], -2 ) ) ) OD;
print( ( newline ) )
END # print digits # ;
 
OP = = ( []INT a, b )BOOL: # returns TRUE if a = b #
IF LWB a /= LWB b OR UPB a /= UPB b THEN
FALSE # a and b have different bounds #
ELSE
# a and b ave the same bounds #
BOOL same := TRUE;
FOR i FROM LWB a TO UPB a WHILE same DO same := a[ i ] = b[ i ] OD;
same
FI # = # ;
OP /= = ( []INT a, b )BOOL: NOT ( a = b ); # returns TRUE if a not = b #
 
INT count := 0;
 
print digits;
WHILE digits /= ordered digits DO
print( ( "How many digits to reverse (2-9)? " ) );
INT n := 0;
read( ( n, newline ) );
IF n >= 2 AND n <= 9 THEN
# reverse the n left-most digits #
count +:= 1;
INT r pos := n;
FOR pos TO n OVER 2 DO
INT t = digits[ r pos ];
digits[ r pos ] := digits[ pos ];
digits[ pos ] := t;
r pos -:= 1
OD;
print digits
FI
OD;
print( ( newline, "You ordered the digits in ", whole( count, 0 ), " moves", newline ) )
 
END
</syntaxhighlight>
{{out}}
<pre>
The digits are: 9 6 4 3 8 7 1 5 2
How many digits to reverse (2-9)? 4
The digits are: 3 4 6 9 8 7 1 5 2
How many digits to reverse (2-9)? 6
The digits are: 7 8 9 6 4 3 1 5 2
How many digits to reverse (2-9)? 3
The digits are: 9 8 7 6 4 3 1 5 2
How many digits to reverse (2-9)? 9
The digits are: 2 5 1 3 4 6 7 8 9
How many digits to reverse (2-9)? 2
The digits are: 5 2 1 3 4 6 7 8 9
How many digits to reverse (2-9)? 5
The digits are: 4 3 1 2 5 6 7 8 9
How many digits to reverse (2-9)? 4
The digits are: 2 1 3 4 5 6 7 8 9
How many digits to reverse (2-9)? 2
The digits are: 1 2 3 4 5 6 7 8 9
 
You ordered the digits in 8 moves
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">∇numrev;list;in;swaps
list←{9?9}⍣{⍺≢⍳9}⊢⍬
swaps←0
read:
swaps+←1
in←{⍞←⍵⋄(≢⍵)↓⍞}(⍕list),': swap how many? '
list←⌽@(⍳⍎in)⊢list
→(list≢⍳9)/read
⎕←(⍕list),': Congratulations!'
⎕←'Swaps:',swaps
∇</syntaxhighlight>
{{out}}
<pre>8 7 2 6 5 3 1 9 4: swap how many? 8
9 1 3 5 6 2 7 8 4: swap how many? 9
4 8 7 2 6 5 3 1 9: swap how many? 3
7 8 4 2 6 5 3 1 9: swap how many? 2
8 7 4 2 6 5 3 1 9: swap how many? 8
1 3 5 6 2 4 7 8 9: swap how many? 4
6 5 3 1 2 4 7 8 9: swap how many? 6
4 2 1 3 5 6 7 8 9: swap how many? 4
3 1 2 4 5 6 7 8 9: swap how many? 3
2 1 3 4 5 6 7 8 9: swap how many? 2
1 2 3 4 5 6 7 8 9: Congratulations!
Swaps: 10</pre>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoftbasic"> 100 LET M$ = CHR$ (13)
110 LET A$ = "123456789"
120 FOR S = 0 TO 1 STEP 0
130 LET N$ = A$
140 FOR I = 1 TO 9
150 LET R = INT ( RND (1) * 9 + 1)
160 GOSUB 500SWAP
170 NEXT I
180 LET S = N$ < > A$
190 NEXT S
200 FOR S = 1 TO 1E9
210 PRINT M$"HOW MANY DIGITS "N$M$" FROM THE LEFT ^^^^^^^^^"M$" TO REVERSE? "A$
230 INPUT "--------------> ";N%
300 FOR I = 1 TO INT (N% / 2)
310 LET R = N% - I + 1
320 GOSUB 500SWAP
330 NEXT I
340 IF N$ = A$ THEN PRINT M$"SCORE "S;: END
350 NEXT S
500 LET I$ = MID$ (N$,I,1)
510 LET N$ = MID$ (N$,1,I - 1) + MID$ (N$,R,1) + MID$ (N$,I + 1)
520 LET N$ = MID$ (N$,1,R - 1) + I$ + MID$ (N$,R + 1)
530 RETURN
</syntaxhighlight>
=={{header|Arturo}}==
 
{{trans|Ruby}}
 
<syntaxhighlight lang="rebol">arr: 1..9
 
while [arr = sort arr]->
arr: shuffle arr
 
score: 0
while [arr <> sort arr][
prints [arr "-- "]
digits: to :integer strip input "How many digits to reverse? "
arr: (reverse slice arr 0 digits-1) ++ slice arr digits (size arr)-1
score: score + 1
]
 
print ["Your score:" score]</syntaxhighlight>
 
{{out}}
 
<pre>[6 2 5 4 1 3 9 7 8] -- How many digits to reverse? 7
[9 3 1 4 5 2 6 7 8] -- How many digits to reverse? 9
[8 7 6 2 5 4 1 3 9] -- How many digits to reverse? 8
[3 1 4 5 2 6 7 8 9] -- How many digits to reverse? 4
[5 4 1 3 2 6 7 8 9] -- How many digits to reverse? 5
[2 3 1 4 5 6 7 8 9] -- How many digits to reverse? 2
[3 2 1 4 5 6 7 8 9] -- How many digits to reverse? 3
Your score: 7 </pre>
 
=={{header|Astro}}==
<syntaxhighlight lang="python">print '# Number reversal game'
 
var data, trials = list(1..9), 0
 
while data == sort data:
random.shuffle data
 
while data != sort data:
trials += 1
flip = int input '#${trials}: LIST: ${join data} Flip how many?: '
data[:flip] = reverse data[:flip]
 
print '\nYou took ${trials} attempts to put digits in order!'</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight Autohotkeylang="autohotkey">; Submitted by MasterFocus --- http://tiny.cc/iTunis
 
ScrambledList := CorrectList := "1 2 3 4 5 6 7 8 9" ; Declare two identical correct sequences
Line 136 ⟶ 615:
Out := A_LoopField Out
Return Out
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
print "\nWelcome to the number reversal game!\n"
 
Line 217 ⟶ 696:
}
 
END { print "\n\nBye!" }</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 224 ⟶ 703:
{{works with|FreeBASIC}}
 
<langsyntaxhighlight lang="qbasic">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."
Line 278 ⟶ 757:
LOOP
 
PRINT : PRINT "You took "; LTRIM$(RTRIM$(STR$(tries))); " tries to put the digits in order."</langsyntaxhighlight>
 
Sample output:
Line 294 ⟶ 773:
7 : 1 2 3 4 5 6 7 8 9
You took 7 tries to put the digits in order.
</pre>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
print "Dada una lista aleatoria de numeros del 1 al 9,"
print "indica cuantos digitos de la izquierda voltear."
print " El objetivo es obtener los digitos en orden "
print " con el 1 a la izquierda y el 9 a la derecha." + chr(10)
 
dim nums(10)
dim a(10)
intentos = 0: denuevo = true: colum = 6
 
#valores iniciales
for i = 1 to 9
nums[i] = i
next i
 
do #barajamos
for i = 9 to 2 step -1
n = int(rand * i) + 1
if n <> i then
a[i] = nums[i]
nums[i] = nums[n]
nums[n] = a[i]
end if
next i
for i = 1 to 8 #nos aseguramos que no estén en orden
if nums[i] > nums[i + 1] then exit do
next i
until false
 
do
if intentos < 10 then print " ";
print intentos; ": ";
for i = 1 to 9
print nums[i];" ";
next i
 
if not denuevo then exit do
 
input " -- Cuantos volteamos ", volteo
if volteo < 0 or volteo > 9 then volteo = 0
 
for i = 1 to (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
exit for
end if
next i
 
if volteo > 0 then intentos += 1
until false
print chr(10) + chr(10) + " Necesitaste "; intentos; " intentos."
end
</syntaxhighlight>
{{out}}
<pre>
Dada una lista aleatoria de numeros del 1 al 9,
indica cuantos digitos de la izquierda voltear.
El objetivo es obtener los digitos en orden
con el 1 a la izquierda y el 9 a la derecha.
 
0: 2 1 4 3 5 9 8 6 7 -- Cuantos volteamos 6
1: 9 5 3 4 1 2 8 6 7 -- Cuantos volteamos 9
2: 7 6 8 2 1 4 3 5 9 -- Cuantos volteamos 3
3: 8 6 7 2 1 4 3 5 9 -- Cuantos volteamos 8
4: 5 3 4 1 2 7 6 8 9 -- Cuantos volteamos 6
5: 7 2 1 4 3 5 6 8 9 -- Cuantos volteamos 7
6: 6 5 3 4 1 2 7 8 9 -- Cuantos volteamos 6
7: 2 1 4 3 5 6 7 8 9 -- Cuantos volteamos 3
8: 4 1 2 3 5 6 7 8 9 -- Cuantos volteamos 4
9: 3 2 1 4 5 6 7 8 9 -- Cuantos volteamos 3
10: 1 2 3 4 5 6 7 8 9
 
Necesitaste 10 intentos.
</pre>
 
=={{header|Batch File}}==
Note that I did not use the FOR command for looping. I used Batch File labels instead.
<langsyntaxhighlight lang="dos">
::
::Number Reversal Game Task from Rosetta Code Wiki
Line 369 ⟶ 932:
goto :loopgame
)
</syntaxhighlight>
</lang>
Sample Output:
<pre>
Line 410 ⟶ 973:
=={{header|BBC BASIC}}==
Note the use of the MOD(array()) function to test the equality of two arrays.
<langsyntaxhighlight lang="bbcbasic"> DIM list%(8), done%(8), test%(8)
list%() = 1, 2, 3, 4, 5, 6, 7, 8, 9
done%() = list%()
Line 441 ⟶ 1,004:
SWAP a%(i%), a%(n%-i%)
NEXT
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 457 ⟶ 1,020:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">sorted = 1.to 9
length = sorted.length
numbers = sorted.shuffle
Line 475 ⟶ 1,038:
 
p numbers
p "It took #{turns} turns to sort numbers."</langsyntaxhighlight>
 
=={{header|C}}==
An example of a number reversal game could be:
<langsyntaxhighlight lang="c">void number_reversal_game()
{
printf("Number Reversal Game. Type a number to flip the first n numbers.");
Line 510 ⟶ 1,073:
}
printf("Hurray! You solved it in %d moves!\n", tries);
}</langsyntaxhighlight>
 
Which uses the following helper functions:
<langsyntaxhighlight lang="c">void shuffle_list(int *list, int len)
{
//We'll just be swapping 100 times. Could be more/less. Doesn't matter much.
Line 556 ⟶ 1,119:
}
return 1;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
C# 3.0
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 590 ⟶ 1,153:
Console.ReadLine();
}
}</langsyntaxhighlight>
 
C# 1.0
<langsyntaxhighlight lang="csharp">class Program
{
static void Main(string[] args)
Line 678 ⟶ 1,241:
return retArray;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
===Version 1 (crude)===
The C code can be used with C++, although the following uses proper C++ iostreams:
<langsyntaxhighlight CPPlang="cpp">void number_reversal_game()
{
cout << "Number Reversal Game. Type a number to flip the first n numbers.";
Line 715 ⟶ 1,279:
}
cout << "Hurray! You solved it in %d moves!\n";
}</langsyntaxhighlight>
 
This uses the same helper functions as the C version.
 
===Version Alternate2 version using the(with C++ standard library )===
====Version 2.1====
This version uses the C++ standard library (note that none of the C helper functions are needed).
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 772 ⟶ 1,337:
return 0;
}
</syntaxhighlight>
</lang>
 
====Version 2.2====
<syntaxhighlight lang="cpp">
// Written by Katsumi -- twitter.com/realKatsumi_vn
// Compile with: g++ -std=c++20 -Wall -Wextra -pedantic NumberReversal.cpp -o NumberReversal
#include <iostream>
#include <algorithm>
#include <utility>
#include <functional>
#include <iterator>
#include <random>
#include <vector>
#include <string>
 
template <class T>
bool Sorted(std::vector<T> list) {
return std::adjacent_find(list.begin(), list.end(), std::greater<T>()) == list.end();
}
 
template <class T>
std::string VectorRepr(std::vector<T> list) {
auto Separate = [](std::string a, int b) {
return std::move(a) + ", " + std::to_string(b);
};
return std::accumulate(std::next(list.begin()), list.end(), std::to_string(list[0]), Separate);
}
 
int main() {
const std::string IntroText = "NUMBER REVERSAL GAME\n"
"based on a \"task\" on Rosetta Code -- rosettacode.org\n"
"by Katsumi -- twitter.com/realKatsumi.vn\n\n";
// Don't ever write this s**tty code...
// std::srand(std::time(0));
// Do this instead:
std::random_device Device;
std::mt19937_64 Generator(Device());
 
std::vector<int> List = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::shuffle(List.begin(), List.end(), Generator);
std::cout << IntroText;
int Moves, PlayerInput;
while (!Sorted(List)) {
std::cout << "Current list: [" << VectorRepr(List) << "]\n"
"Digits to reverse? (2-9) ";
while (true) {
std::cin >> PlayerInput;
if (PlayerInput < 2 || PlayerInput > 9)
std::cout << "Please enter a value between 2 and 9.\n"
"Digits to reverse? (2-9) ";
else
break;
}
std::reverse(List.begin(), List.begin()+PlayerInput);
++Moves;
}
std::cout << "Yay! You sorted the list! You've made " << Moves << " moves.\n";
return 0;
}
</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn flip-at [n coll]
(let [[x y] (split-at n coll)]
(concat (reverse x) y )))
Line 790 ⟶ 1,420:
(flush)
(let [flipcount (read)]
(recur (flip-at flipcount unsorted), (inc steps))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% 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</syntaxhighlight>
{{out}}
<pre>792184365: reverse how many? 2
972184365: reverse how many? 9
563481279: reverse how many? 5
843651279: reverse how many? 8
721563489: reverse how many? 7
436512789: reverse how many? 3
634512789: reverse how many? 6
215436789: reverse how many? 3
512436789: reverse how many? 5
342156789: reverse how many? 2
432156789: reverse how many? 4
123456789
Score = 11</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
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.
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun shuffle! (vector)
(loop for i from (1- (length vector)) downto 1
do (rotatef (aref vector i)
Line 825 ⟶ 1,646:
(replace slice (nreverse slice))))))
(format t "~A~%Congratulations, you did it in ~D reversals!~%" numbers score))))
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
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}"
</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.string, std.conv, std.algorithm,
std.range;
 
Line 842 ⟶ 1,688:
}
writefln("\nYou took %d attempts.", trial);
}</langsyntaxhighlight>
{{out}}
<pre>1: [7, 2, 1, 6, 3, 8, 9, 5, 4] How many numbers to flip? 7
Line 855 ⟶ 1,701:
 
You took 9 attempts.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This program simulates a console application in an event-drivern, GUI application. It does this by creating a special helper object that manages the TMemo control. The helper-object waits for keystrokes and returns when the user has pressed a key or the program aborts. Notice how the object is created and destroyed every time you wait for a key stroke. This a common practice in Delphi and it works because the creation of an object is a low overhead opeation. That allows you to eliminate global variables and isolate resources to specific parts of the program.
 
<syntaxhighlight lang="Delphi">
type TKeyWaiter = class(TObject)
private
FControl: TWinControl;
protected
procedure HandleKeyPress(Sender: TObject; var Key: Char);
public
KeyChar: Char;
ValidKey: boolean;
Abort: boolean;
constructor Create(Control: TWinControl);
function WaitForKey: char;
end;
 
{ TMemoWaiter }
 
type TControlHack = class(TWinControl) end;
 
constructor TKeyWaiter.Create(Control: TWinControl);
{Save the control we want to wait on}
begin
FControl:=Control;
end;
 
procedure TKeyWaiter.HandleKeyPress(Sender: TObject; var Key: Char);
{Handle captured key press}
begin
KeyChar:=Key;
ValidKey:=True;
end;
 
 
function TKeyWaiter.WaitForKey: char;
{Capture keypress event and wait for key press control}
{Spends most of its time sleep and aborts if the user}
{sets the abort flag or the program terminates}
begin
ValidKey:=False;
Abort:=False;
TControlHack(FControl).OnKeyPress:=HandleKeyPress;
repeat
begin
Application.ProcessMessages;
Sleep(100);
end
until ValidKey or Application.Terminated or Abort;
Result:=KeyChar;
end;
 
 
 
 
{===========================================================}
 
type TNumbers = array [0..8] of integer;
 
function WaitForKey(Memo: TMemo; Prompt: string): char;
{Wait for key stroke on TMemo component}
var KW: TKeyWaiter;
begin
{Use custom object to wait and capture key strokes}
KW:=TKeyWaiter.Create(Memo);
try
Memo.Lines.Add(Prompt);
Memo.SelStart:=Memo.SelStart-1;
Memo.SetFocus;
Result:=KW.WaitForKey;
finally KW.Free; end;
end;
 
 
procedure ScrambleNumbers(var Numbers: TNumbers);
{Scramble numbers into a random order}
var I,I1,I2,T: integer;
begin
for I:=0 to 8 do Numbers[I]:=I+1;
for I:=1 to 100 do
begin
I1:=Random(9);
I2:=Random(9);
T:=Numbers[I1];
Numbers[I1]:=Numbers[I2];
Numbers[I2]:=T;
end;
end;
 
function GetNumbersStr(Numbers: TNumbers): string;
{Return number order as a string}
var I: integer;
begin
Result:='';
for I:=0 to High(Numbers) do
begin
if I<>0 then Result:=Result+' ';
Result:=Result+IntToStr(Numbers[I]);
end;
end;
 
 
procedure ReverseNumbers(var Numbers: TNumbers; Count: integer);
{Reverse the specified count of numbers from the start}
var NT: TNumbers;
var I,I1: integer;
begin
NT:=Numbers;
for I:=0 to Count-1 do
begin
I1:=(Count-1) - I;
Numbers[I1]:=NT[I];
end;
end;
 
function IsWinner(Numbers: TNumbers): boolean;
{Check if is number is order 1..9}
var I: integer;
begin
Result:=False;
for I:=0 to High(Numbers) do
if Numbers[I]<>(I+1) then exit;
Result:=True;
end;
 
procedure ReverseGame(Memo: TMemo);
{Play the reverse game on specified memo}
var C: char;
var Numbers: TNumbers;
var S: string;
var R: integer;
begin
Randomize;
ScrambleNumbers(Numbers);
while true do
begin
S:=GetNumbersStr(Numbers);
C:=WaitForKey(Memo,S+' Number To Reverse: ');
if Application.Terminated then exit;
if C in ['x','X'] then break;
R:=byte(C) - $30;
ReverseNumbers(Numbers,R);
if IsWinner(Numbers) then
begin
S:=GetNumbersStr(Numbers);
Memo.Lines.Add(S+' - WINNER!!');
break;
end;
end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
8 5 2 9 7 4 6 3 1 Number To Reverse: 4
9 2 5 8 7 4 6 3 1 Number To Reverse: 9
1 3 6 4 7 8 5 2 9 Number To Reverse: 6
8 7 4 6 3 1 5 2 9 Number To Reverse: 8
2 5 1 3 6 4 7 8 9 Number To Reverse: 5
6 3 1 5 2 4 7 8 9 Number To Reverse: 6
4 2 5 1 3 6 7 8 9 Number To Reverse: 3
5 2 4 1 3 6 7 8 9 Number To Reverse: 5
3 1 4 2 5 6 7 8 9 Number To Reverse: 3
4 1 3 2 5 6 7 8 9 Number To Reverse: 4
2 3 1 4 5 6 7 8 9 Number To Reverse: 2
3 2 1 4 5 6 7 8 9 Number To Reverse: 3
1 2 3 4 5 6 7 8 9 - WINNER!!
 
</pre>
 
 
=={{header|EasyLang}}==
{{trans|Nim}}
<syntaxhighlight>
func sorted s[] .
for c in s[]
if c < last
return 0
.
last = c
.
return 1
.
func$ tostr s[] .
for s in s[]
res$ &= s & " "
.
return res$
.
proc shuffle . s[] .
for i = len s[] downto 2
swap s[i] s[randint i]
.
.
proc reverse n . s[] .
for i = 1 to n div 2
swap s[i] s[n - i + 1]
.
.
data[] = [ 1 2 3 4 5 6 7 8 9 ]
while sorted data[] = 1
shuffle data[]
.
while sorted data[] = 0
print tostr data[]
score += 1
nflip = number input
reverse nflip data[]
.
print "Score " & score
</syntaxhighlight>
 
=={{header|Egel}}==
<syntaxhighlight lang="egel">
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</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 962 ⟶ 2,064:
 
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 999 ⟶ 2,101:
 
=={{header|Elena}}==
ELENA 6.x:
<lang elena>#import system.
#<syntaxhighlight lang="elena">import system'routines.;
#import extensions.;
 
#symbolpublic program =()
{
[
#var sorted := Array new:.allocate(9 set &every).populate:: (&index:n) [=> n + 1 ]. );
#var values := sorted .clone ().randomize:(9.);
while (sorted.sequenceEqual(values))
#var tries := Integer new.
{
#loop (sorted sequenceEqual:values)!
values := sorted.randomize(9)
[
tries += 1.};
var tries := new Integer();
console writeLiteral:"# ":tries:" : LIST : ":values:" - Flip how many?".
until (sorted.sequenceEqual(values))
{
values reverse:(console readLine toInt) &at:0.
] tries.append(1);
console.print("# ",tries," : LIST : ",values," - Flip how many?");
console writeLine:"You took ":tries:" attempts to put the digits in order!" readChar.
].</lang>
values.sequenceReverse(0, console.readLine().toInt())
};
console.printLine("You took ",tries," attempts to put the digits in order!").readChar()
}</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Number_reversal_game do
def start( n ) when n > 1 do
IO.puts "Usage: #{usage(n)}"
Line 1,042 ⟶ 2,149:
end
 
Number_reversal_game.start( 9 )</langsyntaxhighlight>
 
{{out}}
Line 1,067 ⟶ 2,174:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( number_reversal_game ).
 
Line 1,091 ⟶ 2,198:
 
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] ).
</syntaxhighlight>
</lang>
{{out}}
Not being a very good player I show a test run with only 3 numbers.
Line 1,111 ⟶ 2,218:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
function accending(sequence s)
Line 1,165 ⟶ 2,272:
end while
 
printf(1,"\nYou took %d tries to put the digits in order.", tries)</langsyntaxhighlight>
 
Output:
Line 1,189 ⟶ 2,296:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let rand = System.Random()
 
while true do
Line 1,198 ⟶ 2,305:
let xs = randomNums()
 
let suffix = function | 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th"
while xs <> Array.sort xs do
 
printf "\n%A\n\nReverse how many digits?\n> " xs
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
printf "Well done!\n\n" </lang>
move (i+1)
else
printfn "\nYou took %i moves to put the digits in order!\n" i
 
move 1</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel math math.parser math.ranges
namespaces random sequences strings ;
IN: rosetta.number-reversal
Line 1,234 ⟶ 2,348:
: play ( -- )
0 trials set
make-jumbled-array game-loop ;</langsyntaxhighlight>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 D 3;S T=0
01.20 F X=1,9;T %1,D(X)
01.30 T !;A "HOW MANY",R
01.40 I (R-1)1.3;I (9-R)1.3
01.50 D 5;S T=T+1
01.60 D 4;I (A-9)1.2
01.70 D 1.2;T !"CORRECT! ATTEMPTS",%4,T,!
01.80 Q
 
02.10 S A=10*FRAN();S A=A-FITR(A)
 
03.10 F X=1,9;S D(X)=X
03.20 F X=1,8;D 2;S Y=X+FITR((10-X)*A);S A=D(X);S D(X)=D(Y);S D(Y)=A
03.30 D 4
03.40 I (8-A)3.1
 
04.10 S A=0
04.20 F X=1,9;D 4.4
04.30 R
04.40 I (D(X)-X)4.3,4.5,4.3
04.50 S A=A+1
 
05.10 F X=1,R/2;S A=D(X);S D(X)=D(R-X+1);S D(R-X+1)=A</syntaxhighlight>
{{out}}
<pre>= 1= 6= 4= 5= 8= 7= 9= 2= 3
HOW MANY:9
= 3= 2= 9= 7= 8= 5= 4= 6= 1
HOW MANY:2
= 2= 3= 9= 7= 8= 5= 4= 6= 1
HOW MANY:8
= 6= 4= 5= 8= 7= 9= 3= 2= 1
HOW MANY:3
= 5= 4= 6= 8= 7= 9= 3= 2= 1
HOW MANY:2
= 4= 5= 6= 8= 7= 9= 3= 2= 1
HOW MANY:3
= 6= 5= 4= 8= 7= 9= 3= 2= 1
HOW MANY:3
= 4= 5= 6= 8= 7= 9= 3= 2= 1
HOW MANY:6
= 9= 7= 8= 6= 5= 4= 3= 2= 1
HOW MANY:3
= 8= 7= 9= 6= 5= 4= 3= 2= 1
HOW MANY:2
= 7= 8= 9= 6= 5= 4= 3= 2= 1
HOW MANY:3
= 9= 8= 7= 6= 5= 4= 3= 2= 1
HOW MANY:9
= 1= 2= 3= 4= 5= 6= 7= 8= 9
CORRECT! ATTEMPTS= 12</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
variable flips
Line 1,286 ⟶ 2,452:
7 flip
9 6 7 5 8 2 1 4 3 ok
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Reversal_game
implicit none
Line 1,343 ⟶ 2,509:
end function
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
:''See [[#BASIC|BASIC]]''
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,388 ⟶ 2,557:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">sorted = [*(1..9)]
arr = sorted.clone()
 
Line 1,405 ⟶ 2,574:
steps += 1
}
println "Done! That took you ${steps} steps"</langsyntaxhighlight>
 
=={{header|Haskell}}==
Using Rosetta [[Knuth shuffle#Haskell|Knuth Shuffle]]
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Arrow
import Rosetta.Knuthshuffle
Line 1,443 ⟶ 2,612:
start <- shuffle goal
playNRG 1 start</langsyntaxhighlight>
Play:
<pre>*Main> numberRevGame
Line 1,458 ⟶ 2,627:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest"> WRITE(Messagebox) "You took ", Reversals(), " attempts"
 
FUNCTION Reversals()
Line 1,480 ⟶ 2,649:
IF( SUM(temp) == 8 ) RETURN
ENDDO
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(cq) # Number Reversal Game
local x,nums,R,flips
 
Line 1,551 ⟶ 2,720:
map(trim(read())) ? return tab(upto(' ')|0)
end
</syntaxhighlight>
</lang>
 
Sample output:<pre>Input a position. The list will be flipped left to right at that point.
Line 1,579 ⟶ 2,748:
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Number Reversal Game is a room.
 
The current list is a list of numbers that varies.
Line 1,618 ⟶ 2,787:
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.</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">withRange := method( a, z,
Range clone setRange(a,z)
)
Line 1,639 ⟶ 2,808:
steps = steps+1
)
writeln("Done! That took you ", steps, " steps")</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">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</syntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'misc' NB. for the verb prompt
INTRO=: noun define
Line 1,664 ⟶ 2,874:
end.
'You took ',(": score), ' attempts to put the numbers in order.'
)</langsyntaxhighlight>
'''Example Usage:'''
<langsyntaxhighlight lang="j"> reversegame''
Number Reversal Game
Sort the numbers in ascending order by repeatedly
Line 1,682 ⟶ 2,892:
10: 4 1 2 3 5 6 7 8 9 How many numbers to flip?: 4
11: 3 2 1 4 5 6 7 8 9 How many numbers to flip?: 3
You took 11 attempts to put the numbers in order.</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java5">import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
Line 1,757 ⟶ 2,967:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Use <code>knuth_shuffle()</code> function from [[Knuth shuffle#JavaScript|here]].
 
<langsyntaxhighlight lang="html4strict"><html>
<head>
<title>Number Reversal Game</title>
Line 1,771 ⟶ 2,981:
<div id="progress"></div>
<div id="score"></div>
<script type="text/javascript"></langsyntaxhighlight>
<langsyntaxhighlight lang="javascript">function endGame(progress) {
var scoreId = progress.scoreId,
result = 'You took ' + progress.count + ' attempts to put the digits in order!';
Line 1,839 ⟶ 3,049:
}
 
playGame('start', 'progress', 'score');</langsyntaxhighlight>
<langsyntaxhighlight lang="html4strict"></script>
</body>
</html></langsyntaxhighlight>
 
=={{header|Luajq}}==
<syntaxhighlight lang="jq"># Input: the initial array
def play:
def sorted: . == sort;
 
def reverse(n): (.[0:n] | reverse) + .[n:];
Made using member functions though not strictly OO - see http://www.lua.org/pil/16.html
<lang Lua>
def prompt: "List: \(.list)\nEnter a pivot number: ";
math.randomseed(os.time()) -- Random values are used by numList:build()
math.random()
 
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); </syntaxhighlight>
 
'''Example'''
<syntaxhighlight lang="jq">[1,2,3,9,8,7,6,5,4] | play</syntaxhighlight>
 
'''Transcript'''
<pre>$ jq -r -n -f play.jq
List: [1,2,3,9,8,7,6,5,4]
Enter a pivot number:
9
List: [4,5,6,7,8,9,3,2,1]
Enter a pivot number:
6
List: [9,8,7,6,5,4,3,2,1]
Enter a pivot number:
9
Great! Your score is 3</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># 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()</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// 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")
}</syntaxhighlight>
Sample game:
{{out}}
<pre>
Here's your first list : 4, 3, 2, 7, 1, 6, 5, 8, 9
How many numbers from the left are to be reversed : 4
Here's your list now : 7, 2, 3, 4, 1, 6, 5, 8, 9
How many numbers from the left are to be reversed : 7
Here's your list now : 5, 6, 1, 4, 3, 2, 7, 8, 9
How many numbers from the left are to be reversed : 2
Here's your list now : 6, 5, 1, 4, 3, 2, 7, 8, 9
How many numbers from the left are to be reversed : 6
Here's your list now : 2, 3, 4, 1, 5, 6, 7, 8, 9
How many numbers from the left are to be reversed : 3
Here's your list now : 4, 3, 2, 1, 5, 6, 7, 8, 9
How many numbers from the left are to be reversed : 4
Here's your final list : 1, 2, 3, 4, 5, 6, 7, 8, 9
So you've completed the game with a score of 6
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">-- Initialisation
math.randomseed(os.time())
numList = {values = {}}
 
function numList:contains (n) -- Check whether list contains n
function numList:contains (n)
for k, v in pairs(self.values) do
for k, v in pairs(self.values) do
if v == n then return true end
if v == n then return true end
end
end
return false
return false
end
 
function numList:inOrder () -- Check whether list is in order
function numList:inOrder ()
for k, v in pairs(self.values) do
for k, v in pairs(self.values) do
if k ~=v then return false end
if k ~=v then return false end
end
end
return true
return true
end
 
function numList:build () -- Create necessarily out-of-order list
function numList:build ()
local newNum
local newNum
repeat
repeat
for i = 1, 9 do
for i = 1, 9 do
repeat
repeat
newNum = math.random(1, 9)
newNum = math.random(1, 9)
until not numList:contains(newNum)
until not numList:contains(newNum)
table.insert(self.values, newNum)
table.insert(self.values, newNum)
end
end
until not numList:inOrder()
until not numList:inOrder()
end
 
function numList:show () -- Display list of numbers on one line
function numList:show ()
for k, v in pairs(self.values) do
for k, v in pairs(self.values) do
io.write(v .. " ")
io.write(v .. " ")
end
end
io.write(":\t")
io.write(":\t")
end
 
function numList:reverse (n) -- Reverse n values from left
function numList:reverse (n)
local swapList = {}
local swapList = {}
for k, v in pairs(self.values) do
for k, v in pairs(self.values) do
table.insert(swapList, v)
table.insert(swapList, v)
end
end
for i = 1, n do
for i = 1, n do
swapList[i] = self.values[n + 1 - i]
swapList[i] = self.values[n + 1 - i]
end
end
self.values = swapList
self.values = swapList
end
 
local score = 0 -- Start of mainMain 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)</syntaxhighlight>
 
</lang>
=={{header|M2000 Interpreter}}==
Using some ready made Print's from BASIC example
 
Using stack of values which we can move easy values. When we call subs and pass arguments that arguments as values stored to same stack, but because we pop them (read to variables) we leave stack with 9 values for the game.
 
To check if we have all values in order, we just check the difference of two items one after the other, if is one, and if not one then we leave checking returning false.
 
Sub CheckStack get a value by reference. Because stack of values always get values, a reference is a copy of a weak reference, so in CheckStack a new variable defined as local ok, and get the reference from weak reference in stack. When a sub exit any new,including local variables removed (deleted). Subs are always local to Module, and have same scope as module scope.
 
To display the values of stack we use Stack statement with no arguments.
<syntaxhighlight lang="m2000 interpreter">
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
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">Module[{array = Range@9, score = 0},
While[array == Range@9, array = RandomSample@Range@9];
While[array != Range@9,
Print@array; (array[[;; #]] = Reverse@array[[;; #]]) &@
Input["How many digits would you like to reverse?"]; score++];
Print@array; Print["Your score:", score]]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function NumberReversalGame
list = randperm(9);
while issorted(list)
Line 1,945 ⟶ 3,330:
fprintf('\nPlay again soon!\n')
end
end</langsyntaxhighlight>
{{out}}
<pre>Given a list of numbers, try to put them into ascending order
Line 1,965 ⟶ 3,350:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import mathrandom, rdstdin, strutils, algorithm
randomize()
 
proc shuffle[T](x: var seq[T]) =
for i in countdown(x.high, 0):
let j = random(i + 1)
swap(x[i], x[j])
 
proc isSorted[T](s: openarray[T]): bool =
Line 2,005 ⟶ 3,385:
reverse(data, 0, flip - 1)
 
echo "You took ", trials, " attempts to put the digits in order!"</langsyntaxhighlight>
Example:
<pre>#1: List: '6 5 8 7 2 1 9 3 4' Flip how many?: 5
Line 2,024 ⟶ 3,404:
=== Imperative ===
 
<langsyntaxhighlight lang="ocaml">let swap ar i j =
let tmp = ar.(i) in
ar.(i) <- ar.(j);
Line 2,071 ⟶ 3,451:
print_endline "Congratulations!";
Printf.printf "You took %d attempts to put the digits in order.\n" !n;
;;</langsyntaxhighlight>
 
=== Functional ===
 
<langsyntaxhighlight lang="ocaml">let revert li n =
let rec aux acc i = function
| [] -> acc
Line 2,123 ⟶ 3,503:
in
loop 1 li
;;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: reversalGame
Line 2,142 ⟶ 3,522:
1+ l left(n) reverse l right(l size n -) + ->l
]
"You won ! Your score is :" . println ;</langsyntaxhighlight>
 
{{out}}
Line 2,161 ⟶ 3,541:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {Main}
proc {Loop N Xs}
Line 2,219 ⟶ 3,599:
end
in
{Main}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">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),
Line 2,235 ⟶ 3,615:
);
score
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
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.
</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">use List::Util qw(shuffle);
 
my $turn = 0;
Line 2,257 ⟶ 3,743:
 
print " @jumble\n";
print "You won in $turn turns.\n";</langsyntaxhighlight>
 
Output:
Line 2,270 ⟶ 3,756:
1 2 3 4 5 6 7 8 9
You won in 8 turns.</pre>
 
=={{header|Perl 6}}==
 
Do-at-least-once loops are fairly rare, but this program wants to have two of them. We use the built-in <tt>.pick(*)</tt> method to shuffle the numbers. We use <tt>.=</tt> to dispatch a mutating method in two spots; the first is just a different way to write <tt>++</tt>, while the second of these reverses an array slice in place. The <tt>[<]</tt> is a reduction operator on less than, so it returns true if the elements of the list are strictly ordered. We also see in the first repeat loop that, although the while condition is not tested till after the loop, the while condition can in fact declare the variable that will be initialized the first time through the loop, which is a neat trick, and not half unreadable once you get used to it.
 
<lang Perl6>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.";</lang>
 
Output:
<pre> 1: 3 5 8 2 7 9 6 1 4 - Flip how many digits ? 6
2: 9 7 2 8 5 3 6 1 4 - Flip how many digits ? 9
3: 4 1 6 3 5 8 2 7 9 - Flip how many digits ? 6
4: 8 5 3 6 1 4 2 7 9 - Flip how many digits ? 8
5: 7 2 4 1 6 3 5 8 9 - Flip how many digits ? 7
6: 5 3 6 1 4 2 7 8 9 - Flip how many digits ? 3
7: 6 3 5 1 4 2 7 8 9 - Flip how many digits ? 6
8: 2 4 1 5 3 6 7 8 9 - Flip how many digits ? 4
9: 5 1 4 2 3 6 7 8 9 - Flip how many digits ? 5
10: 3 2 4 1 5 6 7 8 9 - Flip how many digits ? 3
11: 4 2 3 1 5 6 7 8 9 - Flip how many digits ? 4
12: 1 3 2 4 5 6 7 8 9 - Flip how many digits ? 2
13: 3 1 2 4 5 6 7 8 9 - Flip how many digits ? 3
14: 2 1 3 4 5 6 7 8 9 - Flip how many digits ? 2
1 2 3 4 5 6 7 8 9
You won in 14 turns.</pre>
 
=={{header|Phix}}==
Simplified copy of [[Number_reversal_game#Euphoria|Euphoria]]
<langsyntaxhighlight Phixlang="phix">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")
Line 2,332 ⟶ 3,780:
end while
printf(1,"\nYou took %d turns to put the digits in order.", turns)</langsyntaxhighlight>
{{out}}
<pre style="font-size: 8px">
Line 2,352 ⟶ 3,800:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php">class ReversalGame {
private $numbers;
Line 2,407 ⟶ 3,855:
$game = new ReversalGame();
$game->play();
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de reversalGame ()
Line 2,421 ⟶ 3,869:
(NIL (num? (read)))
(setq Lst (flip Lst @))
(inc 'Cnt) ) ) )</langsyntaxhighlight>
Output:
<pre>: (reversalGame)
Line 2,435 ⟶ 3,883:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
digits: procedure options (main); /* 23 April 2010 */
declare s character (9) varying;
Line 2,469 ⟶ 3,917:
go to restart;
end digits;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
{{incomplete|Powershell|Task asks that "the numbers 1 to 9 that are definitely not in ascending order".}}
#adding the below function to the previous users submission to prevent the small
<lang PowerShell>
#chance of getting an array that is in ascending order.
$Array = 1..9 | Get-Random -Count 9
 
#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)){
Line 2,483 ⟶ 3,945:
"$Array"
"Your score: $nTries"
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">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).</syntaxhighlight>
{{out}}
<pre>
?- play.
(5 1 8 4 3 6 7 9 2) 8
(9 7 6 3 4 8 1 5 2) 5
(4 3 6 7 9 8 1 5 2) 6
(8 9 7 6 3 4 1 5 2) 2
(9 8 7 6 3 4 1 5 2) 9
(2 5 1 4 3 6 7 8 9) 2
(5 2 1 4 3 6 7 8 9) 3
(1 2 5 4 3 6 7 8 9) 5
(3 4 5 2 1 6 7 8 9) 2
(4 3 5 2 1 6 7 8 9) 3
(5 3 4 2 1 6 7 8 9) 2
(3 5 4 2 1 6 7 8 9) 3
(4 5 3 2 1 6 7 8 9) 2
(5 4 3 2 1 6 7 8 9) 5
(1 2 3 4 5 6 7 8 9) -> 14
true.
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim MyList(9)
 
Declare is_list_sorted()
Line 2,532 ⟶ 4,043:
Next
ProcedureReturn #True
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">'''
number reversal game
Given a jumbled list of the numbers 1 to 9
Line 2,556 ⟶ 4,067:
data[:flip] = reversed(data[:flip])
 
print('\nYou took %2i attempts to put the digits in order!' % trials)</langsyntaxhighlight>
 
'''Sample output:'''
Line 2,580 ⟶ 4,091:
 
You took 10 attempts to put the digits in order!</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 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 ( --> )</syntaxhighlight>
 
{{out}}
Playing in the Quackery shell.
<pre>/O> play
...
[ 8 6 5 9 4 1 7 2 3 ]
Reverse how many? 3
[ 5 6 8 9 4 1 7 2 3 ]
Reverse how many? 4
[ 9 8 6 5 4 1 7 2 3 ]
Reverse how many? 9
[ 3 2 7 1 4 5 6 8 9 ]
Reverse how many? 3
[ 7 2 3 1 4 5 6 8 9 ]
Reverse how many? 7
[ 6 5 4 1 3 2 7 8 9 ]
Reverse how many? 6
[ 2 3 1 4 5 6 7 8 9 ]
Reverse how many? 2
[ 3 2 1 4 5 6 7 8 9 ]
Reverse how many? 3
[ 1 2 3 4 5 6 7 8 9 ]
 
That took 8 reversals.</pre>
 
=={{header|R}}==
<syntaxhighlight lang="text">reversalGame <- function(){
cat("Welcome to the Number Reversal Game! \n")
cat("Sort the numbers into ascending order by repeatedly \n",
Line 2,605 ⟶ 4,161:
# Victory!
cat("Well done. You needed", trials, "flips. \n")
}</langsyntaxhighlight>
 
Sample output:
<syntaxhighlight lang="text">>reversalGame()
Welcome to the Number Reversal Game!
Sort the numbers into ascending order by repeatedly
Line 2,617 ⟶ 4,173:
Trial 03 # 9 8 7 1 2 3 4 5 6 # Flip how many? 9
Trial 04 # 6 5 4 3 2 1 7 8 9 # Flip how many? 6
Well done. You needed 4 flips.</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(let loop ([nums (range 1 10)] [n 0])
(cond [(apply < nums) (if (zero? n)
Line 2,627 ⟶ 4,183:
[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))]))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Do-at-least-once loops are fairly rare, but this program wants to have two of them. We use the built-in <tt>.pick(*)</tt> method to shuffle the numbers. We use <tt>.=</tt> to dispatch a mutating method in two spots; the first is just a different way to write <tt>++</tt>, while the second of these reverses an array slice in place. The <tt>[<]</tt> is a reduction operator on less than, so it returns true if the elements of the list are strictly ordered. We also see in the first repeat loop that, although the while condition is not tested till after the loop, the while condition can in fact declare the variable that will be initialized the first time through the loop, which is a neat trick, and not half unreadable once you get used to it.
 
<syntaxhighlight lang="raku" line>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.";</syntaxhighlight>
 
Output:
<pre> 1: 3 5 8 2 7 9 6 1 4 - Flip how many digits ? 6
2: 9 7 2 8 5 3 6 1 4 - Flip how many digits ? 9
3: 4 1 6 3 5 8 2 7 9 - Flip how many digits ? 6
4: 8 5 3 6 1 4 2 7 9 - Flip how many digits ? 8
5: 7 2 4 1 6 3 5 8 9 - Flip how many digits ? 7
6: 5 3 6 1 4 2 7 8 9 - Flip how many digits ? 3
7: 6 3 5 1 4 2 7 8 9 - Flip how many digits ? 6
8: 2 4 1 5 3 6 7 8 9 - Flip how many digits ? 4
9: 5 1 4 2 3 6 7 8 9 - Flip how many digits ? 5
10: 3 2 4 1 5 6 7 8 9 - Flip how many digits ? 3
11: 4 2 3 1 5 6 7 8 9 - Flip how many digits ? 4
12: 1 3 2 4 5 6 7 8 9 - Flip how many digits ? 2
13: 3 1 2 4 5 6 7 8 9 - Flip how many digits ? 3
14: 2 1 3 4 5 6 7 8 9 - Flip how many digits ? 2
1 2 3 4 5 6 7 8 9
You won in 14 turns.</pre>
 
=={{header|Rascal}}==
<langsyntaxhighlight Rascallang="rascal">import Prelude;
import vis::Figure;
import vis::Render;
Line 2,666 ⟶ 4,261:
render(figure);
}</langsyntaxhighlight>
 
Output:
Line 2,674 ⟶ 4,269:
=={{header|REBOL}}==
 
<langsyntaxhighlight REBOLlang="rebol">REBOL []
 
print "NUMBER REVERSAL GAME"
Line 2,695 ⟶ 4,290:
]
 
print rejoin ["You took " tries " attempts."]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,703 ⟶ 4,298:
:::* &nbsp; allows the user to enter &nbsp; '''quit'''
:::* &nbsp; allows the user to halt the game via &nbsp; '''Cntl-Break''' &nbsp; (or equivalent)
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram (a game): reverse a jumbled set of numeralsdecimal digits until'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 ___ "enter "one of those digits which will reverse all the digits upfrom tothe left-most (anddigit"
say ___ "up to (and including) that decimal digit. The game's objective is to get all the"
say ___ "of the digits in ascending order with the fewest tries. Here are'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.*/
_=random(1,9); if pos(_, $) \== 0 then iterate /*only¬ 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 digsdigits and& the prompt*/
say; say ___ $ right('please enter a digit (or Quit):', 50)
parse pull xox .; ?=left(x,1) ux . 1 x .; upper ux /*get a decimal digit (maybe) from CBLF*/
if abbrev('QUIT',x ux, 1) then signal halt /*does the CBLF want to quit this game?*/
if length(x)>1 then do; say ___ pad 'oops,***error*** invalid input!: ' xox; 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 'oops,***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 /* " " " " " " " " */</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; from playing one game of the &nbsp; ''number reversal game'':
<pre>
───────── This game will show you nine random unique digits (1 ──► 9), and you'll enter
───────── enter one of those digits which will reverse all the digits upfrom tothe left-most (anddigit
───────── up to (and including) that decimal digit. The game's objective is to get all the
───────── of the digits in ascending order with the fewest tries. Here are're your digits:
 
───────── 613279548 please enter a digit (or Quit):
5 ◄■■■■■■■■■ user input
5
 
───────── 597231648 please enter a digit (or Quit):
9 ◄■■■■■■■■■ user input
9
 
───────── 957231648 please enter a digit (or Quit):
8 ◄■■■■■■■■■ user input
8
 
───────── 846132759 please enter a digit (or Quit):
5 ◄■■■■■■■■■ user input
5
 
───────── 572316489 please enter a digit (or Quit):
7 ◄■■■■■■■■■ user input
7
 
───────── 752316489 please enter a digit (or Quit):
4 ◄■■■■■■■■■ user input
4
 
───────── 461325789 please enter a digit (or Quit):
6 ◄■■■■■■■■■ user input
6
 
───────── 641325789 please enter a digit (or Quit):
5 ◄■■■■■■■■■ user input
5
 
───────── 523146789 please enter a digit (or Quit):
4 ◄■■■■■■■■■ user input
4
 
───────── 413256789 please enter a digit (or Quit):
2 ◄■■■■■■■■■ user input
2
 
───────── 231456789 please enter a digit (or Quit):
3 ◄■■■■■■■■■ user input
3
 
───────── 321456789 please enter a digit (or Quit):
1 ◄■■■■■■■■■ user input
1
 
───────── 123456789
Line 2,779 ⟶ 4,374:
══════════════════════════ Congratulations! ══════════════════════════
 
───────── Your score was 12
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# 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
</syntaxhighlight>
Output:
<pre>
7 2 3 1 5 8 6 4 9 : Reverse how many? 6
8 5 1 3 2 7 6 4 9 : Reverse how many? 8
4 6 7 2 3 1 5 8 9 : Reverse how many? 3
7 6 4 2 3 1 5 8 9 : Reverse how many? 7
5 1 3 2 4 6 7 8 9 : Reverse how many? 5
4 2 3 1 5 6 7 8 9 : Reverse how many? 4
1 3 2 4 5 6 7 8 9 : Reverse how many? 3
2 3 1 4 5 6 7 8 9 : Reverse how many? 2
3 2 1 4 5 6 7 8 9 : Reverse how many? 3
You took 9 attempts.
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">ary = (1..9).to_a
ary.shuffle! while ary == ary.sort
score = 0
Line 2,793 ⟶ 4,455:
end
p ary
puts "Your score: #{score}"</langsyntaxhighlight>
 
sample output:
Line 2,809 ⟶ 4,471:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 9 ' get numbers 1 to 9
n(i) = i
next i
Line 2,848 ⟶ 4,510:
a$ = b$ + mid$(a$,i + 2)
goto [loop]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand 0.7.3}}
<syntaxhighlight lang="rust">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
);
}</syntaxhighlight>
{{out}}
<pre>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.
Attempt 1: [7, 1, 6, 2, 3, 4, 5, 8, 9] - How many numbers do you want to flip?
7
Attempt 2: [5, 4, 3, 2, 6, 1, 7, 8, 9] - How many numbers do you want to flip?
5
Attempt 3: [6, 2, 3, 4, 5, 1, 7, 8, 9] - How many numbers do you want to flip?
6
Attempt 4: [1, 5, 4, 3, 2, 6, 7, 8, 9] - How many numbers do you want to flip?
2
Attempt 5: [5, 1, 4, 3, 2, 6, 7, 8, 9] - How many numbers do you want to flip?
5
Attempt 6: [2, 3, 4, 1, 5, 6, 7, 8, 9] - How many numbers do you want to flip?
3
Attempt 7: [4, 3, 2, 1, 5, 6, 7, 8, 9] - How many numbers do you want to flip?
4
Congrats! It took you 7 attempts to sort the sequence.</pre>
 
 
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object NumberReversalGame extends App {
def play(n: Int, cur: List[Int], goal: List[Int]) {
readLine(s"""$n. ${cur mkString " "} How many to flip? """) match {
Line 2,879 ⟶ 4,612:
 
play(9)
}</langsyntaxhighlight>
{{out}}
<pre>1. 8 4 2 9 6 3 7 5 1 How many to flip? 3
Line 2,894 ⟶ 4,627:
Congratulations! You solved 1 2 3 4 5 6 7 8 9
Your score is 11 (lower is better)</pre>
 
=={{header|Scheme}}==
 
{{libheader|Scheme/SRFIs}}
 
<syntaxhighlight lang="scheme">
(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)
</syntaxhighlight>
 
{{out}}
<pre>
List: (1 8 3 4 9 2 7 5 6)
How many numbers should be flipped? 5
List: (9 4 3 8 1 2 7 5 6)
How many numbers should be flipped? 9
List: (6 5 7 2 1 8 3 4 9)
How many numbers should be flipped? 6
List: (8 1 2 7 5 6 3 4 9)
How many numbers should be flipped? 8
List: (4 3 6 5 7 2 1 8 9)
How many numbers should be flipped? 5
List: (7 5 6 3 4 2 1 8 9)
How many numbers should be flipped? 7
List: (1 2 4 3 6 5 7 8 9)
How many numbers should be flipped? 5
List: (6 3 4 2 1 5 7 8 9)
How many numbers should be flipped? 6
List: (5 1 2 4 3 6 7 8 9)
How many numbers should be flipped? 5
List: (3 4 2 1 5 6 7 8 9)
How many numbers should be flipped? 2
List: (4 3 2 1 5 6 7 8 9)
How many numbers should be flipped? 4
Finished in 11 attempts
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,932 ⟶ 4,735:
until list = sortedList;
writeln("Congratulations, you sorted the list in " <& score <& " reversals.");
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,945 ⟶ 4,748:
Congratulations, you sorted the list in 7 reversals.
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">
// 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!"
</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program number_reversal_game;
setrandom(0);
tries := 0;
state := shuffled_numbers();
 
loop until state = "123456789" do
tries +:= 1;
swapat := read_step(tries, state);
state := reverse state(..swapat) + state(swapat+1..);
end loop;
print(state + " - You win in " + str tries + " tries.");
 
proc read_step(tries, state);
loop until r in [str d : d in [1..9]] do
putchar(state + " - Reverse how many? ");
flush(stdout);
r := getline(stdin);
end loop;
return val r;
end proc;
 
proc shuffled_numbers();
digits := "123456789";
loop until out /= digits do
dset := {d : d in digits};
out := +/[[d := random dset, dset less:= d](1) : until dset = {}];
end loop;
return out;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>681934725 - Reverse how many? 4
918634725 - Reverse how many? 9
527436819 - Reverse how many? 7
863472519 - Reverse how many? 8
152743689 - Reverse how many? 4
725143689 - Reverse how many? 7
634152789 - Reverse how many? 6
251436789 - Reverse how many? 2
521436789 - Reverse how many? 5
341256789 - Reverse how many? 2
431256789 - Reverse how many? 4
213456789 - Reverse how many? 2
123456789 - You win in 12 tries.</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var turn = 0;
var jumble = @(1..9 -> bshuffle).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";</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
# Simple shuffler, not very efficient but good enough for here
proc shuffle list {
Line 3,003 ⟶ 4,876:
if {$outcome ne "quit"} {
puts "\nYou took $outcome attempts to put the digits in order."
}</langsyntaxhighlight>
Sample output:
<pre>
Line 3,026 ⟶ 4,899:
You took 11 attempts to put the digits in order.
</pre>
 
 
=={{header|True BASIC}}==
<syntaxhighlight lang="basic">
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
</syntaxhighlight>
 
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
numbers=RANDOM_NUMBERS (1,9,9),nr=0
Line 3,066 ⟶ 5,011:
ENDIF
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 3,094 ⟶ 5,039:
{{trans|AWK}}
{{works with|pdksh|5.2.14}}
<langsyntaxhighlight lang="bash">print "\nWelcome to the number reversal game!\n"
 
print "You must put the numbers in order from 1 to 9."
Line 3,193 ⟶ 5,138:
fi
fi
done</langsyntaxhighlight>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">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</syntaxhighlight>{{out}}
<pre>Given a jumbled list of the numbers 1 to 9
you must select how many digits from the left to reverse.
Your goal is to get the digits in order with 1 on the left and 9 on the right.
0 : 1 4 3 9 8 7 6 2 5
1 : 9 3 4 1 8 7 6 2 5
2 : 5 2 6 7 8 1 4 3 9
3 : 8 7 6 2 5 1 4 3 9
4 : 3 4 1 5 2 6 7 8 9
5 : 5 1 4 3 2 6 7 8 9
6 : 2 3 4 1 5 6 7 8 9
7 : 4 3 2 1 5 6 7 8 9
8 : 1 2 3 4 5 6 7 8 9
You took 8 turns to put the digits in order.</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import rand
import os
 
fn main() {
mut score, mut rnum := 0, 0
mut mix, mut unmix := []int{}, []int{}
for mix.len < 9 {
rnum = rand.int_in_range(1, 10) or {println('Error: invalid number') exit(1)}
if mix.contains(rnum) == false {
mix << rnum
}
}
unmix = mix.clone()
unmix.sort()
println("Select how many digits from the left to reverse.")
for {
print("The list is: ${mix} ==> How many digits to reverse? ")
input := os.input('').str().trim_space().int()
score++
if input == 0 || input < 2 || input > 9 {
println("\n(Enter a number from 2 to 9)")
continue
}
for idx, rdx := 0, input - 1; idx < rdx; idx, rdx = idx + 1, rdx - 1 {
mix[idx], mix[rdx] = mix[rdx], mix[idx]
}
if mix == unmix {
println("The list is: ${mix}.")
println("Your score: ${score}. Good job.")
break
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Select how many digits from the left to reverse.
The list is: [3, 4, 9, 7, 6, 1, 5, 8, 2] ==> How many digits to reverse? 8
The list is: [8, 5, 1, 6, 7, 9, 4, 3, 2] ==> How many digits to reverse? 5
The list is: [7, 6, 1, 5, 8, 9, 4, 3, 2] ==> How many digits to reverse? 4
The list is: [5, 1, 6, 7, 8, 9, 4, 3, 2] ==> How many digits to reverse? 2
The list is: [1, 5, 6, 7, 8, 9, 4, 3, 2] ==> How many digits to reverse? 9
The list is: [2, 3, 4, 9, 8, 7, 6, 5, 1] ==> How many digits to reverse? 8
The list is: [5, 6, 7, 8, 9, 4, 3, 2, 1] ==> How many digits to reverse? 5
The list is: [9, 8, 7, 6, 5, 4, 3, 2, 1] ==> How many digits to reverse? 9
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9].
Your score: 8. Good job.
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-sort}}<syntaxhighlight lang="wren">
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)")</syntaxhighlight>
 
{{out}}
Sample game:
<pre>
Here's your first list : [7, 5, 8, 3, 4, 6, 9, 2, 1]
How many numbers from the left are to be reversed : 7
Here's your list now : [9, 6, 4, 3, 8, 5, 7, 2, 1]
How many numbers from the left are to be reversed : 9
Here's your list now : [1, 2, 7, 5, 8, 3, 4, 6, 9]
How many numbers from the left are to be reversed : 5
Here's your list now : [8, 5, 7, 2, 1, 3, 4, 6, 9]
How many numbers from the left are to be reversed : 8
Here's your list now : [6, 4, 3, 1, 2, 7, 5, 8, 9]
How many numbers from the left are to be reversed : 6
Here's your list now : [7, 2, 1, 3, 4, 6, 5, 8, 9]
How many numbers from the left are to be reversed : 7
Here's your list now : [5, 6, 4, 3, 1, 2, 7, 8, 9]
How many numbers from the left are to be reversed : 2
Here's your list now : [6, 5, 4, 3, 1, 2, 7, 8, 9]
How many numbers from the left are to be reversed : 6
Here's your list now : [2, 1, 3, 4, 5, 6, 7, 8, 9]
How many numbers from the left are to be reversed : 2
Here's your final list : [1, 2, 3, 4, 5, 6, 7, 8, 9]
So you've completed the game with a score of 9
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int Taken, I, Digit, Num, Score, Rev, Temp;
char List(9);
include c:\cxpl\codes;
Line 3,219 ⟶ 5,362:
Text(0, "^M^JCongrats! You did it in "); IntOut(0, Score);
Text(0, " moves!!^M^J");
]</langsyntaxhighlight>
 
Example output:
Line 3,233 ⟶ 5,376:
5 8 3 1 4 9 7 2 6
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// 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</syntaxhighlight>
 
 
=={{header|zkl}}==
{{trans|AutoHotkey}}
<langsyntaxhighlight lang="zkl">correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len();
correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string
attempts:=0;
Line 3,248 ⟶ 5,451:
scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts));</langsyntaxhighlight>
{{out}}
<pre>
2,076

edits