September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -20,4 +20,5 @@ The score is computed as:
|
|||
* [[Bulls and cows/Player]]
|
||||
* [[Guess the number]]
|
||||
* [[Guess the number/With Feedback]]
|
||||
* [[Mastermind]]
|
||||
<br><br>
|
||||
|
|
|
|||
|
|
@ -1,2 +1,5 @@
|
|||
---
|
||||
category:
|
||||
- Puzzles
|
||||
- Games
|
||||
note: Games
|
||||
|
|
|
|||
|
|
@ -1,81 +1,84 @@
|
|||
#define system.
|
||||
#define system'routines.
|
||||
#define extensions.
|
||||
import system'routines.
|
||||
import extensions.
|
||||
|
||||
#class GameMaster
|
||||
class GameMaster
|
||||
{
|
||||
#field theNumbers.
|
||||
#field theAttempt.
|
||||
object theNumbers.
|
||||
object theAttempt.
|
||||
|
||||
#constructor new
|
||||
constructor new
|
||||
[
|
||||
// generate secret number
|
||||
#var aRandomNumbers := (1,2,3,4,5,6,7,8,9) randomize:9.
|
||||
var aRandomNumbers := (1,2,3,4,5,6,7,8,9) randomize:9.
|
||||
|
||||
theNumbers := aRandomNumbers Subarray &index:0 &length:4.
|
||||
theNumbers := aRandomNumbers Subarray:4 at:0.
|
||||
theAttempt := Integer new:1.
|
||||
]
|
||||
|
||||
#method ask
|
||||
ask
|
||||
[
|
||||
#var aRow := console writeLiteral:"Your Guess #":theAttempt:" ?" readLine.
|
||||
var aRow := console print("Your Guess #",theAttempt," ?"); readLine.
|
||||
|
||||
^ aRow toArray.
|
||||
]
|
||||
|
||||
#method proceed : aGuess
|
||||
proceed : aGuess
|
||||
[
|
||||
#var aCows := Integer new:0.
|
||||
#var aBulls := Integer new:0.
|
||||
var aCows := Integer new:0.
|
||||
var aBulls := Integer new:0.
|
||||
|
||||
(aGuess length != 4)
|
||||
? [ aBulls << -1. ]
|
||||
! [
|
||||
0 to:3 &doEach: (:i)
|
||||
if (aGuess length != 4)
|
||||
[ aBulls append int:(-1). ];
|
||||
[
|
||||
try(0 to:3 do(:i)
|
||||
[
|
||||
#var ch := aGuess@i.
|
||||
#var aNumber := ch literal toInt.
|
||||
var ch := aGuess[i].
|
||||
var aNumber := ch literal; toInt.
|
||||
|
||||
// check range
|
||||
((aNumber > 0)and:(aNumber < 10))
|
||||
! [ #throw InvalidArgumentException new. ].
|
||||
ifnot ((aNumber > 0) && (aNumber < 10))
|
||||
[ InvalidArgumentException new; raise. ].
|
||||
|
||||
// check duplicates
|
||||
#var duplicate := aGuess seek &each: x [ (x == ch)and:[ x equal &reference:ch not ] ].
|
||||
(nil != duplicate) ?
|
||||
var duplicate := aGuess seekEach(:x)((x == ch)and:$(x equal reference:ch; not)).
|
||||
if ($nil != duplicate)
|
||||
[
|
||||
#throw InvalidArgumentException new.
|
||||
InvalidArgumentException new; raise.
|
||||
].
|
||||
|
||||
(aNumber == (theNumbers@i))
|
||||
? [ aBulls += 1. ]
|
||||
! [
|
||||
if (aNumber == theNumbers[i])
|
||||
[ aBulls append int:1 ];
|
||||
[
|
||||
(theNumbers ifExists:aNumber)
|
||||
? [ aCows += 1. ].
|
||||
? [ aCows append int:1 ].
|
||||
].
|
||||
]
|
||||
| if &Error: e
|
||||
[
|
||||
aBulls << -1.
|
||||
].
|
||||
])
|
||||
{
|
||||
on(Exception e)
|
||||
[
|
||||
aBulls int := -1
|
||||
]
|
||||
}.
|
||||
].
|
||||
|
||||
^ aBulls =>
|
||||
-1 ? [ console writeLine:"Not a valid guess.". ^ true. ]
|
||||
4 ? [ console writeLine:"Congratulations! You have won!". ^ false. ]
|
||||
aBulls =>
|
||||
-1 [ console printLine:"Not a valid guess.". ^ true ];
|
||||
4 [ console printLine:"Congratulations! You have won!". ^ false ];
|
||||
! [
|
||||
theAttempt += 1.
|
||||
theAttempt append int:1.
|
||||
|
||||
console writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows".
|
||||
console printLine("Your Score is ",aBulls," bulls and ",aCows," cows").
|
||||
|
||||
^ true.
|
||||
^ true
|
||||
].
|
||||
]
|
||||
}
|
||||
|
||||
#symbol program =
|
||||
program =
|
||||
[
|
||||
#var aGameMaster := GameMaster new.
|
||||
var aGameMaster := GameMaster new.
|
||||
|
||||
[ aGameMaster proceed:(aGameMaster ask) ] doWhile.
|
||||
$(aGameMaster proceed:(aGameMaster ask)) doWhile.
|
||||
|
||||
console readChar.
|
||||
].
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(`Cows and Bulls
|
||||
Guess four digit number of unique digits in the range 1 to 9.
|
||||
A correct digit but not in the correct place is a cow.
|
||||
A correct digit in the correct place is a bull.`)
|
||||
// generate pattern
|
||||
pat := make([]byte, 4)
|
||||
rand.Seed(time.Now().Unix())
|
||||
r := rand.Perm(9)
|
||||
for i := range pat {
|
||||
pat[i] = '1' + byte(r[i])
|
||||
}
|
||||
|
||||
// accept and score guesses
|
||||
valid := []byte("123456789")
|
||||
guess:
|
||||
for in := bufio.NewReader(os.Stdin); ; {
|
||||
fmt.Print("Guess: ")
|
||||
guess, err := in.ReadString('\n')
|
||||
if err != nil {
|
||||
fmt.Println("\nSo, bye.")
|
||||
return
|
||||
}
|
||||
guess = strings.TrimSpace(guess)
|
||||
if len(guess) != 4 {
|
||||
// malformed: not four characters
|
||||
fmt.Println("Please guess a four digit number.")
|
||||
continue
|
||||
}
|
||||
var cows, bulls int
|
||||
for ig, cg := range guess {
|
||||
if strings.IndexRune(guess[:ig], cg) >= 0 {
|
||||
// malformed: repeated digit
|
||||
fmt.Printf("Repeated digit: %c\n", cg)
|
||||
continue guess
|
||||
}
|
||||
switch bytes.IndexByte(pat, byte(cg)) {
|
||||
case -1:
|
||||
if bytes.IndexByte(valid, byte(cg)) == -1 {
|
||||
// malformed: not a digit
|
||||
fmt.Printf("Invalid digit: %c\n", cg)
|
||||
continue guess
|
||||
}
|
||||
default: // I just think cows should go first
|
||||
cows++
|
||||
case ig:
|
||||
bulls++
|
||||
}
|
||||
}
|
||||
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
|
||||
if bulls == 4 {
|
||||
fmt.Println("You got it.")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
. "fmt"
|
||||
"rand"
|
||||
"time"
|
||||
"os"
|
||||
"bufio"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func generateTarget() int {
|
||||
rand.Seed(time.Nanoseconds())
|
||||
// loop until we find a number that doesn't have dupes
|
||||
for {
|
||||
target := rand.Intn(9000) + 1000
|
||||
if !hasDupes(target) {
|
||||
return target
|
||||
}
|
||||
}
|
||||
panic("Crap.")
|
||||
}
|
||||
|
||||
func hasDupes(num int) bool {
|
||||
digs := make([]bool, 10)
|
||||
for num > 0 {
|
||||
if digs[num%10] {
|
||||
return true
|
||||
}
|
||||
digs[num%10] = true
|
||||
num /= 10
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func askForNumber() (int, os.Error) {
|
||||
in := bufio.NewReader(os.Stdin)
|
||||
|
||||
for {
|
||||
Print("Give me a number: ")
|
||||
line, err := in.ReadString('\n')
|
||||
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
// Strip off the \n
|
||||
line = line[0 : len(line)-1]
|
||||
number, err := strconv.Atoi(line)
|
||||
|
||||
switch {
|
||||
case err != nil:
|
||||
Println("Give me a number fule!")
|
||||
case number < 1000:
|
||||
Println("Number not long enough")
|
||||
case number > 9999:
|
||||
Println("Number is to big")
|
||||
case hasDupes(number):
|
||||
Println("I said no dupes!")
|
||||
default:
|
||||
return number, nil
|
||||
}
|
||||
// Keep Asking
|
||||
}
|
||||
panic("Crap.")
|
||||
}
|
||||
|
||||
func bullsAndCows(number int, guess int) (bulls int, cows int) {
|
||||
bulls, cows = 0, 0
|
||||
numberstr := strconv.Itoa(number)
|
||||
guessstr := strconv.Itoa(guess)
|
||||
|
||||
for i := range guessstr {
|
||||
s := string(guessstr[i])
|
||||
switch {
|
||||
case guessstr[i] == numberstr[i]:
|
||||
bulls++
|
||||
case strings.Index(numberstr, s) >= 0:
|
||||
cows++
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
func main() {
|
||||
attempts := 0
|
||||
|
||||
Print("I choose a number made of 4 digits (from 1 to 9) without repetitions\n"
|
||||
"You enter a number of 4 digits, and I say you how many of them are\n"
|
||||
"in my secret number but in wrong position (cows or O), and how many\n"
|
||||
"are in the right position (bulls or X)\n\n")
|
||||
|
||||
target := generateTarget()
|
||||
|
||||
for {
|
||||
guess, err := askForNumber()
|
||||
attempts++
|
||||
|
||||
// Handle err
|
||||
if err != nil && err != os.EOF {
|
||||
Print(err)
|
||||
} else if err == os.EOF {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if target matches guess
|
||||
if guess == target {
|
||||
Printf("Congratulations you guessed correctly in %d attempts\n", attempts)
|
||||
return
|
||||
}
|
||||
|
||||
bulls, cows := bullsAndCows(target, guess)
|
||||
Printf("%d Bulls, %d Cows\n", bulls, cows)
|
||||
}
|
||||
|
||||
}
|
||||
49
Task/Bulls-and-cows/Kotlin/bulls-and-cows.kotlin
Normal file
49
Task/Bulls-and-cows/Kotlin/bulls-and-cows.kotlin
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// version 1.1.2
|
||||
|
||||
import java.util.Random
|
||||
|
||||
const val MAX_GUESSES = 20 // say
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val r = Random()
|
||||
var num: String
|
||||
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
|
||||
do {
|
||||
num = (1234 + r.nextInt(8643)).toString()
|
||||
} while ('0' in num || num.toSet().size < 4)
|
||||
|
||||
println("All guesses should have exactly 4 distinct digits excluding zero.")
|
||||
println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n")
|
||||
var guesses = 0
|
||||
while (true) {
|
||||
print("Enter your guess : ")
|
||||
val guess = readLine()!!
|
||||
if (guess == num) {
|
||||
println("You've won with ${++guesses} valid guesses!")
|
||||
return
|
||||
}
|
||||
val n = guess.toIntOrNull()
|
||||
if (n == null)
|
||||
println("Not a valid number")
|
||||
else if ('-' in guess || '+' in guess)
|
||||
println("Can't contain a sign")
|
||||
else if ('0' in guess)
|
||||
println("Can't contain zero")
|
||||
else if (guess.length != 4)
|
||||
println("Must have exactly 4 digits")
|
||||
else if (guess.toSet().size < 4)
|
||||
println("All digits must be distinct")
|
||||
else {
|
||||
var bulls = 0
|
||||
var cows = 0
|
||||
for ((i, c) in guess.withIndex()) {
|
||||
if (num[i] == c) bulls++
|
||||
else if (c in num) cows++
|
||||
}
|
||||
println("Your score for this guess: Bulls = $bulls Cows = $cows")
|
||||
guesses++
|
||||
if (guesses == MAX_GUESSES)
|
||||
println("You've now had $guesses valid guesses, the maximum allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +1,31 @@
|
|||
/*REXX pgm scores Bulls & Cows game with CBLFs (Carbon Based Life Forms)*/
|
||||
?=; do until length(?)==4 /*generate unique 4-digit number.*/
|
||||
r=random(1,9) /*change 1──►0 to allow a 0 dig*/
|
||||
if pos(r,?)\==0 then iterate /*don't allow a repeated digit. */
|
||||
?=? || r /*add random dig by concatenation*/
|
||||
end /*until length··· */ /* [↑] builds a unique 4-digit #*/
|
||||
/*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
|
||||
?=; do until length(?)==4 /*generate a unique four-digit number. */
|
||||
r=random(1, 9) /*change 1──► 0 to allow a zero digit*/
|
||||
if pos(r, ?)\==0 then iterate /*don't allow a repeated digit/numeral.*/
|
||||
?=? || r /*add random digit by concatenation. */
|
||||
end /*until length ···*/ /* [↑] builds a unique four-digit num.*/
|
||||
id= '──────── [Bulls & Cows] '
|
||||
do until bulls==4; say /*play until guessed or enters "QUIT".*/
|
||||
say id 'Please enter a 4-digit guess (with no zeroes) [or Quit]:'
|
||||
pull n; n=space(n,0); if abbrev('QUIT',n,1) then exit /*wants to quit ? */
|
||||
q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables. */
|
||||
|
||||
do until bulls==4; say /*play until guessed |enters QUIT*/
|
||||
say '───── [Bulls & Cows] Please enter a 4-digit guess (with no zeroes) [or Quit]:'
|
||||
pull n; n=space(n,0); if abbrev('QUIT',n,1) then exit /*Quit ?*/
|
||||
q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables.*/
|
||||
|
||||
do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate
|
||||
bulls=bulls+1 /*bump the bull count. */
|
||||
q=overlay(.,q,j) /*disallow this for a cow count. */
|
||||
end /*j*/ /* [↑] bull count───────────────*/
|
||||
|
||||
do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate
|
||||
cows=cows+1 /*bump the cow count. */
|
||||
q=translate(q,,_) /*this allows for multiple digits*/
|
||||
end /*k*/ /* [↑] cow count───────────────*/
|
||||
say
|
||||
if L\==0 & bulls\==4 then say "───── You got" bulls 'bull's(bulls) "and" cows 'cow's(cows)"."
|
||||
end /*until bulls···*/
|
||||
|
||||
say; say " ┌─────────────────────────────────────────┐"
|
||||
say " │ │"
|
||||
say " │ Congratulations, you've guessed it !! │"
|
||||
say " │ │"
|
||||
say " └─────────────────────────────────────────┘"; say
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*──────────────────────────────────S subroutine────────────────────────*/
|
||||
s: if arg(1)==1 then return ''; return 's' /*handles plurals.*/
|
||||
do j=1 for L; if substr(n,j,1)\==substr(q, j, 1) then iterate /*bull? */
|
||||
bulls=bulls+1; q=overlay(.,q,j) /*bump bull count; disallow for cow*/
|
||||
end /*j*/ /* [↑] bull count─────────────────*/
|
||||
/*cow ? */
|
||||
do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate
|
||||
cows=cows+1 ; q=translate(q, , _) /*bump cow count; allow mult digits*/
|
||||
end /*k*/ /* [↑] cow count─────────────────*/
|
||||
say; @='You got' bulls
|
||||
if L\==0 & bulls\==4 then say id @ 'bull's(bulls) "and" cows 'cow's(cows).
|
||||
end /*until bulls==4*/
|
||||
say
|
||||
say " ┌─────────────────────────────────────────┐"
|
||||
say " │ │"
|
||||
say " │ Congratulations, you've guessed it !! │"
|
||||
say " │ │"
|
||||
say " └─────────────────────────────────────────┘"; say
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
s: if arg(1)==1 then return ''; return 's' /*this function handles pluralization. */
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ for (var guesses = 1; true; guesses++) {
|
|||
var bulls = 0
|
||||
var cows = 0
|
||||
|
||||
var input = Sys.scanln("Input: ").chars \
|
||||
.unique \
|
||||
.grep {.~~/^[1-9]$/} \
|
||||
.map {.to_i}
|
||||
var input =
|
||||
read("Input: ", String).chars \
|
||||
.uniq \
|
||||
.grep(/^[1-9]$/) \
|
||||
.map{.to_n}
|
||||
|
||||
if (input.len != size) {
|
||||
warn "Invalid input!\n"
|
||||
|
|
@ -22,7 +23,7 @@ for (var guesses = 1; true; guesses++) {
|
|||
break
|
||||
}
|
||||
|
||||
num.range.each { |i|
|
||||
for i (^num) {
|
||||
if (num[i] == input[i]) {
|
||||
bulls++
|
||||
}
|
||||
|
|
|
|||
87
Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.smart
Normal file
87
Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.smart
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
'by rbytes, January 2017
|
||||
OPTION BASE 1
|
||||
P(" B U L L S A N D C O W S")!l
|
||||
P("A secret 4-digit number has been created, with")
|
||||
P("no repeats and no zeros. You must guess the number.")
|
||||
P("After each guess, you will be shown how many of your")
|
||||
P("digits are correct and in the matching location (bulls),")
|
||||
P("and how many are correct but in a different location (cows).")
|
||||
p("See how many tries it takes you to get the right answer.")
|
||||
' generate a 4-digit number with no repeats
|
||||
guesses = 0
|
||||
1 WHILE LEN(sec$) <4
|
||||
c$ =CHR$( INTEG(RND(1) *9) +49)
|
||||
IF INSTR(sec$, c$)=-1 THEN sec$&=c$
|
||||
ENDWHILE!l
|
||||
2 PRINT "Your guess: "
|
||||
INPUT "FOUR DIGITS": guess$!l
|
||||
IF guess$="" THEN ' check if entry is null
|
||||
P("Please enter something!")!l
|
||||
GOTO 2
|
||||
ENDIF
|
||||
P(guess$)!l
|
||||
IF LEN(guess$)<>4 THEN ' check if entry is exactly 4 characters
|
||||
P("Please enter exactly 4 digits.")!l
|
||||
GOTO 2
|
||||
ENDIF
|
||||
FOR t=1 TO 4 ' check if all characters are digits 1 - 9
|
||||
IF INSTR("123456789",MID$(guess$,t,1))=-1 THEN
|
||||
P("You have entered at least one illegal character")!l
|
||||
GOTO 2
|
||||
ENDIF
|
||||
NEXT t
|
||||
rep = check(guess$) ' check if any digits are repeated
|
||||
IF check.chk THEN
|
||||
P("Please enter a number with no repeated digits.")!l
|
||||
GOTO 2
|
||||
ENDIF
|
||||
|
||||
guesses+=1
|
||||
r$=score$(guess$,sec$)
|
||||
P(r$)!l
|
||||
|
||||
IF guess$=sec$ THEN
|
||||
P("W I N N E R ! ! !")!l
|
||||
IF guesses>1 THEN gs$="guesses!" ELSE gs$="guess!"
|
||||
P("You won after "&guesses&" "&gs$)
|
||||
P("Thanks for playing!")!l
|
||||
PAUSE 2
|
||||
P("A G A I N with a new secret number")!l
|
||||
guesses=0
|
||||
END IF
|
||||
GOTO 1
|
||||
END ' _____________________________________________________________
|
||||
|
||||
DEF P(p$) ' function to print a string
|
||||
PRINT p$
|
||||
END DEF
|
||||
|
||||
DEF L() ' function to print an empty line
|
||||
PRINT
|
||||
END DEF
|
||||
|
||||
DEF check(i$) ' check=0 if digit is not repeated, else=1
|
||||
chk=0
|
||||
FOR i =1 TO 3
|
||||
FOR j =i +1 TO 4
|
||||
IF MID$( i$, i, 1)=MID$( i$, j, 1) THEN chk =1
|
||||
NEXT j
|
||||
NEXT i
|
||||
END DEF
|
||||
|
||||
DEF score$(a$,b$) ' calculate the numbers of bulls & cows.
|
||||
bulls=0!cows=0
|
||||
FOR i = 1 TO 4
|
||||
c$ = MID$( a$, i, 1)
|
||||
IF MID$( b$, i, 1)=c$ THEN
|
||||
bulls+=1
|
||||
ELSE
|
||||
IF INSTR( b$, c$) <>-1 AND INSTR( b$, c$) <>i THEN
|
||||
cows+=1
|
||||
END IF
|
||||
END IF
|
||||
NEXT i
|
||||
r$ ="Bulls: "&STR$( bulls)& ", "& "Cows: " &STR$( cows)
|
||||
RETURN r$
|
||||
END DEF
|
||||
END
|
||||
12
Task/Bulls-and-cows/Zkl/bulls-and-cows.zkl
Normal file
12
Task/Bulls-and-cows/Zkl/bulls-and-cows.zkl
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
|
||||
abcd:=d.keys.shuffle();
|
||||
while(1){
|
||||
guess:=ask("4 digits: ")-" ,";
|
||||
if(guess.len()!=4 or guess.unique().len()!=4) continue;
|
||||
bulls:=abcd.zipWith('==,guess).sum(0);
|
||||
cows:=guess.split("").enumerate()
|
||||
.reduce('wrap(s,[(n,c)]){ s + (d.find(c,False) and abcd[n]!=c) },0);
|
||||
if(bulls==4) { println("You got it!"); break; }
|
||||
"%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println();
|
||||
}
|
||||
fcn s(n){ (n!=1) and "s" or "" }
|
||||
Loading…
Add table
Add a link
Reference in a new issue