Number reversal game: Difference between revisions
m
syntax highlighting fixup automation
(Applesoft BASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 25:
=={{header|8080 Assembly}}==
<
org 100h
;;; Initialize RNG from keypresses
Line 178:
list: equ listhi*256
rnddat: equ list+16
</syntaxhighlight>
{{out}}
<pre>Please press some keys to seed the RNG...done.
Line 195:
{{trans|Python}}
<
V trials = 0
Line 203:
data.reverse_range(0 .< flip)
print("\nYou took #. attempts to put the digits in order!".format(trials))</
{{out}}
Line 222:
=={{header|Action!}}==
<
BYTE i,j,tmp
Line 297:
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</
{{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}}==
<
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>
=={{header|APL}}==
{{works with|Dyalog APL}}
<
list←{9?9}⍣{⍺≢⍳9}⊢⍬
swaps←0
Line 402:
⎕←(⍕list),': Congratulations!'
⎕←'Swaps:',swaps
∇</
{{out}}
<pre>8 7 2 6 5 3 1 9 4: swap how many? 8
Line 417:
Swaps: 10</pre>
=={{header|Applesoft BASIC}}==
<
110 LET A$ = "123456789"
120 FOR S = 0 TO 1 STEP 0
Line 440:
520 LET N$ = MID$ (N$,1,R - 1) + I$ + MID$ (N$,R + 1)
530 RETURN
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|Ruby}}
<
while [arr = sort arr]->
Line 458:
]
print ["Your score:" score]</
{{out}}
Line 472:
=={{header|Astro}}==
<
var data, trials = list(1..9), 0
Line 484:
data[:flip] = reverse data[:flip]
print '\nYou took ${trials} attempts to put digits in order!'</
=={{header|AutoHotkey}}==
<
ScrambledList := CorrectList := "1 2 3 4 5 6 7 8 9" ; Declare two identical correct sequences
Line 520:
Out := A_LoopField Out
Return Out
}</
=={{header|AWK}}==
<
print "\nWelcome to the number reversal game!\n"
Line 601:
}
END { print "\n\nBye!" }</
=={{header|BASIC}}==
Line 608:
{{works with|FreeBASIC}}
<
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 662:
LOOP
PRINT : PRINT "You took "; LTRIM$(RTRIM$(STR$(tries))); " tries to put the digits in order."</
Sample output:
Line 681:
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
print "Dada una lista aleatoria de numeros del 1 al 9,"
print "indica cuantos digitos de la izquierda voltear."
Line 741:
print chr(10) + chr(10) + " Necesitaste "; intentos; " intentos."
end
</syntaxhighlight>
{{out}}
<pre>
Line 766:
=={{header|Batch File}}==
Note that I did not use the FOR command for looping. I used Batch File labels instead.
<
::
::Number Reversal Game Task from Rosetta Code Wiki
Line 837:
goto :loopgame
)
</syntaxhighlight>
Sample Output:
<pre>
Line 878:
=={{header|BBC BASIC}}==
Note the use of the MOD(array()) function to test the equality of two arrays.
<
list%() = 1, 2, 3, 4, 5, 6, 7, 8, 9
done%() = list%()
Line 909:
SWAP a%(i%), a%(n%-i%)
NEXT
ENDPROC</
'''Output:'''
<pre>
Line 925:
=={{header|Brat}}==
<
length = sorted.length
numbers = sorted.shuffle
Line 943:
p numbers
p "It took #{turns} turns to sort numbers."</
=={{header|C}}==
An example of a number reversal game could be:
<
{
printf("Number Reversal Game. Type a number to flip the first n numbers.");
Line 978:
}
printf("Hurray! You solved it in %d moves!\n", tries);
}</
Which uses the following helper functions:
<
{
//We'll just be swapping 100 times. Could be more/less. Doesn't matter much.
Line 1,024:
}
return 1;
}</
=={{header|C sharp|C#}}==
C# 3.0
<
using System.Linq;
Line 1,058:
Console.ReadLine();
}
}</
C# 1.0
<
{
static void Main(string[] args)
Line 1,146:
return retArray;
}
}</
=={{header|C++}}==
The C code can be used with C++, although the following uses proper C++ iostreams:
<
{
cout << "Number Reversal Game. Type a number to flip the first n numbers.";
Line 1,183:
}
cout << "Hurray! You solved it in %d moves!\n";
}</
This uses the same helper functions as the C version.
Line 1,189:
=== Alternate version using the C++ standard library ===
This version uses the C++ standard library (note that none of the C helper functions are needed).
<
#include <iostream>
#include <algorithm>
Line 1,240:
return 0;
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(let [[x y] (split-at n coll)]
(concat (reverse x) y )))
Line 1,258:
(flush)
(let [flipcount (read)]
(recur (flip-at flipcount unsorted), (inc steps))))))</
=={{header|CLU}}==
<
% 'misc.lib'
Line 1,316:
end
stream$putl(po, "\nScore = " || int$unparse(score))
end start_up</
{{out}}
<pre>792184365: reverse how many? 2
Line 1,333:
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. REVERSAL.
Line 1,449:
GOBACK.
END PROGRAM REVERSE.
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(loop for i from (1- (length vector)) downto 1
do (rotatef (aref vector i)
Line 1,484:
(replace slice (nreverse slice))))))
(format t "~A~%Congratulations, you did it in ~D reversals!~%" numbers score))))
</syntaxhighlight>
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
SIZE = 9
ordered = (1..SIZE).to_a
Line 1,509:
puts "#{shuffled} Your score: #{score}"
</syntaxhighlight>
=={{header|D}}==
<
std.range;
Line 1,526:
}
writefln("\nYou took %d attempts.", trial);
}</
{{out}}
<pre>1: [7, 2, 1, 6, 3, 8, 9, 5, 4] How many numbers to flip? 7
Line 1,541:
=={{header|Egel}}==
<syntaxhighlight lang="egel">
import "prelude.eg"
import "io.ego"
Line 1,579:
def main =
let XX = fromto 1 9 in game XX (shuffle XX) 0</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,687:
end
</syntaxhighlight>
{{out}}
Line 1,725:
=={{header|Elena}}==
ELENA 4.x:
<
import extensions;
Line 1,749:
console.printLine("You took ",tries," attempts to put the digits in order!").readChar()
}</
=={{header|Elixir}}==
{{trans|Erlang}}
<
def start( n ) when n > 1 do
IO.puts "Usage: #{usage(n)}"
Line 1,772:
end
Number_reversal_game.start( 9 )</
{{out}}
Line 1,797:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( number_reversal_game ).
Line 1,821:
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>
{{out}}
Not being a very good player I show a test run with only 3 numbers.
Line 1,841:
=={{header|Euphoria}}==
<
function accending(sequence s)
Line 1,895:
end while
printf(1,"\nYou took %d tries to put the digits in order.", tries)</
Output:
Line 1,919:
=={{header|F Sharp|F#}}==
<
while true do
Line 1,939:
printfn "\nYou took %i moves to put the digits in order!\n" i
move 1</
=={{header|Factor}}==
<
namespaces random sequences strings ;
IN: rosetta.number-reversal
Line 1,971:
: play ( -- )
0 trials set
make-jumbled-array game-loop ;</
=={{header|FOCAL}}==
<
01.20 F X=1,9;T %1,D(X)
01.30 T !;A "HOW MANY",R
Line 1,996:
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</
{{out}}
<pre>= 1= 6= 4= 5= 8= 7= 9= 2= 3
Line 2,026:
=={{header|Forth}}==
<
variable flips
Line 2,075:
7 flip
9 6 7 5 8 2 1 4 3 ok
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 2,132:
end function
end program</
=={{header|FreeBASIC}}==
Line 2,138:
=={{header|Go}}==
<
import (
Line 2,180:
}
}
}</
=={{header|Groovy}}==
<
arr = sorted.clone()
Line 2,197:
steps += 1
}
println "Done! That took you ${steps} steps"</
=={{header|Haskell}}==
Using Rosetta [[Knuth shuffle#Haskell|Knuth Shuffle]]
<
import Control.Arrow
import Rosetta.Knuthshuffle
Line 2,235:
start <- shuffle goal
playNRG 1 start</
Play:
<pre>*Main> numberRevGame
Line 2,250:
=={{header|HicEst}}==
<
FUNCTION Reversals()
Line 2,272:
IF( SUM(temp) == 8 ) RETURN
ENDDO
END</
=={{header|Icon}} and {{header|Unicon}}==
<
local x,nums,R,flips
Line 2,343:
map(trim(read())) ? return tab(upto(' ')|0)
end
</syntaxhighlight>
Sample output:<pre>Input a position. The list will be flipped left to right at that point.
Line 2,371:
=={{header|Inform 7}}==
<
The current list is a list of numbers that varies.
Line 2,410:
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.</
=={{header|Io}}==
<
Range clone setRange(a,z)
)
Line 2,431:
steps = steps+1
)
writeln("Done! That took you ", steps, " steps")</
=={{header|IS-BASIC}}==
<
110 RANDOMIZE
120 NUMERIC NR(1 TO 9)
Line 2,472:
460 IF NR(J)>NR(J+1) THEN LET ORDERED=0:EXIT FOR
470 NEXT
480 END DEF</
=={{header|J}}==
'''Solution:'''
<
INTRO=: noun define
Line 2,497:
end.
'You took ',(": score), ' attempts to put the numbers in order.'
)</
'''Example Usage:'''
<
Number Reversal Game
Sort the numbers in ascending order by repeatedly
Line 2,515:
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.</
=={{header|Java}}==
<
import java.util.ArrayList;
import java.util.Scanner;
Line 2,590:
}
}
}</
=={{header|JavaScript}}==
Use <code>knuth_shuffle()</code> function from [[Knuth shuffle#JavaScript|here]].
<
<head>
<title>Number Reversal Game</title>
Line 2,604:
<div id="progress"></div>
<div id="score"></div>
<script type="text/javascript"></
<
var scoreId = progress.scoreId,
result = 'You took ' + progress.count + ' attempts to put the digits in order!';
Line 2,672:
}
playGame('start', 'progress', 'score');</
<
</body>
</html></
=={{header|jq}}==
<
def play:
def sorted: . == sort;
Line 2,696:
.list |= reverse($n) | .score +=1;
if .list | sorted then report, break $done else prompt end ))
end); </
'''Example'''
<
'''Transcript'''
Line 2,715:
=={{header|Julia}}==
<
function numrevgame()
Line 2,732:
end
numrevgame()</
=={{header|Kotlin}}==
<
fun isAscending(a: IntArray): Boolean {
Line 2,776:
}
println("So you've completed the game with a score of $count")
}</
Sample game:
{{out}}
Line 2,797:
=={{header|Lua}}==
<
math.randomseed(os.time())
numList = {values = {}}
Line 2,861:
until numList:inOrder()
numList:show()
print("\n\nW00t! You scored:", score)</
=={{header|M2000 Interpreter}}==
Line 2,874:
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,"
Line 2,916:
}
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]]</
=={{header|MATLAB}}==
<
list = randperm(9);
while issorted(list)
Line 2,953:
fprintf('\nPlay again soon!\n')
end
end</
{{out}}
<pre>Given a list of numbers, try to put them into ascending order
Line 2,973:
=={{header|Nim}}==
<
randomize()
Line 3,008:
reverse(data, 0, flip - 1)
echo "You took ", trials, " attempts to put the digits in order!"</
Example:
<pre>#1: List: '6 5 8 7 2 1 9 3 4' Flip how many?: 5
Line 3,027:
=== Imperative ===
<
let tmp = ar.(i) in
ar.(i) <- ar.(j);
Line 3,074:
print_endline "Congratulations!";
Printf.printf "You took %d attempts to put the digits in order.\n" !n;
;;</
=== Functional ===
<
let rec aux acc i = function
| [] -> acc
Line 3,126:
in
loop 1 li
;;</
=={{header|Oforth}}==
<
: reversalGame
Line 3,145:
1+ l left(n) reverse l right(l size n -) + ->l
]
"You won ! Your score is :" . println ;</
{{out}}
Line 3,164:
=={{header|Oz}}==
<
proc {Main}
proc {Loop N Xs}
Line 3,222:
end
in
{Main}</
=={{header|PARI/GP}}==
<
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,238:
);
score
};</
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
program NumberReversalGame;
Line 3,344:
WriteLn;
end.
</syntaxhighlight>
=={{header|Perl}}==
<
my $turn = 0;
Line 3,366:
print " @jumble\n";
print "You won in $turn turns.\n";</
Output:
Line 3,382:
=={{header|Phix}}==
Simplified copy of [[Number_reversal_game#Euphoria|Euphoria]]
<
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,403:
end while
printf(1,"\nYou took %d turns to put the digits in order.", turns)</
{{out}}
<pre style="font-size: 8px">
Line 3,423:
=={{header|PHP}}==
<
private $numbers;
Line 3,478:
$game = new ReversalGame();
$game->play();
</syntaxhighlight>
=={{header|PicoLisp}}==
<
(de reversalGame ()
Line 3,492:
(NIL (num? (read)))
(setq Lst (flip Lst @))
(inc 'Cnt) ) ) )</
Output:
<pre>: (reversalGame)
Line 3,506:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
digits: procedure options (main); /* 23 April 2010 */
declare s character (9) varying;
Line 3,540:
go to restart;
end digits;
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight 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,568:
"$Array"
"Your score: $nTries"
</syntaxhighlight>
=={{header|Prolog}}==
<
do_turn(N, L) :-
Line 3,597:
print_list(L) :-
atomic_list_concat(L, ' ', Lf),
format('(~w) ',Lf).</
{{out}}
<pre>
Line 3,620:
=={{header|PureBasic}}==
<
Declare is_list_sorted()
Line 3,666:
Next
ProcedureReturn #True
EndProcedure</
=={{header|Python}}==
<
number reversal game
Given a jumbled list of the numbers 1 to 9
Line 3,690:
data[:flip] = reversed(data[:flip])
print('\nYou took %2i attempts to put the digits in order!' % trials)</
'''Sample output:'''
Line 3,717:
=={{header|Quackery}}==
<
[] 9 times
[ i^ 1+ join ]
Line 3,734:
say "That took "
temp take echo
say " reversals." ] is play ( --> )</
{{out}}
Line 3,761:
=={{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,784:
# Victory!
cat("Well done. You needed", trials, "flips. \n")
}</
Sample output:
<syntaxhighlight lang="text">>reversalGame()
Welcome to the Number Reversal Game!
Sort the numbers into ascending order by repeatedly
Line 3,796:
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.</
=={{header|Racket}}==
<
(let loop ([nums (range 1 10)] [n 0])
(cond [(apply < nums) (if (zero? n)
Line 3,806:
[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))]))</
=={{header|Raku}}==
Line 3,813:
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"
@jumbled-list = (1..9).pick(*)
}
Line 3,827:
say " @jumbled-list[]";
say "You won in $turn turns.";</
Output:
Line 3,848:
=={{header|Rascal}}==
<
import vis::Figure;
import vis::Render;
Line 3,884:
render(figure);
}</
Output:
Line 3,892:
=={{header|REBOL}}==
<
print "NUMBER REVERSAL GAME"
Line 3,913:
]
print rejoin ["You took " tries " attempts."]</
=={{header|REXX}}==
Line 3,921:
:::* allows the user to enter '''quit'''
:::* allows the user to halt the game via '''Cntl-Break''' (or equivalent)
<
signal on halt /*allows the CBLF to HALT the program.*/
___= copies('─', 9); pad=left('', 9) /*a fence used for computer's messages.*/
Line 3,949:
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 /* " " " " " " " " */</
{{out|output|text= from playing one game of the ''number reversal game'':
<pre>
Line 4,001:
=={{header|Ring}}==
<
# Project : Number reversal game
Line 4,052:
svect = left(svect, len(svect) - 1)
see svect
</syntaxhighlight>
Output:
<pre>
Line 4,068:
=={{header|Ruby}}==
<
ary.shuffle! while ary == ary.sort
score = 0
Line 4,078:
end
p ary
puts "Your score: #{score}"</
sample output:
Line 4,094:
=={{header|Run BASIC}}==
<
n(i) = i
next i
Line 4,133:
a$ = b$ + mid$(a$,i + 2)
goto [loop]
end</
=={{header|Rust}}==
{{libheader|rand 0.7.3}}
<
use std::io::stdin;
Line 4,182:
attempt - 1 // Remove additionally counted attempt
);
}</
{{out}}
<pre>Number reversal game:
Line 4,207:
=={{header|Scala}}==
<
def play(n: Int, cur: List[Int], goal: List[Int]) {
readLine(s"""$n. ${cur mkString " "} How many to flip? """) match {
Line 4,235:
play(9)
}</
{{out}}
<pre>1. 8 4 2 9 6 3 7 5 1 How many to flip? 3
Line 4,255:
{{libheader|Scheme/SRFIs}}
<
(import (scheme base)
(scheme read)
Line 4,292:
(play-game (make-randomised-list) 1)
</syntaxhighlight>
{{out}}
Line 4,322:
=={{header|Seed7}}==
<
const proc: main is func
Line 4,358:
until list = sortedList;
writeln("Congratulations, you sorted the list in " <& score <& " reversals.");
end func;</
{{out}}
Line 4,373:
=={{header|SenseTalk}}==
<
// set the initial list of digits
set currentList to 1..9 sorted by random of a million
Line 4,394:
answer "You sorted it in " & numberOfTurns & " turns!" titled "Congratulations!"
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|Perl}}
<
var jumble = @(1..9).bshuffle; # best-shuffle
Line 4,408:
print " #{jumble.join(' ')}\n";
print "You won in #{turn} turns.\n";</
=={{header|Tcl}}==
<
# Simple shuffler, not very efficient but good enough for here
proc shuffle list {
Line 4,453:
if {$outcome ne "quit"} {
puts "\nYou took $outcome attempts to put the digits in order."
}</
Sample output:
<pre>
Line 4,479:
=={{header|True BASIC}}==
<
RANDOMIZE
Line 4,546:
PRINT "Necesitaste "; ltrim$(rtrim$(str$(intentos))); " intentos."
END
</syntaxhighlight>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
numbers=RANDOM_NUMBERS (1,9,9),nr=0
Line 4,588:
ENDIF
ENDLOOP
</syntaxhighlight>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 4,616:
{{trans|AWK}}
{{works with|pdksh|5.2.14}}
<
print "You must put the numbers in order from 1 to 9."
Line 4,715:
fi
fi
done</
=={{header|VBA}}==
{{trans|Phix}}<
Dim t As Variant, i As Integer
For i = UBound(a) To LBound(a) + 1 Step -1
Line 4,777:
Debug.Print "You took"; turns; "turns to put the digits in order."
End Sub</
<pre>Given a jumbled list of the numbers 1 to 9
you must select how many digits from the left to reverse.
Line 4,794:
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-sort}}<
import "/sort" for Sort
import "random" for Random
Line 4,836:
System.print("Here's your list now : %(numbers)")
}
System.print("So you've completed the game with a score of %(count)")</
{{out}}
Line 4,864:
=={{header|XPL0}}==
<
char List(9);
include c:\cxpl\codes;
Line 4,887:
Text(0, "^M^JCongrats! You did it in "); IntOut(0, Score);
Text(0, " moves!!^M^J");
]</
Example output:
Line 4,903:
=={{header|Yabasic}}==
<
// by Jjuanhdez, 06/2022
Line 4,959:
until false
print "\n\n You needed ", intentos, " attempts."
end</
=={{header|zkl}}==
{{trans|AutoHotkey}}
<
correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string
attempts:=0;
Line 4,976:
scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts));</
{{out}}
<pre>
|