Number reversal game: Difference between revisions

m
(Number reversal game in Yabasic)
imported>Arakov
(10 intermediate revisions by 9 users not shown)
Line 25:
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang="8080asm">rawio: equ 6
org 100h
;;; Initialize RNG from keypresses
Line 178:
list: equ listhi*256
rnddat: equ list+16
</syntaxhighlight>
</lang>
{{out}}
<pre>Please press some keys to seed the RNG...done.
Line 195:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V data = Array(‘139275486’)
V trials = 0
 
Line 203:
data.reverse_range(0 .< flip)
 
print("\nYou took #. attempts to put the digits in order!".format(trials))</langsyntaxhighlight>
 
{{out}}
Line 222:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
BYTE i,j,tmp
 
Line 297:
 
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Number_reversal_game.png Screenshot from Atari 8-bit computer]
Line 312:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
Line 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}}
<langsyntaxhighlight APLlang="apl">∇numrev;list;in;swaps
list←{9?9}⍣{⍺≢⍳9}⊢⍬
swaps←0
Line 402 ⟶ 496:
⎕←(⍕list),': Congratulations!'
⎕←'Swaps:',swaps
∇</langsyntaxhighlight>
{{out}}
<pre>8 7 2 6 5 3 1 9 4: swap how many? 8
Line 416 ⟶ 510:
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}}
 
<langsyntaxhighlight lang="rebol">arr: 1..9
 
while [arr = sort arr]->
Line 433 ⟶ 553:
]
 
print ["Your score:" score]</langsyntaxhighlight>
 
{{out}}
Line 447 ⟶ 567:
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">print '# Number reversal game'
 
var data, trials = list(1..9), 0
Line 459 ⟶ 579:
data[:flip] = reverse data[:flip]
 
print '\nYou took ${trials} attempts to put digits in order!'</langsyntaxhighlight>
 
=={{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 495 ⟶ 615:
Out := A_LoopField Out
Return Out
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
print "\nWelcome to the number reversal game!\n"
 
Line 576 ⟶ 696:
}
 
END { print "\n\nBye!" }</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 583 ⟶ 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 637 ⟶ 757:
LOOP
 
PRINT : PRINT "You took "; LTRIM$(RTRIM$(STR$(tries))); " tries to put the digits in order."</langsyntaxhighlight>
 
Sample output:
Line 656 ⟶ 776:
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
print "Dada una lista aleatoria de numeros del 1 al 9,"
print "indica cuantos digitos de la izquierda voltear."
Line 716 ⟶ 836:
print chr(10) + chr(10) + " Necesitaste "; intentos; " intentos."
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 741 ⟶ 861:
=={{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 812 ⟶ 932:
goto :loopgame
)
</syntaxhighlight>
</lang>
Sample Output:
<pre>
Line 853 ⟶ 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 884 ⟶ 1,004:
SWAP a%(i%), a%(n%-i%)
NEXT
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 900 ⟶ 1,020:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">sorted = 1.to 9
length = sorted.length
numbers = sorted.shuffle
Line 918 ⟶ 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 953 ⟶ 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 999 ⟶ 1,119:
}
return 1;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
C# 3.0
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,033 ⟶ 1,153:
Console.ReadLine();
}
}</langsyntaxhighlight>
 
C# 1.0
<langsyntaxhighlight lang="csharp">class Program
{
static void Main(string[] args)
Line 1,121 ⟶ 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 1,158 ⟶ 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 1,215 ⟶ 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 1,233 ⟶ 1,420:
(flush)
(let [flipcount (read)]
(recur (flip-at flipcount unsorted), (inc steps))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% This program uses the random number generator from PCLU's
% 'misc.lib'
 
Line 1,291 ⟶ 1,478:
end
stream$putl(po, "\nScore = " || int$unparse(score))
end start_up</langsyntaxhighlight>
{{out}}
<pre>792184365: reverse how many? 2
Line 1,308 ⟶ 1,495:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. REVERSAL.
Line 1,424 ⟶ 1,611:
GOBACK.
END PROGRAM REVERSE.
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun shuffle! (vector)
(loop for i from (1- (length vector)) downto 1
do (rotatef (aref vector i)
Line 1,459 ⟶ 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">
<lang Ruby>
SIZE = 9
ordered = (1..SIZE).to_a
Line 1,484 ⟶ 1,671:
 
puts "#{shuffled} Your score: #{score}"
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.string, std.conv, std.algorithm,
std.range;
 
Line 1,501 ⟶ 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 1,514 ⟶ 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|Egel}}==
<syntaxhighlight lang="egel">
<lang Egel>
import "prelude.eg"
import "io.ego"
Line 1,554 ⟶ 1,915:
 
def main =
let XX = fromto 1 9 in game XX (shuffle XX) 0</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,662 ⟶ 2,023:
 
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,699 ⟶ 2,060:
 
=={{header|Elena}}==
ELENA 46.x:
<langsyntaxhighlight lang="elena">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?");
Line 1,724 ⟶ 2,085:
console.printLine("You took ",tries," attempts to put the digits in order!").readChar()
}</langsyntaxhighlight>
 
=={{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,747 ⟶ 2,108:
end
 
Number_reversal_game.start( 9 )</langsyntaxhighlight>
 
{{out}}
Line 1,772 ⟶ 2,133:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( number_reversal_game ).
 
Line 1,796 ⟶ 2,157:
 
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,816 ⟶ 2,177:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
function accending(sequence s)
Line 1,870 ⟶ 2,231:
end while
 
printf(1,"\nYou took %d tries to put the digits in order.", tries)</langsyntaxhighlight>
 
Output:
Line 1,894 ⟶ 2,255:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let rand = System.Random()
 
while true do
Line 1,914 ⟶ 2,275:
printfn "\nYou took %i moves to put the digits in order!\n" i
 
move 1</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel math math.parser math.ranges
namespaces random sequences strings ;
IN: rosetta.number-reversal
Line 1,946 ⟶ 2,307:
: play ( -- )
0 trials set
make-jumbled-array game-loop ;</langsyntaxhighlight>
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="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
Line 1,971 ⟶ 2,332:
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</langsyntaxhighlight>
{{out}}
<pre>= 1= 6= 4= 5= 8= 7= 9= 2= 3
Line 2,001 ⟶ 2,362:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
variable flips
Line 2,050 ⟶ 2,411:
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 2,107 ⟶ 2,468:
end function
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 2,113 ⟶ 2,474:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,155 ⟶ 2,516:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">sorted = [*(1..9)]
arr = sorted.clone()
 
Line 2,172 ⟶ 2,533:
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 2,210 ⟶ 2,571:
start <- shuffle goal
playNRG 1 start</langsyntaxhighlight>
Play:
<pre>*Main> numberRevGame
Line 2,225 ⟶ 2,586:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest"> WRITE(Messagebox) "You took ", Reversals(), " attempts"
 
FUNCTION Reversals()
Line 2,247 ⟶ 2,608:
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 2,318 ⟶ 2,679:
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 2,346 ⟶ 2,707:
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Number Reversal Game is a room.
 
The current list is a list of numbers that varies.
Line 2,385 ⟶ 2,746:
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 2,406 ⟶ 2,767:
steps = steps+1
)
writeln("Done! That took you ", steps, " steps")</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Reversal.bas"
110 RANDOMIZE
120 NUMERIC NR(1 TO 9)
Line 2,447 ⟶ 2,808:
460 IF NR(J)>NR(J+1) THEN LET ORDERED=0:EXIT FOR
470 NEXT
480 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'misc' NB. for the verb prompt
INTRO=: noun define
Line 2,472 ⟶ 2,833:
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 2,490 ⟶ 2,851:
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 2,565 ⟶ 2,926:
}
}
}</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 2,579 ⟶ 2,940:
<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 2,647 ⟶ 3,008:
}
 
playGame('start', 'progress', 'score');</langsyntaxhighlight>
<langsyntaxhighlight lang="html4strict"></script>
</body>
</html></langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># Input: the initial array
def play:
def sorted: . == sort;
Line 2,671 ⟶ 3,032:
.list |= reverse($n) | .score +=1;
if .list | sorted then report, break $done else prompt end ))
end); </langsyntaxhighlight>
 
'''Example'''
<langsyntaxhighlight lang="jq">[1,2,3,9,8,7,6,5,4] | play</langsyntaxhighlight>
 
'''Transcript'''
Line 2,690 ⟶ 3,051:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
function numrevgame()
Line 2,707 ⟶ 3,068:
end
 
numrevgame()</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun isAscending(a: IntArray): Boolean {
Line 2,751 ⟶ 3,112:
}
println("So you've completed the game with a score of $count")
}</langsyntaxhighlight>
Sample game:
{{out}}
Line 2,772 ⟶ 3,133:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Initialisation
math.randomseed(os.time())
numList = {values = {}}
Line 2,836 ⟶ 3,197:
until numList:inOrder()
numList:show()
print("\n\nW00t! You scored:", score)</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 2,849 ⟶ 3,210:
To display the values of stack we use Stack statement with no arguments.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Number_Reversal_Game {
PRINT "Given a jumbled list of the numbers 1 to 9,"
Line 2,891 ⟶ 3,252:
}
Number_Reversal_Game
</syntaxhighlight>
</lang>
 
=={{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 2,928 ⟶ 3,289:
fprintf('\nPlay again soon!\n')
end
end</langsyntaxhighlight>
{{out}}
<pre>Given a list of numbers, try to put them into ascending order
Line 2,948 ⟶ 3,309:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import random, rdstdin, strutils, algorithm
randomize()
 
Line 2,983 ⟶ 3,344:
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 3,002 ⟶ 3,363:
=== Imperative ===
 
<langsyntaxhighlight lang="ocaml">let swap ar i j =
let tmp = ar.(i) in
ar.(i) <- ar.(j);
Line 3,049 ⟶ 3,410:
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 3,101 ⟶ 3,462:
in
loop 1 li
;;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: reversalGame
Line 3,120 ⟶ 3,481:
1+ l left(n) reverse l right(l size n -) + ->l
]
"You won ! Your score is :" . println ;</langsyntaxhighlight>
 
{{out}}
Line 3,139 ⟶ 3,500:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {Main}
proc {Loop N Xs}
Line 3,197 ⟶ 3,558:
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 3,213 ⟶ 3,574:
);
score
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang Pascal>
program NumberReversalGame;
 
Line 3,319 ⟶ 3,680:
WriteLn;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">use List::Util qw(shuffle);
 
my $turn = 0;
Line 3,341 ⟶ 3,702:
 
print " @jumble\n";
print "You won in $turn turns.\n";</langsyntaxhighlight>
 
Output:
Line 3,357 ⟶ 3,718:
=={{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 3,378 ⟶ 3,739:
end while
printf(1,"\nYou took %d turns to put the digits in order.", turns)</langsyntaxhighlight>
{{out}}
<pre style="font-size: 8px">
Line 3,398 ⟶ 3,759:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php">class ReversalGame {
private $numbers;
Line 3,453 ⟶ 3,814:
$game = new ReversalGame();
$game->play();
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de reversalGame ()
Line 3,467 ⟶ 3,828:
(NIL (num? (read)))
(setq Lst (flip Lst @))
(inc 'Cnt) ) ) )</langsyntaxhighlight>
Output:
<pre>: (reversalGame)
Line 3,481 ⟶ 3,842:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
digits: procedure options (main); /* 23 April 2010 */
declare s character (9) varying;
Line 3,515 ⟶ 3,876:
go to restart;
end digits;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
#adding the below function to the previous users submission to prevent the small
#chance of getting an array that is in ascending order.
Line 3,543 ⟶ 3,904:
"$Array"
"Your score: $nTries"
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">play :- random_numbers(L), do_turn(0,L), !.
 
do_turn(N, L) :-
Line 3,572 ⟶ 3,933:
print_list(L) :-
atomic_list_concat(L, ' ', Lf),
format('(~w) ',Lf).</langsyntaxhighlight>
{{out}}
<pre>
Line 3,595 ⟶ 3,956:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim MyList(9)
 
Declare is_list_sorted()
Line 3,641 ⟶ 4,002:
Next
ProcedureReturn #True
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">'''
number reversal game
Given a jumbled list of the numbers 1 to 9
Line 3,665 ⟶ 4,026:
data[:flip] = reversed(data[:flip])
 
print('\nYou took %2i attempts to put the digits in order!' % trials)</langsyntaxhighlight>
 
'''Sample output:'''
Line 3,692 ⟶ 4,053:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 temp put
[] 9 times
[ i^ 1+ join ]
Line 3,709 ⟶ 4,070:
say "That took "
temp take echo
say " reversals." ] is play ( --> )</langsyntaxhighlight>
 
{{out}}
Line 3,736 ⟶ 4,097:
 
=={{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 3,759 ⟶ 4,120:
# 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 3,771 ⟶ 4,132:
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 3,781 ⟶ 4,142:
[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}}==
Line 3,788 ⟶ 4,149:
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" perl6line>repeat while [<] my @jumbled-list {
@jumbled-list = (1..9).pick(*)
}
Line 3,802 ⟶ 4,163:
 
say " @jumbled-list[]";
say "You won in $turn turns.";</langsyntaxhighlight>
 
Output:
Line 3,823 ⟶ 4,184:
 
=={{header|Rascal}}==
<langsyntaxhighlight Rascallang="rascal">import Prelude;
import vis::Figure;
import vis::Render;
Line 3,859 ⟶ 4,220:
render(figure);
}</langsyntaxhighlight>
 
Output:
Line 3,867 ⟶ 4,228:
=={{header|REBOL}}==
 
<langsyntaxhighlight REBOLlang="rebol">REBOL []
 
print "NUMBER REVERSAL GAME"
Line 3,888 ⟶ 4,249:
]
 
print rejoin ["You took " tries " attempts."]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,896 ⟶ 4,257:
:::* &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 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.*/
Line 3,924 ⟶ 4,285:
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>
Line 3,976 ⟶ 4,337:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Number reversal game
 
Line 4,027 ⟶ 4,388:
svect = left(svect, len(svect) - 1)
see svect
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,043 ⟶ 4,404:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">ary = (1..9).to_a
ary.shuffle! while ary == ary.sort
score = 0
Line 4,053 ⟶ 4,414:
end
p ary
puts "Your score: #{score}"</langsyntaxhighlight>
 
sample output:
Line 4,069 ⟶ 4,430:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 9 ' get numbers 1 to 9
n(i) = i
next i
Line 4,108 ⟶ 4,469:
a$ = b$ + mid$(a$,i + 2)
goto [loop]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand 0.7.3}}
<langsyntaxhighlight Rustlang="rust">use rand::prelude::*;
use std::io::stdin;
 
Line 4,157 ⟶ 4,518:
attempt - 1 // Remove additionally counted attempt
);
}</langsyntaxhighlight>
{{out}}
<pre>Number reversal game:
Line 4,182 ⟶ 4,543:
 
=={{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 4,210 ⟶ 4,571:
 
play(9)
}</langsyntaxhighlight>
{{out}}
<pre>1. 8 4 2 9 6 3 7 5 1 How many to flip? 3
Line 4,230 ⟶ 4,591:
{{libheader|Scheme/SRFIs}}
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme read)
Line 4,267 ⟶ 4,628:
 
(play-game (make-randomised-list) 1)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,297 ⟶ 4,658:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 4,333 ⟶ 4,694:
until list = sortedList;
writeln("Congratulations, you sorted the list in " <& score <& " reversals.");
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,348 ⟶ 4,709:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
// set the initial list of digits
set currentList to 1..9 sorted by random of a million
Line 4,369 ⟶ 4,730:
 
answer "You sorted it in " & numberOfTurns & " turns!" titled "Congratulations!"
</syntaxhighlight>
</lang>
 
=={{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; # best-shuffle
 
Line 4,383 ⟶ 4,790:
 
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 4,428 ⟶ 4,835:
if {$outcome ne "quit"} {
puts "\nYou took $outcome attempts to put the digits in order."
}</langsyntaxhighlight>
Sample output:
<pre>
Line 4,454 ⟶ 4,861:
 
=={{header|True BASIC}}==
<langsyntaxhighlight lang="basic">
RANDOMIZE
 
Line 4,521 ⟶ 4,928:
PRINT "Necesitaste "; ltrim$(rtrim$(str$(intentos))); " intentos."
END
</syntaxhighlight>
</lang>
 
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
numbers=RANDOM_NUMBERS (1,9,9),nr=0
Line 4,563 ⟶ 4,970:
ENDIF
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 4,591 ⟶ 4,998:
{{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 4,690 ⟶ 5,097:
fi
fi
done</langsyntaxhighlight>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight 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
Line 4,752 ⟶ 5,159:
Debug.Print "You took"; turns; "turns to put the digits in order."
End Sub</langsyntaxhighlight>{{out}}
<pre>Given a jumbled list of the numbers 1 to 9
you must select how many digits from the left to reverse.
Line 4,766 ⟶ 5,173:
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}}<langsyntaxhighlight ecmascriptlang="wren">
import "./sort" for Sort
import "random" for Random
import "io" for Stdin, Stdout
Line 4,811 ⟶ 5,270:
System.print("Here's your list now : %(numbers)")
}
System.print("So you've completed the game with a score of %(count)")</langsyntaxhighlight>
 
{{out}}
Line 4,839 ⟶ 5,298:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int Taken, I, Digit, Num, Score, Rev, Temp;
char List(9);
include c:\cxpl\codes;
Line 4,862 ⟶ 5,321:
Text(0, "^M^JCongrats! You did it in "); IntOut(0, Score);
Text(0, " moves!!^M^J");
]</langsyntaxhighlight>
 
Example output:
Line 4,878 ⟶ 5,337:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">// Rosetta Code problem: https://www.rosettacode.org/wiki/Number_reversal_game
// by Jjuanhdez, 06/2022
 
Line 4,934 ⟶ 5,393:
until false
print "\n\n You needed ", intentos, " attempts."
end</langsyntaxhighlight>
 
 
=={{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 4,951 ⟶ 5,410:
scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts));</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user