new files
This commit is contained in:
parent
3af7344581
commit
86c034bb8b
1364 changed files with 21352 additions and 0 deletions
14
Task/Bulls-and-cows/0DESCRIPTION
Normal file
14
Task/Bulls-and-cows/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
[[wp:Bulls and Cows|This]] is an old game played with pencil and paper that was later implemented on computer.
|
||||
|
||||
The task is for the program to create a four digit random number from the digits 1 to 9, without duplication.
|
||||
The program should ask for guesses to this number, reject guesses that are malformed, then print the score for the guess.
|
||||
|
||||
The score is computed as:
|
||||
# The player wins if the guess is the same as the randomly chosen number, and the program ends.
|
||||
# A score of one '''bull''' is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
|
||||
# A score of one '''cow''' is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
|
||||
|
||||
;Cf,
|
||||
* [[Bulls and cows/Player]]
|
||||
* [[Guess the number]]
|
||||
* [[Guess the number/With Feedback]]
|
||||
2
Task/Bulls-and-cows/1META.yaml
Normal file
2
Task/Bulls-and-cows/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Games
|
||||
53
Task/Bulls-and-cows/Ada/bulls-and-cows.ada
Normal file
53
Task/Bulls-and-cows/Ada/bulls-and-cows.ada
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
with Ada.Numerics.Discrete_Random;
|
||||
|
||||
procedure Bulls_And_Cows is
|
||||
package Random_Natural is new Ada.Numerics.Discrete_Random (Natural);
|
||||
Number : String (1..4);
|
||||
begin
|
||||
declare -- Generation of number
|
||||
use Random_Natural;
|
||||
Digit : String := "123456789";
|
||||
Size : Positive := 9;
|
||||
Dice : Generator;
|
||||
Position : Natural;
|
||||
begin
|
||||
Reset (Dice);
|
||||
for I in Number'Range loop
|
||||
Position := Random (Dice) mod Size + 1;
|
||||
Number (I) := Digit (Position);
|
||||
Digit (Position..Size - 1) := Digit (Position + 1..Size);
|
||||
Size := Size - 1;
|
||||
end loop;
|
||||
end;
|
||||
loop -- Guessing loop
|
||||
Put ("Enter four digits:");
|
||||
declare
|
||||
Guess : String := Get_Line;
|
||||
Bulls : Natural := 0;
|
||||
Cows : Natural := 0;
|
||||
begin
|
||||
if Guess'Length /= 4 then
|
||||
raise Data_Error;
|
||||
end if;
|
||||
for I in Guess'Range loop
|
||||
for J in Number'Range loop
|
||||
if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then
|
||||
raise Data_Error;
|
||||
end if;
|
||||
if Number (I) = Guess (J) then
|
||||
if I = J then
|
||||
Bulls := Bulls + 1;
|
||||
else
|
||||
Cows := Cows + 1;
|
||||
end if;
|
||||
end if;
|
||||
end loop;
|
||||
end loop;
|
||||
exit when Bulls = 4;
|
||||
Put_Line (Integer'Image (Bulls) & " bulls," & Integer'Image (Cows) & " cows");
|
||||
exception
|
||||
when Data_Error => Put_Line ("You should enter four different digits 1..9");
|
||||
end;
|
||||
end loop;
|
||||
end Bulls_And_Cows;
|
||||
41
Task/Bulls-and-cows/BASIC/bulls-and-cows.bas
Normal file
41
Task/Bulls-and-cows/BASIC/bulls-and-cows.bas
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
DEFINT A-Z
|
||||
|
||||
DIM secret AS STRING
|
||||
DIM guess AS STRING
|
||||
DIM c AS STRING
|
||||
DIM bulls, cows, guesses, i
|
||||
|
||||
RANDOMIZE TIMER
|
||||
DO WHILE LEN(secret) < 4
|
||||
c = CHR$(INT(RND * 10) + 48)
|
||||
IF INSTR(secret, c) = 0 THEN secret = secret + c
|
||||
LOOP
|
||||
|
||||
guesses = 0
|
||||
DO
|
||||
INPUT "Guess a 4-digit number with no duplicate digits: "; guess
|
||||
guess = LTRIM$(RTRIM$(guess))
|
||||
IF LEN(guess) = 0 THEN EXIT DO
|
||||
|
||||
IF LEN(guess) <> 4 OR VAL(guess) = 0 THEN
|
||||
PRINT "** You should enter 4 numeric digits!"
|
||||
GOTO looper
|
||||
END IF
|
||||
|
||||
bulls = 0: cows = 0: guesses = guesses + 1
|
||||
FOR i = 1 TO 4
|
||||
c = MID$(secret, i, 1)
|
||||
IF MID$(guess, i, 1) = c THEN
|
||||
bulls = bulls + 1
|
||||
ELSEIF INSTR(guess, c) THEN
|
||||
cows = cows + 1
|
||||
END IF
|
||||
NEXT i
|
||||
PRINT bulls; " bulls, "; cows; " cows"
|
||||
|
||||
IF guess = secret THEN
|
||||
PRINT "You won after "; guesses; " guesses!"
|
||||
EXIT DO
|
||||
END IF
|
||||
looper:
|
||||
LOOP
|
||||
60
Task/Bulls-and-cows/C/bulls-and-cows-1.c
Normal file
60
Task/Bulls-and-cows/C/bulls-and-cows-1.c
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <curses.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_NUM_TRIES 72
|
||||
#define LINE_BEGIN 7
|
||||
#define LAST_LINE 18
|
||||
|
||||
int yp=LINE_BEGIN, xp=0;
|
||||
|
||||
char number[5];
|
||||
char guess[5];
|
||||
|
||||
#define MAX_STR 256
|
||||
void mvaddstrf(int y, int x, const char *fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
char buf[MAX_STR];
|
||||
|
||||
va_start(args, fmt);
|
||||
vsprintf(buf, fmt, args);
|
||||
move(y, x);
|
||||
clrtoeol();
|
||||
addstr(buf);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void ask_for_a_number()
|
||||
{
|
||||
int i=0;
|
||||
char symbols[] = "123456789";
|
||||
|
||||
move(5,0); clrtoeol();
|
||||
addstr("Enter four digits: ");
|
||||
while(i<4) {
|
||||
int c = getch();
|
||||
if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
|
||||
addch(c);
|
||||
symbols[c-'1'] = 0;
|
||||
guess[i++] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void choose_the_number()
|
||||
{
|
||||
int i=0, j;
|
||||
char symbols[] = "123456789";
|
||||
|
||||
while(i<4) {
|
||||
j = rand() % 9;
|
||||
if ( symbols[j] != 0 ) {
|
||||
number[i++] = symbols[j];
|
||||
symbols[j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
85
Task/Bulls-and-cows/C/bulls-and-cows-2.c
Normal file
85
Task/Bulls-and-cows/C/bulls-and-cows-2.c
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
bool take_it_or_not()
|
||||
{
|
||||
int i;
|
||||
int cows=0, bulls=0;
|
||||
|
||||
for(i=0; i < 4; i++) {
|
||||
if ( number[i] == guess[i] ) {
|
||||
bulls++;
|
||||
} else if ( strchr(number, guess[i]) != NULL ) {
|
||||
cows++;
|
||||
}
|
||||
}
|
||||
move(yp, xp);
|
||||
addstr(guess); addch(' ');
|
||||
if ( bulls == 4 ) { yp++; return true; }
|
||||
if ( (cows==0) && (bulls==0) ) addch('-');
|
||||
while( cows-- > 0 ) addstr("O");
|
||||
while( bulls-- > 0 ) addstr("X");
|
||||
yp++;
|
||||
if ( yp > LAST_LINE ) {
|
||||
yp = LINE_BEGIN;
|
||||
xp += 10;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ask_play_again()
|
||||
{
|
||||
int i;
|
||||
|
||||
while(yp-- >= LINE_BEGIN) {
|
||||
move(yp, 0); clrtoeol();
|
||||
}
|
||||
yp = LINE_BEGIN; xp = 0;
|
||||
|
||||
move(21,0); clrtoeol();
|
||||
addstr("Do you want to play again? [y/n]");
|
||||
while(true) {
|
||||
int a = getch();
|
||||
switch(a) {
|
||||
case 'y':
|
||||
case 'Y':
|
||||
return true;
|
||||
case 'n':
|
||||
case 'N':
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
bool bingo, again;
|
||||
int tries = 0;
|
||||
|
||||
initscr(); cbreak(); noecho();
|
||||
clear();
|
||||
|
||||
number[4] = guess[4] = 0;
|
||||
|
||||
mvaddstr(0,0, "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)");
|
||||
do {
|
||||
move(20,0); clrtoeol(); move(21, 0); clrtoeol();
|
||||
srand(time(NULL));
|
||||
choose_the_number();
|
||||
do {
|
||||
ask_for_a_number();
|
||||
bingo = take_it_or_not();
|
||||
tries++;
|
||||
} while(!bingo && (tries < MAX_NUM_TRIES));
|
||||
if ( bingo )
|
||||
mvaddstrf(20, 0, "You guessed %s correctly in %d attempts!", number, tries);
|
||||
else
|
||||
mvaddstrf(20,0, "Sorry, you had only %d tries...; the number was %s",
|
||||
MAX_NUM_TRIES, number);
|
||||
again = ask_play_again();
|
||||
tries = 0;
|
||||
} while(again);
|
||||
nocbreak(); echo(); endwin();
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
38
Task/Bulls-and-cows/Clojure/bulls-and-cows.clj
Normal file
38
Task/Bulls-and-cows/Clojure/bulls-and-cows.clj
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
(ns bulls-and-cows)
|
||||
|
||||
(defn bulls [guess solution]
|
||||
(count (filter true? (map = guess solution))))
|
||||
|
||||
(defn cows [guess solution]
|
||||
(-
|
||||
(count (filter (set solution) guess))
|
||||
(bulls guess solution)))
|
||||
|
||||
(defn valid-input?
|
||||
"checks whether the string is a 4 digit number with unique digits"
|
||||
[user-input]
|
||||
(if (re-seq #"^(?!.*(\d).*\1)\d{4}$" user-input)
|
||||
true
|
||||
false))
|
||||
|
||||
(defn enter-guess []
|
||||
"Let the user enter a guess. Verify the input. Repeat until valid.
|
||||
returns a list of digits enters by the user (# # # #)"
|
||||
(println "Enter your guess: ")
|
||||
(let [guess (read-line)]
|
||||
(if (valid-input? guess)
|
||||
(map #(Character/digit % 10) guess)
|
||||
(recur))))
|
||||
|
||||
(defn bulls-and-cows []
|
||||
"generate a random 4 digit number from the list of (1 ... 9): no repeating digits
|
||||
player tries to guess the number with bull and cows rules gameplay"
|
||||
(let [solution ( take 4 (shuffle (range 1 10)))]
|
||||
(println "lets play some bulls and cows!")
|
||||
(loop [guess (enter-guess)]
|
||||
(println (bulls guess solution) " bulls and " (cows guess solution) " cows.")
|
||||
(if (not= guess solution)
|
||||
(recur (enter-guess))
|
||||
(println "You have won!")))))
|
||||
|
||||
(bulls-and-cows)
|
||||
45
Task/Bulls-and-cows/Erlang/bulls-and-cows-1.erl
Normal file
45
Task/Bulls-and-cows/Erlang/bulls-and-cows-1.erl
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
-module(bulls_and_cows).
|
||||
-export([generate_secret/0, score_guess/2, play/0]).
|
||||
|
||||
% generate the secret code
|
||||
generate_secret() -> generate_secret([], 4, lists:seq(1,9)).
|
||||
generate_secret(Secret, 0, _) -> Secret;
|
||||
generate_secret(Secret, N, Digits) ->
|
||||
Next = lists:nth(random:uniform(length(Digits)), Digits),
|
||||
generate_secret(Secret ++ [Next], N - 1, Digits -- [Next]).
|
||||
|
||||
% evaluate a guess
|
||||
score_guess(Secret, Guess)
|
||||
when length(Secret) =/= length(Guess) -> throw(badguess);
|
||||
score_guess(Secret, Guess) ->
|
||||
Bulls = count_bulls(Secret,Guess),
|
||||
Cows = count_cows(Secret, Guess, Bulls),
|
||||
[Bulls, Cows].
|
||||
|
||||
% count bulls (exact matches)
|
||||
count_bulls(Secret, Guess) ->
|
||||
length(lists:filter(fun(I) -> lists:nth(I,Secret) == lists:nth(I,Guess) end,
|
||||
lists:seq(1, length(Secret)))).
|
||||
|
||||
% count cows (digits present but out of place)
|
||||
count_cows(Secret, Guess, Bulls) ->
|
||||
length(lists:filter(fun(I) -> lists:member(I, Guess) end, Secret)) - Bulls.
|
||||
|
||||
% play a game
|
||||
play() -> play_round(generate_secret()).
|
||||
|
||||
play_round(Secret) -> play_round(Secret, read_guess()).
|
||||
|
||||
play_round(Secret, Guess) ->
|
||||
play_round(Secret, Guess, score_guess(Secret,Guess)).
|
||||
|
||||
play_round(_, _, [4,0]) ->
|
||||
io:put_chars("Correct!\n");
|
||||
|
||||
play_round(Secret, _, Score) ->
|
||||
io:put_chars("\tbulls:"), io:write(hd(Score)), io:put_chars(", cows:"),
|
||||
io:write(hd(tl(Score))), io:put_chars("\n"), play_round(Secret).
|
||||
|
||||
read_guess() ->
|
||||
lists:map(fun(D)->D-48 end,
|
||||
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).
|
||||
3
Task/Bulls-and-cows/Erlang/bulls-and-cows-2.erl
Normal file
3
Task/Bulls-and-cows/Erlang/bulls-and-cows-2.erl
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/escript
|
||||
% Play Bulls and Cows
|
||||
main(_) -> random:seed(now()), bulls_and_cows:play().
|
||||
37
Task/Bulls-and-cows/Forth/bulls-and-cows.fth
Normal file
37
Task/Bulls-and-cows/Forth/bulls-and-cows.fth
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
include random.fs
|
||||
|
||||
create hidden 4 allot
|
||||
|
||||
: ok? ( str -- ? )
|
||||
dup 4 <> if 2drop false exit then
|
||||
1 9 lshift 1- -rot
|
||||
bounds do
|
||||
i c@ '1 -
|
||||
dup 0 9 within 0= if 2drop false leave then
|
||||
1 swap lshift over and
|
||||
dup 0= if nip leave then
|
||||
xor
|
||||
loop 0<> ;
|
||||
|
||||
: init
|
||||
begin
|
||||
hidden 4 bounds do 9 random '1 + i c! loop
|
||||
hidden 4 ok?
|
||||
until ;
|
||||
|
||||
: check? ( addr -- solved? )
|
||||
0
|
||||
4 0 do
|
||||
over i + c@
|
||||
4 0 do
|
||||
dup hidden i + c@ = if swap
|
||||
i j = if 8 else 1 then + swap
|
||||
then
|
||||
loop drop
|
||||
loop nip
|
||||
8 /mod tuck . ." bulls, " . ." cows"
|
||||
4 = ;
|
||||
|
||||
: guess: ( "1234" -- )
|
||||
bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
|
||||
drop check? if cr ." You guessed it!" then ;
|
||||
84
Task/Bulls-and-cows/Fortran/bulls-and-cows.f
Normal file
84
Task/Bulls-and-cows/Fortran/bulls-and-cows.f
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
module bac
|
||||
implicit none
|
||||
|
||||
contains
|
||||
|
||||
subroutine Gennum(n)
|
||||
integer, intent(out) :: n(4)
|
||||
integer :: i, j
|
||||
real :: r
|
||||
|
||||
call random_number(r)
|
||||
n(1) = int(r * 9.0) + 1
|
||||
i = 2
|
||||
|
||||
outer: do while (i <= 4)
|
||||
call random_number(r)
|
||||
n(i) = int(r * 9.0) + 1
|
||||
inner: do j = i-1 , 1, -1
|
||||
if (n(j) == n(i)) cycle outer
|
||||
end do inner
|
||||
i = i + 1
|
||||
end do outer
|
||||
|
||||
end subroutine Gennum
|
||||
|
||||
subroutine Score(n, guess, b, c)
|
||||
character(*), intent(in) :: guess
|
||||
integer, intent(in) :: n(0:3)
|
||||
integer, intent(out) :: b, c
|
||||
integer :: digit, i, j, ind
|
||||
|
||||
b = 0; c = 0
|
||||
do i = 1, 4
|
||||
read(guess(i:i), "(i1)") digit
|
||||
if (digit == n(i-1)) then
|
||||
b = b + 1
|
||||
else
|
||||
do j = i, i+2
|
||||
ind = mod(j, 4)
|
||||
if (digit == n(ind)) then
|
||||
c = c + 1
|
||||
exit
|
||||
end if
|
||||
end do
|
||||
end if
|
||||
end do
|
||||
|
||||
end subroutine Score
|
||||
|
||||
end module bac
|
||||
|
||||
program Bulls_and_Cows
|
||||
use bac
|
||||
implicit none
|
||||
|
||||
integer :: n(4)
|
||||
integer :: bulls=0, cows=0, tries=0
|
||||
character(4) :: guess
|
||||
|
||||
call random_seed
|
||||
call Gennum(n)
|
||||
|
||||
write(*,*) "I have selected a number made up of 4 digits (1-9) without repetitions."
|
||||
write(*,*) "You attempt to guess this number."
|
||||
write(*,*) "Every digit in your guess that is in the correct position scores 1 Bull"
|
||||
write(*,*) "Every digit in your guess that is in an incorrect position scores 1 Cow"
|
||||
write(*,*)
|
||||
|
||||
do while (bulls /= 4)
|
||||
write(*,*) "Enter a 4 digit number"
|
||||
read*, guess
|
||||
if (verify(guess, "123456789") /= 0) then
|
||||
write(*,*) "That is an invalid entry. Please try again."
|
||||
cycle
|
||||
end if
|
||||
tries = tries + 1
|
||||
call Score (n, guess, bulls, cows)
|
||||
write(*, "(a, i1, a, i1, a)") "You scored ", bulls, " bulls and ", cows, " cows"
|
||||
write(*,*)
|
||||
end do
|
||||
|
||||
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
|
||||
|
||||
end program Bulls_and_Cows
|
||||
68
Task/Bulls-and-cows/Go/bulls-and-cows-1.go
Normal file
68
Task/Bulls-and-cows/Go/bulls-and-cows-1.go
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
117
Task/Bulls-and-cows/Go/bulls-and-cows-2.go
Normal file
117
Task/Bulls-and-cows/Go/bulls-and-cows-2.go
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
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)
|
||||
}
|
||||
|
||||
}
|
||||
50
Task/Bulls-and-cows/Haskell/bulls-and-cows.hs
Normal file
50
Task/Bulls-and-cows/Haskell/bulls-and-cows.hs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import Data.List (partition, intersect, nub)
|
||||
import Control.Monad
|
||||
import System.Random (StdGen, getStdRandom, randomR)
|
||||
import Text.Printf
|
||||
|
||||
numberOfDigits = 4 :: Int
|
||||
|
||||
main = bullsAndCows
|
||||
|
||||
bullsAndCows :: IO ()
|
||||
bullsAndCows = do
|
||||
digits <- getStdRandom $ pick numberOfDigits ['1' .. '9']
|
||||
putStrLn "Guess away!"
|
||||
loop digits
|
||||
|
||||
where loop digits = do
|
||||
input <- getLine
|
||||
if okay input
|
||||
then
|
||||
let (bulls, cows) = score digits input in
|
||||
if bulls == numberOfDigits then
|
||||
putStrLn "You win!"
|
||||
else do
|
||||
printf "%d bulls, %d cows.\n" bulls cows
|
||||
loop digits
|
||||
else do
|
||||
putStrLn "Malformed guess; try again."
|
||||
loop digits
|
||||
|
||||
okay :: String -> Bool
|
||||
okay input =
|
||||
length input == numberOfDigits &&
|
||||
input == nub input &&
|
||||
all legalchar input
|
||||
where legalchar c = '1' <= c && c <= '9'
|
||||
|
||||
score :: String -> String -> (Int, Int)
|
||||
score secret guess = (length bulls, cows)
|
||||
where (bulls, nonbulls) = partition (uncurry (==)) $
|
||||
zip secret guess
|
||||
cows = length $ uncurry intersect $ unzip nonbulls
|
||||
|
||||
pick :: Int -> [a] -> StdGen -> ([a], StdGen)
|
||||
{- Randomly selects items from a list without replacement. -}
|
||||
pick n l g = f n l g (length l - 1) []
|
||||
where f 0 _ g _ ps = (ps, g)
|
||||
f n l g max ps =
|
||||
f (n - 1) (left ++ right) g' (max - 1) (picked : ps)
|
||||
where (i, g') = randomR (0, max) g
|
||||
(left, picked : right) = splitAt i l
|
||||
52
Task/Bulls-and-cows/Java/bulls-and-cows.java
Normal file
52
Task/Bulls-and-cows/Java/bulls-and-cows.java
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import java.util.InputMismatchException;
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class BullsAndCows{
|
||||
public static void main(String[] args){
|
||||
Random gen= new Random();
|
||||
int target= 0;
|
||||
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
|
||||
String targetStr = target +"";
|
||||
boolean guessed = false;
|
||||
Scanner input = new Scanner(System.in);
|
||||
int guesses = 0;
|
||||
do{
|
||||
int bulls = 0;
|
||||
int cows = 0;
|
||||
System.out.print("Guess a 4-digit number with no duplicate digits: ");
|
||||
int guess;
|
||||
try{
|
||||
guess = input.nextInt();
|
||||
if(hasDupes(guess) || guess < 1000) continue;
|
||||
}catch(InputMismatchException e){
|
||||
continue;
|
||||
}
|
||||
guesses++;
|
||||
String guessStr = guess + "";
|
||||
for(int i= 0;i < 4;i++){
|
||||
if(guessStr.charAt(i) == targetStr.charAt(i)){
|
||||
bulls++;
|
||||
}else if(targetStr.contains(guessStr.charAt(i)+"")){
|
||||
cows++;
|
||||
}
|
||||
}
|
||||
if(bulls == 4){
|
||||
guessed = true;
|
||||
}else{
|
||||
System.out.println(cows+" Cows and "+bulls+" Bulls.");
|
||||
}
|
||||
}while(!guessed);
|
||||
System.out.println("You won after "+guesses+" guesses!");
|
||||
}
|
||||
|
||||
public static boolean hasDupes(int num){
|
||||
boolean[] digs = new boolean[10];
|
||||
while(num > 0){
|
||||
if(digs[num%10]) return true;
|
||||
digs[num%10] = true;
|
||||
num/= 10;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
88
Task/Bulls-and-cows/JavaScript/bulls-and-cows.js
Normal file
88
Task/Bulls-and-cows/JavaScript/bulls-and-cows.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
#!/usr/bin/env js
|
||||
|
||||
function main() {
|
||||
var len = 4;
|
||||
playBullsAndCows(len);
|
||||
}
|
||||
|
||||
function playBullsAndCows(len) {
|
||||
var num = pickNum(len);
|
||||
// print('The secret number is:\n ' + num.join('\n '));
|
||||
showInstructions(len);
|
||||
var nGuesses = 0;
|
||||
while (true) {
|
||||
nGuesses++;
|
||||
var guess = getGuess(nGuesses, len);
|
||||
var census = countBovine(num, guess);
|
||||
showScore(census.bulls, census.cows);
|
||||
if (census.bulls == len) {
|
||||
showFinalResult(nGuesses);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showScore(nBulls, nCows) {
|
||||
print(' Bulls: ' + nBulls + ', cows: ' + nCows);
|
||||
}
|
||||
|
||||
function showFinalResult(guesses) {
|
||||
print('You win!!! Guesses needed: ' + guesses);
|
||||
}
|
||||
|
||||
function countBovine(num, guess) {
|
||||
var count = {bulls:0, cows:0};
|
||||
var g = guess.join('');
|
||||
for (var i = 0; i < num.length; i++) {
|
||||
var digPresent = g.search(num[i]) != -1;
|
||||
if (num[i] == guess[i]) count.bulls++;
|
||||
else if (digPresent) count.cows++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function getGuess(nGuesses, len) {
|
||||
while (true) {
|
||||
putstr('Your guess #' + nGuesses + ': ');
|
||||
var guess = readline();
|
||||
guess = String(parseInt(guess)).split('');
|
||||
if (guess.length != len) {
|
||||
print(' You must enter a ' + len + ' digit number.');
|
||||
continue;
|
||||
}
|
||||
if (hasDups(guess)) {
|
||||
print(' No digits can be duplicated.');
|
||||
continue;
|
||||
}
|
||||
return guess;
|
||||
}
|
||||
}
|
||||
|
||||
function hasDups(ary) {
|
||||
var t = ary.concat().sort();
|
||||
for (var i = 1; i < t.length; i++) {
|
||||
if (t[i] == t[i-1]) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function showInstructions(len) {
|
||||
print();
|
||||
print('Bulls and Cows Game');
|
||||
print('-------------------');
|
||||
print(' You must guess the ' + len + ' digit number I am thinking of.');
|
||||
print(' The number is composed of the digits 1-9.');
|
||||
print(' No digit appears more than once.');
|
||||
print(' After each of your guesses, I will tell you:');
|
||||
print(' The number of bulls (digits in right place)');
|
||||
print(' The number of cows (correct digits, but in the wrong place)');
|
||||
print();
|
||||
}
|
||||
|
||||
function pickNum(len) {
|
||||
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
nums.sort(function(){return Math.random() - 0.5});
|
||||
return nums.slice(0, len);
|
||||
}
|
||||
|
||||
main();
|
||||
101
Task/Bulls-and-cows/Lua/bulls-and-cows.lua
Normal file
101
Task/Bulls-and-cows/Lua/bulls-and-cows.lua
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
function ShuffleArray(array)
|
||||
for i=1,#array-1 do
|
||||
local t = math.random(i, #array)
|
||||
array[i], array[t] = array[t], array[i]
|
||||
end
|
||||
end
|
||||
|
||||
function GenerateNumber()
|
||||
local digits = {1,2,3,4,5,6,7,8,9}
|
||||
|
||||
ShuffleArray(digits)
|
||||
|
||||
return digits[1] * 1000 +
|
||||
digits[2] * 100 +
|
||||
digits[3] * 10 +
|
||||
digits[4]
|
||||
end
|
||||
|
||||
function IsMalformed(input)
|
||||
local malformed = false
|
||||
|
||||
if #input == 4 then
|
||||
local already_used = {}
|
||||
for i=1,4 do
|
||||
local digit = input:byte(i) - string.byte('0')
|
||||
if digit < 1 or digit > 9 or already_used[digit] then
|
||||
malformed = true
|
||||
break
|
||||
end
|
||||
already_used[digit] = true
|
||||
end
|
||||
else
|
||||
malformed = true
|
||||
end
|
||||
|
||||
return malformed
|
||||
end
|
||||
|
||||
math.randomseed(os.time())
|
||||
math.randomseed(math.random(2^31-1)) -- since os.time() only returns seconds
|
||||
|
||||
print("\nWelcome to Bulls and Cows!")
|
||||
print("")
|
||||
print("The object of this game is to guess the random 4-digit number that the")
|
||||
print("computer has chosen. The number is generated using only the digits 1-9,")
|
||||
print("with no repeated digits. Each time you enter a guess, you will score one")
|
||||
print("\"bull\" for each digit in your guess that matches the corresponding digit")
|
||||
print("in the computer-generated number, and you will score one \"cow\" for each")
|
||||
print("digit in your guess that appears in the computer-generated number, but is")
|
||||
print("in the wrong position. Use this information to refine your guesses. When")
|
||||
print("you guess the correct number, you win.");
|
||||
print("")
|
||||
|
||||
quit = false
|
||||
|
||||
repeat
|
||||
magic_number = GenerateNumber()
|
||||
magic_string = tostring(magic_number) -- Easier to do scoring with a string
|
||||
repeat
|
||||
io.write("\nEnter your guess (or 'Q' to quit): ")
|
||||
user_input = io.read()
|
||||
if user_input == 'Q' or user_input == 'q' then
|
||||
quit = true
|
||||
break
|
||||
end
|
||||
|
||||
if not IsMalformed(user_input) then
|
||||
if user_input == magic_string then
|
||||
print("YOU WIN!!!")
|
||||
else
|
||||
local bulls, cows = 0, 0
|
||||
for i=1,#user_input do
|
||||
local find_result = magic_string:find(user_input:sub(i,i))
|
||||
|
||||
if find_result and find_result == i then
|
||||
bulls = bulls + 1
|
||||
elseif find_result then
|
||||
cows = cows + 1
|
||||
end
|
||||
end
|
||||
print(string.format("You scored %d bulls, %d cows", bulls, cows))
|
||||
end
|
||||
else
|
||||
print("Malformed input. You must enter a 4-digit number with")
|
||||
print("no repeated digits, using only the digits 1-9.")
|
||||
end
|
||||
|
||||
until user_input == magic_string
|
||||
|
||||
if not quit then
|
||||
io.write("\nPress <Enter> to play again or 'Q' to quit: ")
|
||||
user_input = io.read()
|
||||
if user_input == 'Q' or user_input == 'q' then
|
||||
quit = true
|
||||
end
|
||||
end
|
||||
|
||||
if quit then
|
||||
print("\nGoodbye!")
|
||||
end
|
||||
until quit
|
||||
40
Task/Bulls-and-cows/PHP/bulls-and-cows.php
Normal file
40
Task/Bulls-and-cows/PHP/bulls-and-cows.php
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
$size = 4;
|
||||
|
||||
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
|
||||
|
||||
echo "I've chosen a number from $size unique digits from 1 to 9; you need
|
||||
to input $size unique digits to guess my number\n";
|
||||
|
||||
for ($guesses = 1; ; $guesses++) {
|
||||
while (true) {
|
||||
echo "\nNext guess [$guesses]: ";
|
||||
$guess = rtrim(fgets(STDIN));
|
||||
if (!checkguess($guess))
|
||||
echo "$size digits, no repetition, no 0... retry\n";
|
||||
else
|
||||
break;
|
||||
}
|
||||
if ($guess == $chosen) {
|
||||
echo "You did it in $guesses attempts!\n";
|
||||
break;
|
||||
} else {
|
||||
$bulls = 0;
|
||||
$cows = 0;
|
||||
foreach (range(0, $size-1) as $i) {
|
||||
if ($guess[$i] == $chosen[$i])
|
||||
$bulls++;
|
||||
else if (strpos($chosen, $guess[$i]) !== FALSE)
|
||||
$cows++;
|
||||
}
|
||||
echo "$cows cows, $bulls bulls\n";
|
||||
}
|
||||
}
|
||||
|
||||
function checkguess($g)
|
||||
{
|
||||
global $size;
|
||||
return count(array_unique(str_split($g))) == $size &&
|
||||
preg_match("/^[1-9]{{$size}}$/", $g);
|
||||
}
|
||||
?>
|
||||
39
Task/Bulls-and-cows/Perl/bulls-and-cows.pl
Normal file
39
Task/Bulls-and-cows/Perl/bulls-and-cows.pl
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
use Data::Random qw(rand_set);
|
||||
use List::MoreUtils qw(uniq);
|
||||
|
||||
my $size = 4;
|
||||
my $chosen = join "", rand_set set => ["1".."9"], size => $size;
|
||||
|
||||
print "I've chosen a number from $size unique digits from 1 to 9; you need
|
||||
to input $size unique digits to guess my number\n";
|
||||
|
||||
for ( my $guesses = 1; ; $guesses++ ) {
|
||||
my $guess;
|
||||
while (1) {
|
||||
print "\nNext guess [$guesses]: ";
|
||||
$guess = <STDIN>;
|
||||
chomp $guess;
|
||||
checkguess($guess) and last;
|
||||
print "$size digits, no repetition, no 0... retry\n";
|
||||
}
|
||||
if ( $guess eq $chosen ) {
|
||||
print "You did it in $guesses attempts!\n";
|
||||
last;
|
||||
}
|
||||
my $bulls = 0;
|
||||
my $cows = 0;
|
||||
for my $i (0 .. $size-1) {
|
||||
if ( substr($guess, $i, 1) eq substr($chosen, $i, 1) ) {
|
||||
$bulls++;
|
||||
} elsif ( index($chosen, substr($guess, $i, 1)) >= 0 ) {
|
||||
$cows++;
|
||||
}
|
||||
}
|
||||
print "$cows cows, $bulls bulls\n";
|
||||
}
|
||||
|
||||
sub checkguess
|
||||
{
|
||||
my $g = shift;
|
||||
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
|
||||
}
|
||||
20
Task/Bulls-and-cows/PicoLisp/bulls-and-cows.l
Normal file
20
Task/Bulls-and-cows/PicoLisp/bulls-and-cows.l
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
(de ok? (N)
|
||||
(let D (mapcar 'format (chop N))
|
||||
(and (num? N)
|
||||
(not (member 0 D))
|
||||
(= 4 (length D))
|
||||
(= D (uniq D))
|
||||
D )) )
|
||||
|
||||
(de init-cows ()
|
||||
(until (setq *Hidden (ok? (rand 1234 9876)))) )
|
||||
|
||||
(de guess (N)
|
||||
(let D (ok? N)
|
||||
(if D
|
||||
(let Bulls (cnt '= D *Hidden)
|
||||
(if (= 4 Bulls)
|
||||
" You guessed it!"
|
||||
(let Cows (- (cnt '((N) (member N *Hidden)) D) Bulls)
|
||||
(pack Bulls " bulls, " Cows " cows") ) ) )
|
||||
" Bad guess! (4 unique digits, 1-9)" ) ) )
|
||||
56
Task/Bulls-and-cows/Prolog/bulls-and-cows.pro
Normal file
56
Task/Bulls-and-cows/Prolog/bulls-and-cows.pro
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
:- use_module(library(lambda)).
|
||||
:- use_module(library(clpfd)).
|
||||
|
||||
% Parameters of the server
|
||||
|
||||
% length of the guess
|
||||
proposition(4).
|
||||
|
||||
% Numbers of digits
|
||||
% 0 -> 8
|
||||
digits(8).
|
||||
|
||||
|
||||
bulls_and_cows_server :-
|
||||
proposition(LenGuess),
|
||||
length(Solution, LenGuess),
|
||||
choose(Solution),
|
||||
repeat,
|
||||
write('Your guess : '),
|
||||
read(Guess),
|
||||
( study(Solution, Guess, Bulls, Cows)
|
||||
-> format('Bulls : ~w Cows : ~w~n', [Bulls, Cows]),
|
||||
Bulls = LenGuess
|
||||
; digits(Digits), Max is Digits + 1,
|
||||
format('Guess must be of ~w digits between 1 and ~w~n',
|
||||
[LenGuess, Max]),
|
||||
fail).
|
||||
|
||||
choose(Solution) :-
|
||||
digits(Digits),
|
||||
Max is Digits + 1,
|
||||
repeat,
|
||||
maplist(\X^(X is random(Max) + 1), Solution),
|
||||
all_distinct(Solution),
|
||||
!.
|
||||
|
||||
study(Solution, Guess, Bulls, Cows) :-
|
||||
proposition(LenGuess),
|
||||
digits(Digits),
|
||||
|
||||
% compute the transformation 1234 => [1,2,3,4]
|
||||
atom_chars(Guess, Chars),
|
||||
maplist(\X^Y^(atom_number(X, Y)), Chars, Ms),
|
||||
|
||||
% check that the guess is well formed
|
||||
length(Ms, LenGuess),
|
||||
maplist(\X^(X > 0, X =< Digits+1), Ms),
|
||||
|
||||
% compute the digit in good place
|
||||
foldl(\X^Y^V0^V1^((X = Y->V1 is V0+1; V1 = V0)),Solution, Ms, 0, Bulls),
|
||||
|
||||
% compute the digits in bad place
|
||||
foldl(\Y1^V2^V3^(foldl(\X2^Z2^Z3^(X2 = Y1 -> Z3 is Z2+1; Z3 = Z2), Ms, 0, TT1),
|
||||
V3 is V2+ TT1),
|
||||
Solution, 0, TT),
|
||||
Cows is TT - Bulls.
|
||||
33
Task/Bulls-and-cows/Python/bulls-and-cows.py
Normal file
33
Task/Bulls-and-cows/Python/bulls-and-cows.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
'''
|
||||
Bulls and cows. A game pre-dating, and similar to, Mastermind.
|
||||
'''
|
||||
|
||||
import random
|
||||
|
||||
digits = '123456789'
|
||||
size = 4
|
||||
chosen = ''.join(random.sample(digits,size))
|
||||
#print chosen # Debug
|
||||
print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order.
|
||||
You need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size)
|
||||
guesses = 0
|
||||
while True:
|
||||
guesses += 1
|
||||
while True:
|
||||
# get a good guess
|
||||
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
|
||||
if len(guess) == size and \
|
||||
all(char in digits for char in guess) \
|
||||
and len(set(guess)) == size:
|
||||
break
|
||||
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
|
||||
if guess == chosen:
|
||||
print '\nCongratulations you guessed correctly in',guesses,'attempts'
|
||||
break
|
||||
bulls = cows = 0
|
||||
for i in range(size):
|
||||
if guess[i] == chosen[i]:
|
||||
bulls += 1
|
||||
elif guess[i] in chosen:
|
||||
cows += 1
|
||||
print ' %i Bulls\n %i Cows' % (bulls, cows)
|
||||
19
Task/Bulls-and-cows/R/bulls-and-cows.r
Normal file
19
Task/Bulls-and-cows/R/bulls-and-cows.r
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
target <- sample(1:9,4)
|
||||
bulls <- 0
|
||||
cows <- 0
|
||||
attempts <- 0
|
||||
while (bulls != 4)
|
||||
{
|
||||
input <- readline("Guess a 4-digit number with no duplicate digits or 0s: ")
|
||||
if (nchar(input) == 4)
|
||||
{
|
||||
input <- as.integer(strsplit(input,"")[[1]])
|
||||
if ((sum(is.na(input)+sum(input==0))>=1) | (length(table(input)) != 4)) {print("Malformed input!")} else {
|
||||
bulls <- sum(input == target)
|
||||
cows <- sum(input %in% target)-bulls
|
||||
cat("\n",bulls," Bull(s) and ",cows, " Cow(s)\n")
|
||||
attempts <- attempts + 1
|
||||
}
|
||||
} else {print("Malformed input!")}
|
||||
}
|
||||
print(paste("You won in",attempts,"attempt(s)!"))
|
||||
43
Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx
Normal file
43
Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/*REXX pgm interactively plays a game of "Bulls & Cows" with CBLs. */
|
||||
/* [CBLs = Carbon Based Lifeforms.] */
|
||||
/* */
|
||||
/* This game is also known as: Cows and Bulls */
|
||||
/* Pigs and Bulls */
|
||||
/* Bulls and Cleots */
|
||||
/* MasterMind (or Master Mind) */
|
||||
/*══════════════════════════════════════════════════════════════════════*/
|
||||
?=''; 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
|
||||
end /*until*/
|
||||
|
||||
prompt='[Bulls & Cows game] ', /*build the prompt text string. */
|
||||
"Please enter a 4-digit guess (with no zeroes) [or Quit]:"
|
||||
|
||||
do until bulls==4 /*play until guessed |enters QUIT*/
|
||||
say prompt; pull n; n=space(n,0); if n=='' then iterate
|
||||
if abbrev('QUIT',n,1) then exit /*Does the user want to quit now?*/
|
||||
g=?; L=length(n); bulls=0; cows=0
|
||||
/*bull count─────────────────────*/
|
||||
do j=1 for L; if substr(n,j,1)\==substr(g,j,1) then iterate
|
||||
bulls=bulls+1 /*bump the bull count. */
|
||||
g=overlay(' ',g,j) /*disallow this for a cow count. */
|
||||
end /*j*/
|
||||
/*cow count─────────────────────*/
|
||||
do k=1 for L; x=substr(n,k,1); if pos(x,g)==0 then iterate
|
||||
cows=cows+1 /*bump the cow count. */
|
||||
g=translate(g,,x) /*this allows for rule variants. */
|
||||
end /*k*/
|
||||
|
||||
if bulls\==4 then say "───── You got" bulls '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
|
||||
/*──────────────────────────────────S subroutine────────────────────────*/
|
||||
s: if arg(1)==1 then return ''; return 's'
|
||||
101
Task/Bulls-and-cows/REXX/bulls-and-cows-2.rexx
Normal file
101
Task/Bulls-and-cows/REXX/bulls-and-cows-2.rexx
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
/*REXX program to play the game of "Bulls & Cows". *******************
|
||||
* Changes from Version 1:
|
||||
* ?= -> qq='' (righthandside mandatory and I never use ? as symbol -
|
||||
* although it is available on all Rexxes)
|
||||
* implemented singular/plural distinction differently
|
||||
* change getRand to avoid invalid digit rejection
|
||||
* check user's input for multiple digits
|
||||
* add feature MM to ease guessing (MM=Mastermind - a similar game)
|
||||
* add feature ? to see the solution (for the impatient player)
|
||||
* program runs as is on ooRexx and on TSO (after changing | to !)
|
||||
* Made source and output more compact
|
||||
* formatted source 'my way' 2 July 2012 Walter Pachl
|
||||
**********************************************************************/
|
||||
ask='<Bulls & Cows game> Please enter a four-digit guess (or QUIT):'
|
||||
|
||||
b.='bulls'; b.1='bull'
|
||||
c.='cows'; c.1='cow'
|
||||
qq=getRand()
|
||||
mm=0
|
||||
Do Forever
|
||||
If get_guess()==qq Then leave
|
||||
Call scorer
|
||||
Say "You got" bulls b.bulls "and" cows c.cows"."
|
||||
If mm Then
|
||||
Say mms
|
||||
End /*forever*/
|
||||
Say " *******************************************"
|
||||
Say " * *"
|
||||
Say " * Congratulations, you've guessed it !! *"
|
||||
Say " * *"
|
||||
Say " *******************************************"
|
||||
Exit
|
||||
|
||||
get_guess: /*get a guess from the guesser. */
|
||||
|
||||
do forever
|
||||
Say ask
|
||||
Parse Pull guessi
|
||||
guess=translate(guessi)
|
||||
bc=verify(guess,987654321)
|
||||
Select
|
||||
When guess='?' Then Say qq 'is the correct sequence'
|
||||
When guess='QUIT' Then Exit
|
||||
When guess='MM' Then Do
|
||||
Say 'Mastermind output enabled'
|
||||
mm=1
|
||||
End
|
||||
When guess='' Then Call ser 'no argument specified.'
|
||||
When words(guess)>1 Then Call ser 'too many arguments specified.'
|
||||
When verify(0,guess)=0 Then Call ser 'illegal digit: 0'
|
||||
When bc>0 Then Call ser 'illegal character:' substr(guessi,bc,1)
|
||||
When length(guess)<4 Then Call ser 'not enough digits'
|
||||
When length(guess)>4 Then Call ser 'too many digits'
|
||||
When dups(guess) Then Call ser '4 DIFFERENT digits, please'
|
||||
Otherwise Do
|
||||
/********** Say guess ************/
|
||||
Return guess
|
||||
End
|
||||
End
|
||||
End
|
||||
|
||||
getRand:
|
||||
digits='123456789'
|
||||
qq=''
|
||||
Do i=1 To 4
|
||||
d=random(1,length(digits))
|
||||
d=substr(digits,d,1)
|
||||
qq=qq||d
|
||||
digits=space(translate(digits,' ',d),0)
|
||||
/************ Say qq digits ************/
|
||||
End
|
||||
Return qq
|
||||
|
||||
scorer: g=qq
|
||||
mms='----'
|
||||
bulls=0
|
||||
Do j=1 for 4
|
||||
If substr(guess,j,1)=substr(qq,j,1) Then Do
|
||||
bulls=bulls+1
|
||||
guess=overlay(' ',guess,j)
|
||||
mms=overlay('+',mms,j)
|
||||
End
|
||||
End
|
||||
cows=0
|
||||
Do j=1 To 4
|
||||
If pos(substr(guess,j,1),qq)>0 Then Do
|
||||
cows=cows+1
|
||||
mms=overlay('.',mms,j)
|
||||
End
|
||||
End
|
||||
Return
|
||||
|
||||
dups: Procedure
|
||||
Parse Arg s
|
||||
Do i=1 To 3
|
||||
If pos(substr(s,i,1),substr(s,i+1))>0 Then
|
||||
Return 1
|
||||
End
|
||||
Return 0
|
||||
|
||||
ser: Say '*** error ***' arg(1); Return
|
||||
44
Task/Bulls-and-cows/Ruby/bulls-and-cows.rb
Normal file
44
Task/Bulls-and-cows/Ruby/bulls-and-cows.rb
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
def generate_word(len)
|
||||
([1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle)[0,len].join("")
|
||||
end
|
||||
|
||||
def get_guess(len)
|
||||
while true
|
||||
print "Enter a guess: "
|
||||
guess = gets.strip
|
||||
err = case
|
||||
when guess.match(/\D/) : "digits only"
|
||||
when guess.length != len : "exactly #{len} digits"
|
||||
when guess.split("").uniq.length != len: "digits must be unique "
|
||||
else nil
|
||||
end
|
||||
break if err.nil?
|
||||
puts "the word must be #{len} unique digits between 1 and 9 (#{err}). Try again."
|
||||
end
|
||||
guess
|
||||
end
|
||||
|
||||
def score(word, guess)
|
||||
bulls = cows = 0
|
||||
guess.bytes.each_with_index do |byte, idx|
|
||||
if word[idx] == byte
|
||||
bulls += 1
|
||||
elsif word.include? byte
|
||||
cows += 1
|
||||
end
|
||||
end
|
||||
[bulls, cows]
|
||||
end
|
||||
|
||||
srand
|
||||
word_length = 4
|
||||
puts "I have chosen a number with #{word_length} unique digits from 1 to 9."
|
||||
word = generate_word(word_length)
|
||||
count = 0
|
||||
while true
|
||||
guess = get_guess(word_length)
|
||||
count += 1
|
||||
break if word == guess
|
||||
puts "that guess has %d bulls and %d cows" % score(word, guess)
|
||||
end
|
||||
puts "you guessed correctly in #{count} tries."
|
||||
42
Task/Bulls-and-cows/Scala/bulls-and-cows.scala
Normal file
42
Task/Bulls-and-cows/Scala/bulls-and-cows.scala
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import scala.util.Random
|
||||
|
||||
object BullCow {
|
||||
def main(args: Array[String]): Unit = {
|
||||
val number=chooseNumber
|
||||
var guessed=false
|
||||
var guesses=0
|
||||
|
||||
while(!guessed){
|
||||
Console.print("Guess a 4-digit number with no duplicate digits: ")
|
||||
val input=Console.readInt
|
||||
val digits=input.toString.map(_.asDigit).toList
|
||||
if(input>=1111 && input<=9999 && !hasDups(digits)){
|
||||
guesses+=1
|
||||
var bulls, cows=0
|
||||
for(i <- 0 to 3)
|
||||
if(number(i)==digits(i))
|
||||
bulls+=1
|
||||
else if(number.contains(digits(i)))
|
||||
cows+=1
|
||||
|
||||
if(bulls==4)
|
||||
guessed=true
|
||||
else
|
||||
println("%d Cows and %d Bulls.".format(cows, bulls))
|
||||
}
|
||||
}
|
||||
println("You won after "+guesses+" guesses!");
|
||||
}
|
||||
|
||||
def chooseNumber={
|
||||
var digits=List[Int]()
|
||||
while(digits.size<4){
|
||||
val d=Random.nextInt(9)+1
|
||||
if (!digits.contains(d))
|
||||
digits=digits:+d
|
||||
}
|
||||
digits
|
||||
}
|
||||
|
||||
def hasDups(input:List[Int])=input.size!=input.distinct.size
|
||||
}
|
||||
65
Task/Bulls-and-cows/Scheme/bulls-and-cows.ss
Normal file
65
Task/Bulls-and-cows/Scheme/bulls-and-cows.ss
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
;generate a random non-repeating list of 4 digits, 1-9 inclusive
|
||||
(define (get-num)
|
||||
(define (gen lst)
|
||||
(if (= (length lst) 4) lst
|
||||
(let ((digit (+ (random 9) 1)))
|
||||
(if (member digit lst) ;make sure the new digit isn't in the
|
||||
;list
|
||||
(gen lst)
|
||||
(gen (cons digit lst))))))
|
||||
(string->list (apply string-append (map number->string (gen '())))))
|
||||
|
||||
;is g a valid guess (that is, non-repeating, four digits 1-9
|
||||
;inclusive?)
|
||||
(define (valid-guess? g)
|
||||
(let ((g-num (string->number (apply string g))))
|
||||
;does the same digit appear twice in lst?
|
||||
(define (repeats? lst)
|
||||
(cond ((null? lst) #f)
|
||||
((member (car lst) (cdr lst)) #t)
|
||||
(else (repeats? (cdr lst)))))
|
||||
(and g-num
|
||||
(> g-num 1233)
|
||||
(< g-num 9877)
|
||||
(not (repeats? g)))))
|
||||
|
||||
;return '(cows bulls) for the given guess
|
||||
(define (score answer guess)
|
||||
;total cows + bulls
|
||||
(define (cows&bulls a g)
|
||||
(cond ((null? a) 0)
|
||||
((member (car a) g) (+ 1 (cows&bulls (cdr a) g)))
|
||||
(else (cows&bulls (cdr a) g))))
|
||||
;bulls only
|
||||
(define (bulls a g)
|
||||
(cond ((null? a) 0)
|
||||
((equal? (car a) (car g)) (+ 1 (bulls (cdr a) (cdr g))))
|
||||
(else (bulls (cdr a) (cdr g)))))
|
||||
(list (- (cows&bulls answer guess) (bulls answer guess)) (bulls answer guess)))
|
||||
|
||||
;play the game
|
||||
(define (bull-cow answer)
|
||||
;get the user's guess as a list
|
||||
(define (get-guess)
|
||||
(let ((e (read)))
|
||||
(if (number? e)
|
||||
(string->list (number->string e))
|
||||
(string->list (symbol->string e)))))
|
||||
(display "Enter a guess: ")
|
||||
(let ((guess (get-guess)))
|
||||
(if (valid-guess? guess)
|
||||
(let ((bulls (cadr (score answer guess)))
|
||||
(cows (car (score answer guess))))
|
||||
(if (= bulls 4)
|
||||
(display "You win!\n")
|
||||
(begin
|
||||
(display bulls)
|
||||
(display " bulls, ")
|
||||
(display cows)
|
||||
(display " cows.\n")
|
||||
(bull-cow answer))))
|
||||
(begin
|
||||
(display "Invalid guess.\n")
|
||||
(bull-cow answer)))))
|
||||
|
||||
(bull-cow (get-num))
|
||||
58
Task/Bulls-and-cows/Smalltalk/bulls-and-cows.st
Normal file
58
Task/Bulls-and-cows/Smalltalk/bulls-and-cows.st
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
Object subclass: BullsCows [
|
||||
|number|
|
||||
BullsCows class >> new: secretNum [ |i|
|
||||
i := self basicNew.
|
||||
(self isValid: secretNum)
|
||||
ifFalse: [ SystemExceptions.InvalidArgument
|
||||
signalOn: secretNum
|
||||
reason: 'You need 4 unique digits from 1 to 9' ].
|
||||
i setNumber: secretNum.
|
||||
^ i
|
||||
]
|
||||
BullsCows class >> new [ |b| b := Set new.
|
||||
[ b size < 4 ]
|
||||
whileTrue: [ b add: ((Random between: 1 and: 9) displayString first) ].
|
||||
^ self new: (b asString)
|
||||
]
|
||||
BullsCows class >> isValid: num [
|
||||
^ (num asSet size = 4) & ((num asSet includes: $0) not)
|
||||
]
|
||||
setNumber: num [ number := num ]
|
||||
check: guess [ |bc| bc := Bag new.
|
||||
1 to: 4 do: [ :i |
|
||||
(number at: i) = (guess at: i)
|
||||
ifTrue: [ bc add: 'bulls' ]
|
||||
ifFalse: [
|
||||
(number includes: (guess at: i))
|
||||
ifTrue: [ bc add: 'cows' ]
|
||||
]
|
||||
].
|
||||
^ bc
|
||||
]
|
||||
].
|
||||
|
||||
'Guess the 4-digits number (digits from 1 to 9, no repetition)' displayNl.
|
||||
|
||||
|guessMe d r tries|
|
||||
[
|
||||
tries := 0.
|
||||
guessMe := BullsCows new.
|
||||
[
|
||||
[
|
||||
'Write 4 digits: ' display.
|
||||
d := stdin nextLine.
|
||||
(BullsCows isValid: d)
|
||||
] whileFalse: [
|
||||
'Insert 4 digits, no repetition, exclude the digit 0' displayNl
|
||||
].
|
||||
r := guessMe check: d.
|
||||
tries := tries + 1.
|
||||
(r occurrencesOf: 'bulls') = 4
|
||||
] whileFalse: [
|
||||
('%1 cows, %2 bulls' % { r occurrencesOf: 'cows'. r occurrencesOf: 'bulls' })
|
||||
displayNl.
|
||||
].
|
||||
('Good, you guessed it in %1 tries!' % { tries }) displayNl.
|
||||
'Do you want to play again? [y/n]' display.
|
||||
( (stdin nextLine) = 'y' )
|
||||
] whileTrue: [ Character nl displayNl ].
|
||||
85
Task/Bulls-and-cows/Tcl/bulls-and-cows.tcl
Normal file
85
Task/Bulls-and-cows/Tcl/bulls-and-cows.tcl
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
proc main {} {
|
||||
fconfigure stdout -buffering none
|
||||
set length 4
|
||||
|
||||
puts "I have chosen a number from $length unique digits from 1 to 9 arranged in a random order.
|
||||
You need to input a $length digit, unique digit number as a guess at what I have chosen
|
||||
"
|
||||
|
||||
while true {
|
||||
set word [generateWord $length]
|
||||
set count 1
|
||||
while {[set guess [getGuess $length]] ne $word} {
|
||||
printScore $length $word $guess
|
||||
incr count
|
||||
}
|
||||
puts "You guessed correctly in $count tries."
|
||||
if {[yn "Play again?"] eq "n"} break
|
||||
}
|
||||
}
|
||||
|
||||
proc generateWord {length} {
|
||||
set chars 123456789
|
||||
for {set i 1} {$i <= $length} {incr i} {
|
||||
set idx [expr {int(rand() * [string length $chars])}]
|
||||
append word [string index $chars $idx]
|
||||
set chars [string replace $chars $idx $idx]
|
||||
}
|
||||
return $word
|
||||
|
||||
# here's another way to generate word with no duplications
|
||||
set word ""
|
||||
while {[string length $word] < $length} {
|
||||
set char [expr {int(1 + 9*rand())}]
|
||||
if {[string first $char $word] == -1} {
|
||||
append word $char
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proc getGuess {length} {
|
||||
puts -nonewline "Enter your guess: "
|
||||
while true {
|
||||
gets stdin guess
|
||||
if {[string match [string repeat {[1-9]} $length] $guess]} {
|
||||
return $guess
|
||||
}
|
||||
if {[string tolower [string trim $guess]] eq "quit"} {
|
||||
puts Bye
|
||||
exit
|
||||
}
|
||||
puts "The word must be $length digits between 1 and 9 inclusive. Try again."
|
||||
}
|
||||
}
|
||||
|
||||
proc printScore {length word guess} {
|
||||
set bulls 0
|
||||
set cows 0
|
||||
for {set i 0} {$i < $length} {incr i} {
|
||||
if {[string index $word $i] eq [string index $guess $i]} {
|
||||
incr bulls
|
||||
set word [string replace $word $i $i +]
|
||||
}
|
||||
}
|
||||
puts " $bulls bulls"
|
||||
for {set i 0} {$i < $length} {incr i} {
|
||||
if {[set j [string first [string index $guess $i] $word]] != -1} {
|
||||
incr cows
|
||||
set word [string replace $word $j $j -]
|
||||
}
|
||||
}
|
||||
puts " $cows cows"
|
||||
}
|
||||
|
||||
proc yn {msg} {
|
||||
while true {
|
||||
puts -nonewline "$msg \[y/n] "
|
||||
gets stdin ans
|
||||
set char [string tolower [string index [string trim $ans] 0]]
|
||||
if {$char eq "y" || $char eq "n"} {
|
||||
return $char
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main
|
||||
Loading…
Add table
Add a link
Reference in a new issue