Number reversal game: Difference between revisions

added Easylang
(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
(added Easylang)
 
(6 intermediate revisions by 6 users not shown)
Line 389:
end NumberReverse;
</syntaxhighlight>
 
=={{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}}==
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)
Line 1,149 ⟶ 1,244:
 
=={{header|C++}}==
===Version 1 (crude)===
The C code can be used with C++, although the following uses proper C++ iostreams:
<syntaxhighlight lang="cpp">void number_reversal_game()
Line 1,187 ⟶ 1,283:
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).
<syntaxhighlight lang="cpp">
Line 1,239 ⟶ 1,336:
<< "You needed " << score << " reversals." << std::endl;
return 0;
}
</syntaxhighlight>
 
====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>
Line 1,539 ⟶ 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}}==
Line 1,724 ⟶ 2,101:
 
=={{header|Elena}}==
ELENA 46.x:
<syntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,730 ⟶ 2,107:
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 4,395 ⟶ 4,772:
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}}==
Line 4,846 ⟶ 5,269:
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-sort}}<syntaxhighlight lang="ecmascriptwren">
import "./sort" for Sort
import "random" for Random
import "io" for Stdin, Stdout
2,042

edits