Jump to content

Number reversal game: Difference between revisions

Add Nimrod
(Added MATLAB example.)
(Add Nimrod)
Line 1,562:
Input["How many digits would you like to reverse?"]; score++];
Print@array; Print["Your score:", score]]</lang>
 
=={{header|Nimrod}}==
<lang nimrod>import math, 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 =
var last: T
for c in s:
if c < last:
return false
last = c
return true
 
proc toString[T](s: openarray[T]): string =
result = ""
for i, x in s:
if i > 0:
result.add " "
result.add($x)
 
echo """number reversal game
Given a jumbled list of the numbers 1 to 9
Show the list.
Ask the player how many digits from the left to reverse.
Reverse those digits then ask again.
until all the digits end up in ascending order."""
 
var data = @[1,2,3,4,5,6,7,8,9]
var trials = 0
while isSorted data:
shuffle data
while not isSorted data:
inc trials
var flip = parseInt readLineFromStdin(
"#" & $trials & ": List: '" & toString(data) & "' Flip how many?: ")
reverse(data, 0, flip - 1)
 
echo "You took ", trials, " attempts to put the digits in order!"</lang>
Example:
<pre>#1: List: '6 5 8 7 2 1 9 3 4' Flip how many?: 5
#2: List: '2 7 8 5 6 1 9 3 4' Flip how many?: 6
#3: List: '1 6 5 8 7 2 9 3 4' Flip how many?: 9
#4: List: '4 3 9 2 7 8 5 6 1' Flip how many?: 4
#5: List: '2 9 3 4 7 8 5 6 1' Flip how many?: 8
#6: List: '6 5 8 7 4 3 9 2 1' Flip how many?: 6
#7: List: '3 4 7 8 5 6 9 2 1' Flip how many?: 7
#8: List: '9 6 5 8 7 4 3 2 1' Flip how many?: 3
#9: List: '5 6 9 8 7 4 3 2 1' Flip how many?: 5
#10: List: '7 8 9 6 5 4 3 2 1' Flip how many?: 3
#11: List: '9 8 7 6 5 4 3 2 1' Flip how many?: 9
You took 11 attempts to put the digits in order!</pre>
 
=={{header|OCaml}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.