September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -0,0 +1,18 @@
'''
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.
'''.print()
var data = list('123456789')
var trials = 0
while data == sorted(data): random.shuffle data
while data != sorted(data):
trials += 1
flip = int scan '#$trials: LIST: $(join data) Flip how many?: '
data[:flip] = data[!flip:]
print '\nYou took $trials attempts to put digits in order!'

View file

@ -1,99 +0,0 @@
class
NUMBER_REVERSAL_GAME
feature
play_game
local
count: INTEGER
do
initialize_game
io.put_string ("Let's play the number reversal game.%N")
across numbers as ar loop io.put_string (ar.item.out + "%T") end
from
until
is_sorted(numbers,1, numbers.count)
loop
io.put_string ("%NHow many numbers should be reversed?%N")
io.read_integer
reverse_array(io.last_integer)
across numbers as ar loop io.put_string (ar.item.out + "%T") end
count:= count+1
end
io.put_string ("%NYou needed "+ count.out + " reversals.")
end
feature {NONE}
initialize_game
local
random: V_RANDOM
item,i: INTEGER
do
create random
create numbers.make_empty
from
i:= 1
until
numbers.count = 9
loop
item :=random.bounded_item (1, 9)
if numbers.has (item)= FALSE then
numbers.force(item, i)
i:= i+1
end
random.forth
end
end
numbers: ARRAY[INTEGER]
reverse_array(upper:INTEGER)
require
upper_positive: upper >0
ar_not_void: numbers /= void
local
i,j:INTEGER
new_array: ARRAY[INTEGER]
do
create new_array.make_empty
new_array.copy (numbers)
from
i:= 1
j:=upper
until
i>j
loop
new_array[i]:=numbers[j]
new_array[j]:=numbers[i]
i:=i+1
j:=j-1
end
numbers := new_array
end
is_sorted(ar: ARRAY[INTEGER];l, r: INTEGER): BOOLEAN
require
ar_not_empty: ar.is_empty= FALSE
local
smaller : BOOLEAN
i: INTEGER
do
smaller:= TRUE
from
i:= l
until
i=r
loop
if ar[i]> ar[i+1] then
smaller:= FALSE
end
i:= i+1
end
if smaller = TRUE then
RESULT := TRUE
else
RESULT:= FALSE
end
end
end

View file

@ -1,14 +0,0 @@
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
do
create nr
nr.play_game
end
nr: NUMBER_REVERSAL_GAME
end

View file

@ -1,21 +1,25 @@
#import system.
#import system'routines.
#import extensions.
import system'routines.
import extensions.
#symbol program =
program =
[
#var sorted := Array new:9 set &every: (&index:n) [ n + 1 ].
#var values := sorted clone randomize:9.
var sorted := Array new:9; populate(:n)( n + 1 ).
var values := sorted clone; randomize:9.
#var tries := Integer new.
#loop (sorted sequenceEqual:values)!
while (sorted sequenceEqual:values)
[
tries += 1.
console writeLiteral:"# ":tries:" : LIST : ":values:" - Flip how many?".
values reverse:(console readLine toInt) &at:0.
values := sorted randomize:9
].
console writeLine:"You took ":tries:" attempts to put the digits in order!" readChar.
var tries := Integer new.
until (sorted sequenceEqual:values)
[
tries append:1.
console print("# ",tries," : LIST : ",values," - Flip how many?").
values sequenceReverse(console readLine; toInt) at:0.
].
console printLine("You took ",tries," attempts to put the digits in order!"); readChar.
].

View file

@ -0,0 +1,19 @@
# Input: the initial array
def play:
def sorted: . == sort;
def reverse(n): (.[0:n] | reverse) + .[n:];
def prompt: "List: \(.list)\nEnter a pivot number: ";
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);

View file

@ -0,0 +1 @@
[1,2,3,9,8,7,6,5,4] | play

View file

@ -0,0 +1,18 @@
# 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()

View file

@ -0,0 +1,42 @@
// 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")
}

View file

@ -1,60 +1,65 @@
math.randomseed(os.time()) -- Random values are used by numList:build()
math.random()
-- Initialisation
math.randomseed(os.time())
numList = {values = {}}
function numList:contains (n) -- Check whether list contains n
for k, v in pairs(self.values) do
if v == n then return true end
end
return false
-- Check whether list contains n
function numList:contains (n)
for k, v in pairs(self.values) do
if v == n then return true end
end
return false
end
function numList:inOrder () -- Check whether list is in order
for k, v in pairs(self.values) do
if k ~=v then return false end
end
return true
-- Check whether list is in order
function numList:inOrder ()
for k, v in pairs(self.values) do
if k ~=v then return false end
end
return true
end
function numList:build () -- Create necessarily out-of-order list
local newNum
repeat
for i = 1, 9 do
repeat
newNum = math.random(1, 9)
until not numList:contains(newNum)
table.insert(self.values, newNum)
end
until not numList:inOrder()
-- Create necessarily out-of-order list
function numList:build ()
local newNum
repeat
for i = 1, 9 do
repeat
newNum = math.random(1, 9)
until not numList:contains(newNum)
table.insert(self.values, newNum)
end
until not numList:inOrder()
end
function numList:show () -- Display list of numbers on one line
for k, v in pairs(self.values) do
io.write(v .. " ")
end
io.write(":\t")
-- Display list of numbers on one line
function numList:show ()
for k, v in pairs(self.values) do
io.write(v .. " ")
end
io.write(":\t")
end
function numList:reverse (n) -- Reverse n values from left
local swapList = {}
for k, v in pairs(self.values) do
table.insert(swapList, v)
end
for i = 1, n do
swapList[i] = self.values[n + 1 - i]
end
self.values = swapList
-- Reverse n values from left
function numList:reverse (n)
local swapList = {}
for k, v in pairs(self.values) do
table.insert(swapList, v)
end
for i = 1, n do
swapList[i] = self.values[n + 1 - i]
end
self.values = swapList
end
local score = 0 -- Start of main procedure
-- Main 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
numList:show()
numList:reverse(tonumber(io.read()))
score = score + 1
until numList:inOrder()
numList:show()
print("\nW00t! You scored:", score)
print("\n\nW00t! You scored:", score)

View file

@ -0,0 +1,36 @@
(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)

View file

@ -0,0 +1,13 @@
correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len();
correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string
attempts:=0;
while(scrambledList!=correctList){ // Repeat until the sequence is correct
n:=ask(("[%d] %s How many numbers (from the left) should be flipped? ")
.fmt(attempts,scrambledList));
try{ n=n.toInt() }catch{ println("Not a number"); continue; }
if(not (0<=n<N)){ println("Out of range"); continue; }
attempts+=1;
// Reverse the first part of the string and add the second part
scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts));