Bulls and cows: Difference between revisions

(added golo)
 
(86 intermediate revisions by 42 users not shown)
Line 1:
{{task|Games}}
[[Category:Puzzles]]
[[Category:Games]]
{{task|Games}}
 
[[wp:Bulls and Cows|Bulls and Cows]]   is an old game played with pencil and paper that was later implemented using computers.
Line 27:
*   [[Mastermind]]
<br><br>
=={{header|8080 Assembly}}==
 
This is written to run under CP/M and includes an RNG to generate the secret.
 
<syntaxhighlight lang="8080asm">bdos equ 5
putchar equ 2
rawio equ 6
puts equ 9
cstat equ 11
reads equ 10
 
org 100h
mvi c,puts
lxi d,signon ; Print name
call bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize the RNG with keyboard input
mvi c,puts
lxi d,entropy ; Ask for randomness
call bdos
mvi b,9 ; 9 times,
randloop: mvi c,3 ; read 3 keys.
lxi h,xabcdat + 1
randkey: push b ; Read a key
push h
randkeywait: mvi c,rawio
mvi e,0FFh
call bdos
ana a
jz randkeywait
pop h
pop b
xra m ; XOR it with the random memory
mov m,a
inx h
dcr c
jnz randkey ; Go get more characters
dcr b
jnz randloop
mvi c,puts
lxi d,done ; Tell the user we're done
call bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generate 4-digit secret code
lxi h,secret
mvi b,4
gencode: push h
push b
call randcode
pop b
pop h
mov m,a
inx h
dcr b
jnz gencode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User makes a guess
readguess: mvi c,puts ; Ask for guess
lxi d,guess
call bdos
mvi c,reads ; Read guess
lxi d,bufdef
call bdos
call newline ; Print newline
mvi b,4 ; Check input
lxi h,buf
validate: mov a,m
cpi '9' + 1 ; >9?
jnc inval ; = invalid
cpi '1' ; <1?
jc inval ; = invalid
sui '0' ; Make ASCII digit into number
mov m,a
inx h
dcr b
jnz validate
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Count bulls
mvi c,puts
lxi d,bulls ; Output "Bulls:"
call bdos
lxi d,secret
lxi h,buf
lxi b,4 ; No bulls, counter = 4
bullloop: ldax d ; Get secret digit
cmp m ; Match to buffer digit
cz countmatch
inx h
inx d
dcr c
jnz bullloop
push b ; Keep bulls for cow count,
push b ; and for final check.
call printcount
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Count cows
mvi c,puts
lxi d,cows ; Output ", Cows:"
call bdos
pop psw ; Retrieve the bulls (into A reg)
cma ; Negate amount of bulls
inr a
mov b,a ; Use it as start of cow count
mvi d,4 ; For all 4 secret digits..
lxi h,secret
cowouter: mov a,m ; Grab secret digit to test
push h ; Store secret position
mvi e,4 ; For all 4 input digits...
lxi h,buf
cowinner: cmp m ; Compare to current secret digit
cz countmatch
inx h
dcr e ; While there are more digits in buf
jnz cowinner ; Test next digit
pop h ; Restore secret position
inx h ; Look at next secret digit
dcr d ; While there are digits left
jnz cowouter
push b ; Keep cow count
call printcount
call newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Check win condition
pop psw ; Cow count (in A)
pop b ; Bull count (in B)
ana a ; To win, there must be 0 cows...
jnz readguess
mvi a,4 ; And 4 bulls.
cmp b
jnz readguess
mvi c,puts
lxi d,win
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Increment bull/cow counter
countmatch: inr b
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Print a newline
newline: mvi c,puts
lxi d,nl
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Output counter as ASCII
printcount: mvi a,'0'
add b
mvi c,putchar
mov e,a
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User entered invalid input
inval: mvi c,puts
lxi d,invalid
call bdos
jmp readguess
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generate random number 1-9 that isn't in key
randcode: call xabcrand
ani 0fh ; Low nybble
ana a ; 0 = invalid
jz randcode
cpi 10 ; >9 = invalid
jnc randcode
;; Check if it is a duplicate
mvi b,4
lxi h,secret
checkdup: cmp m
jz randcode
inx h
dcr b
jnz checkdup
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The "X ABC" 8-bit random number generator
;; (Google that to find where it came from)
xabcrand: lxi h,xabcdat
inr m ; X++
mov a,m ; X,
inx h ;
xra m ; ^ C,
inx h ;
xra m ; ^ A,
mov m,a ; -> A
inx h
add m ; + B,
mov m,a ; -> B
rar ; >>1
dcx h
xra m ; ^ A,
dcx h
add m ; + C
mov m,a ; -> C
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Strings
signon: db 'Bulls and Cows',13,10,'$'
entropy: db 'Please mash the keyboard to generate entropy...$'
done: db 'done.',13,10,13,10,'$'
bulls: db 'Bulls: $'
cows: db ', Cows: $'
guess: db 'Guess: $'
invalid: db 'Invalid input.',13,10,'$'
win: db 'You win!',13,10,'$'
nl: db 13,10,'$'
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variables
xabcdat: ds 4 ; RNG state
secret: ds 4 ; Holds the secret code
bufdef: db 4,0 ; User input buffer
buf: ds 4</syntaxhighlight>
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO RETURN random.digit:
RETURN choice "123456789"
 
HOW TO MAKE SECRET secret:
PUT "" IN secret
FOR i IN {1..4}:
PUT random.digit IN digit
WHILE SOME j IN {1..i-1} HAS secret item j = digit:
PUT random.digit IN digit
PUT secret^digit IN secret
 
HOW TO RETURN guess count.bulls secret:
PUT 0 IN bulls
FOR i IN {1..4}:
IF secret item i = guess item i: PUT bulls+1 IN bulls
RETURN bulls
 
HOW TO RETURN guess count.cows secret:
PUT -(guess count.bulls secret) IN cows
FOR c IN guess:
IF c in secret: PUT cows+1 IN cows
RETURN cows
 
HOW TO REPORT has.duplicates guess:
FOR i IN {1..3}:
FOR j IN {i+1..4}:
IF guess item i = guess item j: SUCCEED
FAIL
 
HOW TO REPORT is.valid guess:
IF SOME digit IN guess HAS digit not.in "123456789":
WRITE "Invalid digit: ", digit/
FAIL
IF #guess <> 4:
WRITE "Guess must contain 4 digits."/
FAIL
IF has.duplicates guess:
WRITE "No duplicates allowed"/
FAIL
SUCCEED
 
HOW TO READ GUESS guess:
WHILE 1=1:
WRITE "Guess? "
READ guess RAW
IF is.valid guess: QUIT
 
HOW TO PLAY BULLS AND COWS:
PUT 0, 0, 0 IN tries, bulls, cows
MAKE SECRET secret
WRITE "Bulls and cows"/
WRITE "--------------"/
WRITE /
WHILE bulls<>4:
READ GUESS guess
PUT guess count.bulls secret IN bulls
PUT guess count.cows secret IN cows
WRITE "Bulls:",bulls,"- Cows:",cows/
PUT tries+1 IN tries
WRITE "You win! Tries:", tries
 
PLAY BULLS AND COWS</syntaxhighlight>
{{out}}
<pre>Bulls and cows
--------------
 
Guess? 1234
Bulls: 0 - Cows: 1
Guess? 5678
Bulls: 0 - Cows: 2
Guess? 1679
Bulls: 0 - Cows: 2
Guess? 1689
Bulls: 0 - Cows: 2
Guess? 1659
Bulls: 1 - Cows: 2
Guess? 2659
Bulls: 1 - Cows: 2
Guess? 3659
Bulls: 1 - Cows: 3
Guess? 9356
Bulls: 4 - Cows: 0
You win! Tries: 8</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE DIGNUM="4"
 
TYPE Score=[BYTE bulls,cows,err]
 
PROC Generate(CHAR ARRAY secret)
DEFINE DIGCOUNT="9"
CHAR ARRAY digits(DIGCOUNT)
BYTE i,j,d,tmp,count
 
FOR i=0 TO DIGCOUNT-1
DO
digits(i)=i+'1
OD
 
secret(0)=DIGNUM
count=DIGCOUNT
FOR i=1 TO DIGNUM
DO
d=Rand(count)
secret(i)=digits(d)
count==-1
digits(d)=digits(count)
OD
RETURN
 
PROC CheckScore(CHAR ARRAY code,guess Score POINTER res)
BYTE i,j
 
res.bulls=0
res.cows=0
IF guess(0)#DIGNUM THEN
res.err=1
RETURN
FI
res.err=0
FOR i=1 TO DIGNUM
DO
IF guess(i)=code(i) THEN
res.bulls==+1
ELSE
FOR j=1 TO DIGNUM
DO
IF j#i AND guess(j)=code(i) THEN
res.cows==+1
EXIT
FI
OD
FI
OD
RETURN
 
PROC Main()
CHAR ARRAY code(DIGNUM+1),guess(255)
Score res
 
Generate(code)
PrintE("Bull and cows game.") PutE()
Print("I choose a 4-digit number from digits 1 to 9 without repetition. ")
PrintE("Your goal is to guess it.") PutE()
PrintE("Enter your guess:")
DO
InputS(guess)
CheckScore(code,guess,res)
Put(28) ;cursor up
PrintF("%S -> ",guess)
IF res.err THEN
Print("Wrong input")
ELSE
PrintF("Bulls=%B Cows=%B",res.bulls,res.cows)
IF res.bulls=DIGNUM THEN
PutE() PutE()
PrintE("You win!")
EXIT
FI
FI
PrintE(", try again:")
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bulls_and_cows.png Screenshot from Atari 8-bit computer]
<pre>
Bull and cows game.
 
I choose a 4-digit number from digits 1 to 9 without repetition. Your goal is to guess it.
 
Enter your guess:
12345 -> Wrong input, try again:
1234 -> Bulls=0 Cows=2, try again:
1243 -> Bulls=2 Cows=0, try again:
5643 -> Bulls=2 Cows=0, try again:
7843 -> Bulls=3 Cows=0, try again:
7943 -> Bulls=2 Cows=1, try again:
9843 -> Bulls=4 Cows=0
 
You win!
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 81 ⟶ 473:
end;
end loop;
end Bulls_And_Cows;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|Python}}
Line 91 ⟶ 482:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">STRING digits = "123456789";
 
[4]CHAR chosen;
Line 145 ⟶ 536:
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))</langsyntaxhighlight>
Output:
<pre>
Line 153 ⟶ 544:
Next guess [1]:
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
 
Call the <code>moo</code> function with one dummy argument to play a game of
Bulls and Cows in the APL session.
 
<syntaxhighlight lang="apl">input ← {⍞←'Guess: ' ⋄ 7↓⍞}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
valid ← isdigits∧4=≢
guess ← ⍎¨input⍣(valid⊣)
bulls ← +/=
cows ← +/∊∧≠
game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣)
random ← 4∘⊣?9∘⊣
moo ← 'You win!'⊣(random game⊢)
</syntaxhighlight>
 
 
To show off APL, this is written entirely in tacit style (except for the I/O). There is no explicit flow control or recursion,
and there are no variables. The code is split into functions only to aid the reader, none is ever
referred to twice. The following definition of <code>moo</code> is exactly equivalent to the above:
 
<syntaxhighlight lang="apl">moo←'You win!'⊣((4∘⊣?9∘⊣)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢)</syntaxhighlight>
=={{header|AppleScript}}==
 
GUI implementation; the prompt for a guess includes a list of all past guesses and their scores.
 
<langsyntaxhighlight lang="applescript">on pickNumber()
set theNumber to ""
repeat 4 times
Line 215 ⟶ 629:
end if
end repeat
end run</langsyntaxhighlight>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0
 
while [bulls <> 4][
bulls: new 0
cows: new 0
 
got: strip input "make a guess: "
if? or? not? numeric? got
4 <> size got -> print "Malformed answer. Try again!"
else [
loop.with:'i split got 'digit [
if? (to :integer digit) = rand\[i] -> inc 'bulls
else [
if contains? rand to :integer digit -> inc 'cows
]
]
print ["Bulls:" bulls "Cows:" cows "\n"]
]
]
print color #green "** Well done! You made the right guess!!"</syntaxhighlight>
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">length:=4, Code:="" ; settings
 
While StrLen(Code) < length {
Line 269 ⟶ 705:
Cows++
Return Bulls "," Cows
}</langsyntaxhighlight>
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
srand()
Line 324 ⟶ 760:
}
return bulls == 4
}</langsyntaxhighlight>
{{out}}
<pre>
Line 346 ⟶ 782:
Congratulations, you win!
</pre>
 
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">DEFINT A-Z
 
DIM secret AS STRING
Line 389 ⟶ 824:
END IF
looper:
LOOP</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 D$ = "123456789"
110 FOR I = 1 TO 4
120 P = INT(RND(1) * LEN(D$)) + 1
Line 419 ⟶ 854:
380 PRINT B " BULLS, " C " COWS"
390 Q = G$ = N$
400 NEXT Q</langsyntaxhighlight>
 
==={{header|BatchCommodore FileBASIC}}===
<lang dos>
::
::Bulls and Cows Task from Rosetta Code Wiki
::Batch File Implementation
::
::Directly OPEN the Batch File to play...
::
 
Based on the AppleSoft BASIC version. Modifications as follows:
* Accommodate 80 character BASIC line length (for line 250 especially), created subroutines.
* Booleans in Commodore BASIC evaluate to -1 for TRUE, therefore ABS function added to give desired results.
* Leading space in printed numbers (which is placeholder for negative sign) is included in string conversion in Commodore BASIC, therefore RIGHT$ function added on 220 to trim leading whitespace upon conversion.
* Other formatting (clear screen, etc.) unique to Commodore BASIC.
 
<syntaxhighlight lang="freebasic">100 D$="123456789"
110 FOR I=1 TO 4
120 P=INT(RND(1)*LEN(D$))+1
130 N$=N$+MID$(D$,P,1)
140 D$=MID$(D$,1,P - 1)+MID$(D$,P+1,8)
150 NEXT
160 PRINT CHR$(147);"A RANDOM NUMBER HAS BEEN CREATED."
170 PRINT "THE NUMBER HAS FOUR DIGITS FROM 1 TO 9, WITHOUT DUPLICATION."
200 FOR Q=0 TO 1 STEP 0
210 INPUT "GUESS THE NUMBER: "; G%
219 REM CONVERT TO STRING AND TRIM LEADING SPACE
220 G$=RIGHT$(STR$(G%),4)
230 M=LEN(G$)<>4 OR G%=0
240 IF NOT M THEN GOSUB 600
250 IF NOT M THEN GOSUB 700
260 IF M THEN PRINT "THE GUESS IS MALFORMED.":NEXT Q
270 B=0
280 C=0
300 FOR I=1 TO 4
310 C$=MID$(N$,I,1)
320 BULL=MID$(G$,I,1)=C$
330 COW=0
340 IF NOT BULL THEN FOR J=1 TO 4:COW=MID$(G$,J,1)=C$:IF NOT COW THEN NEXT J
350 B=B+ABS(BULL)
360 C=C+ABS(COW)
370 NEXT I
380 PRINT "BULLS:";B:PRINT "COWS:";C
390 Q=ABS(G$=N$)
400 NEXT Q
500 PRINT "GOOD JOB!":END
600 FOR I=2 TO 4:M=MID$(G$,I,1)="0"
610 IF NOT M THEN NEXT I
620 RETURN
700 FOR I=1 TO 3
710 FOR J=I+1 TO 4
720 M=MID$(G$,I,1)=MID$(G$,J,1)
730 IF NOT M THEN NEXT J,I
740 RETURN
</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Bulls.bas"
110 RANDOMIZE
120 STRING C$*4
130 LET GUESS=0
140 DO
150 LET C$=STR$(RND(8701)+1199)
160 LOOP UNTIL CHECK$(C$)=C$
170 CLEAR SCREEN:PRINT "Welcome to 'Bulls and Cows!'"
180 DO
190 DO
200 PRINT :INPUT PROMPT "Guess a 4-digit number with no duplicate digits: ":G$
210 IF CHECK$(G$)="" THEN PRINT "You should enter 4-digit number with no duplicate digits."
220 LOOP UNTIL CHECK$(G$)=G$ AND G$<>""
230 LET GUESS=GUESS+1:LET BULLS,COWS=0
240 FOR I=1 TO 4
250 IF C$(I)=G$(I) THEN
260 LET BULLS=BULLS+1
270 ELSE IF POS(C$,G$(I))<>0 THEN
280 LET COWS=COWS+1
290 END IF
300 NEXT
310 PRINT BULLS;"bulls,";COWS;"cows"
320 LOOP UNTIL C$=G$
330 PRINT "You won after";GUESS;"guesses!"
340 DEF CHECK$(S$)
350 LET CHECK$=""
360 IF LEN(STR$(VAL(S$)))=4 AND POS(S$,"0")=0 THEN LET CHECK$=S$
370 FOR I=1 TO 4
380 IF POS(S$(:I-1),S$(I)) OR POS(S$(I+1:),S$(I)) THEN LET CHECK$=""
390 NEXT
400 END DEF</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
{{trans|QBasic}}
<syntaxhighlight lang="zxbasic">10 DIM n(10): LET c$=""
20 FOR i=1 TO 4
30 LET d=INT (RND*9+1)
40 IF n(d)=1 THEN GO TO 30
50 LET n(d)=1
60 LET c$=c$+STR$ d
70 NEXT i
80 LET guesses=0
90 INPUT "Guess a 4-digit number (1 to 9) with no duplicate digits: ";guess
100 IF guess=0 THEN STOP
110 IF guess>9999 OR guess<1000 THEN PRINT "Only 4 numeric digits, please": GO TO 90
120 LET bulls=0: LET cows=0: LET guesses=guesses+1: LET g$=STR$ guess
130 FOR i=1 TO 4
140 IF g$(i)=c$(i) THEN LET bulls=bulls+1: GO TO 160
150 IF n(VAL g$(i))=1 THEN LET cows=cows+1
160 NEXT i
170 PRINT bulls;" bulls, ";cows;" cows"
180 IF c$=g$ THEN PRINT "You won after ";guesses;" guesses!": GO TO 10
190 GO TO 90
</syntaxhighlight>
=={{header|Batch File}}==
<syntaxhighlight lang="dos">:: Bulls and Cows Task from Rosetta Code
:: Batch File Implementation
@echo off
title Bulls and Cows Game
setlocal enabledelayedexpansion
 
:: initialization
::GENERATING THE CODE TO BE GUESSED BY PLAYER...
:begin
set list"list_chars=123456789"
set cnt"list_length=19"
set "code="
set "code_length=4" %== this should be less than 10 ==%
set tries=0
set "tries=0" %== number of tries ==%
:gen
 
set /a mod=10-%cnt%
:: generate the code to be guessed by player
set /a rnd=%random%%%%mod%
set "chars_left=%list_chars%"
set pick=!list:~%rnd%,1!
for /l %%c in (1, 1, %code_length%) do (
set code=%code%%pick%
set /a "rnd=!random! %% (%list_length% + 1 - %%c)"
set list=!list:%pick%=!
for %%? in (!rnd!) do set "pick_char=!chars_left:~%%?,1!"
if %cnt%==4 (
set "code=!code!!pick_char!"
set c1=%code:~0,1%&set c2=%code:~1,1%&set c3=%code:~2,1%&set c4=%code:~3,1%
for %%? in (!pick_char!) do set "chars_left=!chars_left:%%?=!"
goto :start
)
set /a cnt+=1
goto :gen
::/GENERATING THE CODE TO BE GUESSED BY PLAYER...
 
:: get the min and max allowable guess for input validation
::GAME DISPLAY
set "min=!list_chars:~0,%code_length%!"
:start
set "max="
for /l %%c in (1, 1, %code_length%) do set "max=!max!!list_chars:~-%%c,1!"
 
:: display game
:display
cls
echo.(
echo (Bulls and Cows Game
echo (Batch File Implementation
echo.(
echo(Gameplay:
echo NOTE: Please MAXIMIZE this command window.
echo.(
echo(I have generated a %code_length%-digit code from digits 1-9 without duplication.
echo Gameplay:
echo(Your objective is to guess it. If your guess is equal to my code,
echo.
echo(then you WIN. If not, I will score your guess:
echo I have generated a 4-digit code from digit 1-9 WITHOUT duplication.
echo(
echo Your objective is to guess it. If your guess is equal to my code,
echo(** thenA youscore WIN.of Ifone not,BULL Iis willaccumulated scorefor each digit in your guess:
echo(that equals the corresponding digit in my code.
echo.
echo(
echo ** A score of one BULL is accumulated for each digit that equals
echo(** theA CORRESPONDINGscore of one COW is accumulated for each digit in myyour code.guess
echo(that also appears in my code, but in the WRONG position.
echo.
echo(
echo ** A score of one COW is accumulated for each digit that appears
echo(Now, start guessing^^!
echo in your guess, but in the WRONG position.
echo.
echo Now, start guessing^^!
echo.
:game
echo.
set /p guess=Your Guess:
::/GAME DISPLAY
 
:: input guess
::INPUT VALIDATION
:guess
if !guess! gtr 9876 (echo Please input a valid guess.&goto :game)
echo(
if !guess! lss 1234 (echo Please input a valid guess.&goto :game)
set "guess=" %== clear input ==%
set i1=%guess:~0,1%&set i2=%guess:~1,1%&set i3=%guess:~2,1%&set i4=%guess:~3,1%
set /p "guess=Your Guess: "
set chk=1
 
:cycle
:: validate input
set /a tmp1=%chk%+1
if "!guess!" gtr "%max%" goto invalid
for /l %%a in (%tmp1%,1,4) do (
if "!i%chk%guess!==!i" lss "%min%a!" goto (invalid
set /a "last_idx=%code_length% - 1"
echo Please input a valid guess.&goto :game
for /l %%i in (0, 1, %last_idx%) do (
)
set /a "next_idx=%%i + 1"
)
for /l %%j in (!next_idx!, 1, %last_idx%) do (
if %chk%==3 (
if "!guess:~%%i,1!" equ "!guess:~%%j,1!" goto invalid
goto :score
)
)
goto score
set /a chk+=1
goto :cycle
::/INPUT VALIDATION
 
:: display that input is invalid
::SCORING
:invalid
echo(Please input a valid guess.
goto guess
 
:: scoring section
:score
set /a "tries+=1"
if "%guess%==" equ "%code%" (goto :won)win
set "cow=0"
set "bull=0"
for /l %%ai in (10, 1,4 %last_idx%) do (
for /l %%j in (0, 1, %last_idx%) do (
if !i%%a!==!c%%a! (
if "!guess:~%%i,1!" equ "!code:~%%j,1!" (
set /a bull+=1
if "%%i" equ "%%j" (
) else (
set /a "bull+=1"
set "entrycow=%%a"
) else (
call :scorecow
set /a "cow+=1"
)
)
)
)
)
:: display score and go back to user input
set guess=
echo (BULLS = %bull%; COWS = %cow%.
goto :gameguess
 
:: player wins!
:scorecow
:win
set nums=1 2 3 4
echo(
set put=!nums:%entrycow%=!
echo(After %tries% tries, YOU CRACKED IT^^! My code is %code%.
for %%b in (%put%) do (
echo(
if !c%%b!==!i%entrycow%! (
set /ap cow+"opt=1Play again? "
if /i "!opt!" equ "y" goto begin
goto :EOF
exit /b 0</syntaxhighlight>
)
{{Out}}
)
<pre>
goto :EOF
Bulls and Cows Game
::/SCORING
Batch File Implementation
 
Gameplay:
 
I have generated a 4-digit code from digits 1-9 without duplication.
Your objective is to guess it. If your guess is equal to my code,
then you WIN. If not, I will score your guess:
 
** A score of one BULL is accumulated for each digit in your guess
that equals the corresponding digit in my code.
 
** A score of one COW is accumulated for each digit in your guess
that also appears in my code, but in the WRONG position.
 
Now, start guessing!
 
Your Guess: 0123
Please input a valid guess.
 
Your Guess: 1234
BULLS = 0; COWS = 3.
 
Your Guess: 4123
BULLS = 2; COWS = 1.
 
...
 
Your Guess: 4391
BULLS = 2; COWS = 0.
 
Your Guess: 4521
BULLS = 3; COWS = 0.
 
Your Guess: 4621
BULLS = 3; COWS = 0.
 
Your Guess: 4821
 
After 10 tries, YOU CRACKED IT! My code is 4821.
::ALREADY WON!
:won
echo.
echo.
echo After %tries% Tries, YOU CRACKED IT^^! My code is %code%.
echo.
set /p opt=Play again?(Y/N)
if /i "!opt!"=="y" (call :begin)
if /i "!opt!"=="n" (exit/b)
goto :won
::/ALREADY WON!
</lang>
 
Play again? </pre>
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> secret$ = ""
REPEAT
c$ = CHR$(&30 + RND(9))
Line 577 ⟶ 1,138:
UNTIL FALSE
</syntaxhighlight>
</lang>
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
static $( randstate = ? $)
 
let randdigit() = valof
$( let x = ?
$( randstate := random(randstate)
x := (randstate >> 7) & 15
$) repeatuntil 0 < x <= 9
resultis x
$)
 
let gensecret(s) be
for i=0 to 3
s!i := randdigit() repeatuntil valof
$( for j=0 to i-1 if s!i = s!j then resultis false
resultis true
$)
 
let bulls(secret, guess) = valof
$( let x = 0
for i=0 to 3 if secret!i = guess!i then x := x + 1
resultis x
$)
 
let cows(secret, guess) = valof
$( let x = 0
for i=0 to 3
for j=0 to 3
unless i=j
if secret!i = guess!j then x := x + 1
resultis x
$)
 
let readguess(guess) be
$( let g, v = ?, true
writes("Enter a guess, or 0 to quit: ")
g := readn()
if g=0 then finish
for i=3 to 0 by -1
$( guess!i := g rem 10
g := g / 10
$)
for i=0 to 2 for j = i+1 to 3
v := v & guess!i ~= 0 & guess!j ~= 0 & guess!i ~= guess!j
if v then return
writes("Invalid guess.*N")
$) repeat
 
let play(secret) be
$( let tries, b, c = 0, ?, ?
let guess = vec 3
$( readguess(guess)
b := bulls(secret, guess)
c := cows(secret, guess)
writef("Bulls: %N, cows: %N*N", b, c);
tries := tries + 1
$) repeatuntil b = 4
writef("You win in %N tries.*N", tries)
$)
 
let start() be
$( let secret = vec 3
writes("Bulls and cows*N----- --- ----*N")
writes("Please enter a random seed: ")
randstate := readn()
wrch('*N')
gensecret(secret)
play(secret)
$)</syntaxhighlight>
{{out}}
<pre>Bulls and cows
----- --- ----
Please enter a random seed: 20394
 
Enter a guess, or 0 to quit: 1234
Bulls: 0, cows: 3
Enter a guess, or 0 to quit: 4321
Bulls: 1, cows: 2
Enter a guess, or 0 to quit: 1423
Bulls: 2, cows: 1
Enter a guess, or 0 to quit: 1243
Bulls: 1, cows: 2
Enter a guess, or 0 to quit: 4123
Bulls: 3, cows: 0
Enter a guess, or 0 to quit: 4523
Bulls: 2, cows: 0
Enter a guess, or 0 to quit: 5123
Bulls: 3, cows: 0
Enter a guess, or 0 to quit: 6123
Bulls: 3, cows: 0
Enter a guess, or 0 to quit: 7123
Bulls: 4, cows: 0
You win in 9 tries.</pre>
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">secret_length = 4
 
secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
Line 618 ⟶ 1,273:
guesses = guesses + 1
}
}</langsyntaxhighlight>
 
=={{header|C}}==
{{libheader|ncurses}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
Line 681 ⟶ 1,335:
}
}
}</langsyntaxhighlight>
 
The following function contains the code to check how many bulls and cows there are.
 
<langsyntaxhighlight lang="c">bool take_it_or_not()
{
int i;
Line 769 ⟶ 1,423:
nocbreak(); echo(); endwin();
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
 
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
 
void game()
{
typedef std::string::size_type index;
 
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
 
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
 
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
 
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
}</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace BullsnCows
Line 931 ⟶ 1,504:
}
}
</syntaxhighlight>
</lang>
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
 
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
 
void game()
{
typedef std::string::size_type index;
 
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
 
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
 
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
 
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
}</syntaxhighlight>
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
}
Line 1,003 ⟶ 1,654:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(ns bulls-and-cows)
Line 1,045 ⟶ 1,695:
(bulls-and-cows)
</syntaxhighlight>
</lang>
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
% pclu -merge $CLUHOME/lib/misc.lib -compile bulls_cows.clu
 
% Seed the random number generator with the current time
init_rng = proc ()
d: date := now()
seed: int := ((d.hour*60) + d.minute)*60 + d.second
random$seed(seed)
end init_rng
 
% Generate a secret
make_secret = proc () returns (sequence[int])
secret: array[int] := array[int]$[0,0,0,0]
for i: int in int$from_to(1,4) do
digit: int
valid: bool := false
while ~valid do
digit := 1+random$next(9)
valid := true
for j: int in int$from_to(1, i-1) do
if secret[i] = digit then
valid := false
break
end
end
end
secret[i] := digit
end
return(sequence[int]$a2s(secret))
end make_secret
 
% Count the bulls
bulls = proc (secret, input: sequence[int]) returns (int)
n_bulls: int := 0
for i: int in int$from_to(1,4) do
if secret[i] = input[i] then n_bulls := n_bulls + 1 end
end
return(n_bulls)
end bulls
 
% Count the cows
cows = proc (secret, input: sequence[int]) returns (int)
n_cows: int := 0
for i: int in int$from_to(1,4) do
for j: int in int$from_to(1,4) do
if i ~= j cand secret[i] = input[j] then
n_cows := n_cows + 1
end
end
end
return(n_cows)
end cows
 
% Read a guess
player_guess = proc () returns (sequence[int])
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
while true do % we will keep reading until the guess is valid
stream$puts(po, "Guess? ")
guess: string := stream$getl(pi)
% check length
if string$size(guess) ~= 4 then
stream$putl(po, "Invalid guess: need four digits.")
continue
end
% get and check digits
valid: bool := true
digits: sequence[int] := sequence[int]$[]
for c: char in string$chars(guess) do
i: int := char$c2i(c) - 48
if ~(i>=1 & i<=9) then
valid := false
break
end
digits := sequence[int]$addh(digits,i)
end
if ~valid then
stream$putl(po, "Invalid guess: each position needs to be a digit 1-9.")
continue
end
% check that there are no duplicates
valid := true
for i: int in int$from_to(1,4) do
for j: int in int$from_to(i+1,4) do
if digits[i] = digits[j] then
valid := false
break
end
end
end
if ~valid then
stream$putl(po, "Invalid guess: there must be no duplicate digits.")
continue
end
return(digits)
end
end player_guess
 
% Play a game
play_game = proc (secret: sequence[int])
po: stream := stream$primary_output()
n_guesses: int := 0
while true do
n_guesses := n_guesses + 1
guess: sequence[int] := player_guess()
n_bulls: int := bulls(secret, guess)
n_cows: int := cows(secret, guess)
stream$putl(po, "Bulls: " || int$unparse(n_bulls)
|| ", cows: " || int$unparse(n_cows))
if n_bulls = 4 then
stream$putl(po, "Congratulations! You won in "
|| int$unparse(n_guesses) || " tries.")
break
end
end
end play_game
 
start_up = proc ()
po: stream := stream$primary_output()
init_rng()
stream$putl(po, "Bulls and cows\n----- --- ----\n")
play_game(make_secret())
end start_up</syntaxhighlight>
{{out}}
<pre>Bulls and cows
----- --- ----
 
Guess? 1234
Bulls: 0, cows: 1
Guess? 5678
Bulls: 0, cows: 2
Guess? 4579
Bulls: 1, cows: 2
Guess? 3579
Bulls: 2, cows: 2
Guess? 3759
Bulls: 4, cows: 0
Congratulations! You won in 5 tries.</pre>
=={{header|Coco}}==
 
Line 1,053 ⟶ 1,850:
To handle I/O, we use functions named <code>say</code> (which simply outputs a string) and <code>prompt</code> (which takes a prompt string to display to the user and returns a line of input, without a trailing newline). These require platform-specific implementations. Here's how they can be implemented for the SpiderMonkey shell:
 
<langsyntaxhighlight lang="coco">say = print
prompt = (str) ->
putstr str
readline! ? quit!</langsyntaxhighlight>
 
We can now solve the task using <code>say</code> and <code>prompt</code>:
 
<langsyntaxhighlight lang="coco">const SIZE = 4
 
secret = _.sample ['1' to '9'], SIZE
Line 1,081 ⟶ 1,878:
say "#bulls bull#{[if bulls !== 1 then 's']}, #cows cow#{[if cows !== 1 then 's']}."
 
say 'A winner is you!'</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun get-number ()
(do ((digits '()))
((>= (length digits) 4) digits)
Line 1,125 ⟶ 1,921:
(format stream "~&Correct, you win!")
(format stream "~&Score: ~a cows, ~a bulls."
cows bulls)))))))</langsyntaxhighlight>
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight Rubylang="ruby">size = 4
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
Line 1,162 ⟶ 1,958:
 
puts "Bulls: #{bulls}; Cows: #{cows}"
end</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.string, std.algorithm,
std.range, std.ascii;
Line 1,182 ⟶ 1,977:
" Bad guess! (4 unique digits, 1-9)".writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>Next guess: 6548
Line 1,203 ⟶ 1,998:
Next guess: 5814
You guessed it!</pre>
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|Draco}}==
<syntaxhighlight lang="draco">union {
ulong state;
struct {
byte x;
byte a;
byte b;
byte c;
} fields;
} rng;
 
proc rand() byte:
rng.fields.x := rng.fields.x + 1;
rng.fields.a := rng.fields.a >< rng.fields.c >< rng.fields.x;
rng.fields.b := rng.fields.b + rng.fields.a;
rng.fields.c := rng.fields.c + (rng.fields.b >> 1) >< rng.fields.a;
rng.fields.c
corp
 
proc rand_digit() byte:
byte digit;
while
digit := rand() & 15;
digit < 1 or digit >= 10
do od;
digit
corp
 
proc make_secret([4]byte secret) void:
int i, j;
bool ok;
for i from 0 upto 3 do
while
secret[i] := rand_digit();
ok := true;
for j from 0 upto i-1 do
ok := ok and secret[i] /= secret[j]
od;
not ok
do od
od
corp
 
proc bulls([4]byte secret, guess) byte:
byte i, count;
count := 0;
for i from 0 upto 3 do
if secret[i] = guess[i] then count := count + 1 fi
od;
count
corp
 
proc cows([4]byte secret, guess) byte:
byte i, j, count;
count := 0;
for i from 0 upto 3 do
for j from 0 upto 3 do
if i /= j and secret[i] = guess[j] then count := count + 1 fi
od
od;
count
corp
 
proc read_guess([4]byte guess) void:
word guessNo;
byte i;
 
while
write("Guess? ");
readln(guessNo);
if guessNo<1111 or guessNo>9999 then true
else
for i from 3 downto 0 do
guess[i] := guessNo % 10;
guessNo := guessNo / 10;
od;
guess[0]*guess[1]*guess[2]*guess[3] = 0
fi
do
writeln("A guess must be a four-digit number not containing zeroes.")
od
corp
 
proc play_game([4]byte secret) word:
[4]byte guess;
word tries;
tries := 1;
while
read_guess(guess);
writeln("Bulls: ", bulls(secret, guess), ", cows: ", cows(secret, guess));
bulls(secret, guess) /= 4
do
tries := tries + 1
od;
tries
corp
 
proc main() void:
[4]byte secret;
word tries;
 
write("Please enter a random seed: ");
readln(rng.state);
make_secret(secret);
tries := play_game(secret);
writeln();
writeln("You got it in ", tries, " tries.")
corp</syntaxhighlight>
{{out}}
<pre>Please enter a random seed: 123456
Guess? 1234
Bulls: 2, cows: 1
Guess? 5678
Bulls: 0, cows: 0
Guess? 9234
Bulls: 1, cows: 2
Guess? 1934
Bulls: 3, cows: 0
Guess? 1294
Bulls: 2, cows: 2
Guess? 1924
Bulls: 4, cows: 0
 
You got it in 6 tries.</pre>
 
=={{header|E}}==
Line 1,208 ⟶ 2,130:
Note: This example was deliberately written in an abstracted style, separating out the algorithms, game logic, and UI.
 
<langsyntaxhighlight lang="e">def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]
 
Line 1,289 ⟶ 2,211:
return gameTurn()
}</langsyntaxhighlight>
 
===REPL user interface===
Line 1,311 ⟶ 2,233:
{{works with|E-on-Java}} (Java Swing)
 
<langsyntaxhighlight lang="e">def guiBullsAndCows() {
var lastGuess := ""
def op := <unsafe:javax.swing.makeJOptionPane>
Line 1,325 ⟶ 2,247:
op.showMessageDialog(null, msg)
}, entropy)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>dig[] = [ 1 2 3 4 5 6 7 8 9 ]
dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
for hi = i1 +to random (9 - i)4
h = i - 1 + randint (10 - i)
swap dig[i] dig[h]
swap dig[i] dig[h]
.
# print dig[]
Line 1,337 ⟶ 2,260:
attempts = 0
repeat
repeat
ok = 0
s$[] = str_splitstrchars input
if len s$[] = 4
ok = 1
for i range= 1 to 4
g[i] = number s$[i]
if g[i] = 0
ok = 0
.
.
.
. until ok = 1
.
until ok = 1
print g[]
.
attempts += 1
print g[]
attempts +bulls = 10
bulls cows = 0
cows for i = 01 to 4
for if g[i] range= 4dig[i]
if g[i] bulls += dig[i]1
bulls += 1else
for j = 1 to 4
else
for if dig[j] range= 4g[i]
if dig[j] cows += g[i]1
cows += 1.
.
.
.
print "bulls:" & bulls & " cows:" & cows
.
print "bulls:" &until bulls & " cows:" &= cows4
until bulls = 4
.
print "Well done! " & attempts & " attempts needed."</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
BULLS_AND_COWS
Line 1,485 ⟶ 2,408:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,512 ⟶ 2,435:
Congratulations! You won with 6 guesses.
</pre>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
 
class GameMaster
{
field _numbers;
object theNumbers;
field _attempt;
object theAttempt;
 
constructor()
{
// generate secret number
var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9);
 
theNumbers_numbers := randomNumbers.Subarray(0, 4);
theAttempt_attempt := new Integer(1);
}
 
ask()
{
var row := console.print("Your Guess #",theAttempt_attempt," ?").readLine();
^ row.toArray()
}
 
proceed(guess)
{
int cows := 0;
int bulls := 0;
 
if (guess.Length != 4)
{
bulls := -1
}
else
{
try
{
for (int i := 0,; i < 4,; i+=1) {
var ch := guess[i];
var number := ch.toString().toInt();
// check range
ifnot (number > 0 && number < 10)
{ InvalidArgumentException.raise() };
// check duplicates
var duplicate := guess.seekEach::(x => (x == ch)&&(x.equalReference(ch).Inverted));
if (nil != duplicate)
{
InvalidArgumentException.raise()
};
if (number == theNumbers_numbers[i])
{
bulls += 1
}
else
{
if (theNumbers_numbers.ifExists(number))
{ cows += 1 }
}
}
}
catch(Exception e)}
catch(Exception {e)
bulls := -1{
}bulls := -1
};
};
 
bulls =>
-1 { console.printLine:("Not a valid guess."); ^ true }
4 { console.printLine:("Congratulations! You have won!"); ^ false }
:! {
theAttempt_attempt.append(1);
console.printLine("Your Score is ",bulls," bulls and ",cows," cows");
^ true
}
}
}
 
public program()
{
var gameMaster := new GameMaster();
 
var process := $lazy gameMaster.proceed(gameMaster.ask());
 
lazy::(^gameMaster.proceed(gameMaster.ask()))process.doWhile();
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,623 ⟶ 2,547:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">defmodule Bulls_and_cows do
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
Line 1,664 ⟶ 2,588:
end
 
Bulls_and_cows.play</langsyntaxhighlight>
 
{{out}}
Line 1,679 ⟶ 2,603:
You win!
</pre>
 
=={{header|Erlang}}==
Module:
<langsyntaxhighlight lang="erlang">-module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).
 
Line 1,726 ⟶ 2,649:
read_guess() ->
lists:map(fun(D)->D-48 end,
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).</langsyntaxhighlight>
 
Script:
<langsyntaxhighlight lang="erlang">#!/usr/bin/escript
% Play Bulls and Cows
main(_) -> random:seed(now()), bulls_and_cows:play().</langsyntaxhighlight>
 
Sample play:<pre>Enter your 4-digit guess: 8376
Line 1,744 ⟶ 2,667:
Correct!
</pre>
 
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<langsyntaxhighlight lang="euphoria">include std\text.e
include std\os.e
include std\sequence.e
Line 1,852 ⟶ 2,774:
 
 
</syntaxhighlight>
</lang>
Output :
<pre>
Line 1,875 ⟶ 2,797:
Press Any Key to continue...
</pre>
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
open System
 
let generate_number targetSize =
let rnd = Random()
let initial = Seq.initInfinite (fun _ -> rnd.Next(1,9))
initial |> Seq.distinct |> Seq.take(targetSize) |> Seq.toList
 
let countBulls guess target =
let hits = List.map2 (fun g t -> if g = t then true else false) guess target
List.filter (fun x -> x = true) hits |> List.length
 
let countCows guess target =
let mutable score = 0
for g in guess do
for t in target do
if g = t then
score <- score + 1
else
score <- score
score
 
let countScore guess target =
let bulls = countBulls guess target
let cows = countCows guess target
(bulls, cows)
 
let playRound guess target =
countScore guess target
 
let inline ctoi c : int =
int c - int '0'
 
let lineToList (line: string) =
let listc = Seq.map(fun c -> c |> string) line |> Seq.toList
let conv = List.map(fun x -> Int32.Parse x) listc
conv
 
let readLine() =
let line = Console.ReadLine()
if line <> null then
if line.Length = 4 then
Ok (lineToList line)
else
Error("Input guess must be 4 characters!")
else
Error("Input guess cannot be empty!")
 
let rec handleInput() =
let line = readLine()
match line with
| Ok x -> x
| Error s ->
printfn "%A" s
handleInput()
 
[<EntryPoint>]
let main argv =
let target = generate_number 4
let mutable shouldEnd = false
while shouldEnd = false do
let guess = handleInput()
let (b, c) = playRound guess target
printfn "Bulls: %i | Cows: %i" b c
if b = 4 then
shouldEnd <- true
else
shouldEnd <- false
0
</syntaxhighlight>
 
=={{Header|FreeBASIC}}==
<syntaxhighlight lang="text">function get_digit( num as uinteger, ps as uinteger ) as uinteger
return (num mod 10^(ps+1))\10^ps
end function
 
function is_malformed( num as uinteger ) as boolean
if num > 9876 then return true
dim as uinteger i, j
for i = 0 to 2
for j = i+1 to 3
if get_digit( num, j ) = get_digit( num, i ) then return true
next j
next i
return false
end function
 
function make_number() as uinteger
dim as uinteger num = 0
while is_malformed(num)
num = int(rnd*9877)
wend
return num
end function
 
randomize timer
 
dim as uinteger count=0, num=make_number(), guess=0
dim as uinteger cows, bulls, i, j
 
while guess <> num
count += 1
do
print "Guess a number. "
input guess
loop while is_malformed(guess)
cows = 0
bulls = 0
for i = 0 to 3
for j = 0 to 3
if get_digit( num, i ) = get_digit( guess, j ) then
if i= j then bulls += 1
if i<>j then cows += 1
end if
next j
next i
print using "You scored # bulls and # cows."; bulls; cows
wend
 
print using "Correct. That took you ### guesses."; count</syntaxhighlight>
=={{header|Factor}}==
<langsyntaxhighlight Factorlang="factor">USING: accessors assocs combinators fry grouping hashtables kernel
locals math math.parser math.ranges random sequences strings
io ascii ;
Line 1,940 ⟶ 2,984:
[ main-loop ] [ drop win ] if ;
 
: main ( -- ) new-number drop narr>nhash main-loop ;</langsyntaxhighlight>
 
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
<lang Fan>**
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
Line 1,992 ⟶ 3,035:
}
}
}</langsyntaxhighlight>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 T %1,"BULLS AND COWS"!"----- --- ----"!!
01.20 S T=0;D 3
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
01.40 I (B-4)1.3
01.50 T "YOU WON! GUESSES",%4,T,!!
01.60 Q
 
02.10 A "GUESS",A
02.20 F X=0,3;S B=FITR(A/10);S G(3-X)=A-B*10;S A=B
02.30 S A=1
02.40 F X=0,3;S A=A*G(X)
02.50 I (-A)2.6;T "NEED FOUR NONZERO DIGITS"!;G 2.1
02.60 F X=0,2;F Y=X+1,3;S A=A*(FABS(G(X)-G(Y)))
02.70 I (-A)2.8;T "NO DUPLICATES ALLOWED"!;G 2.1
02.80 R
 
03.10 F X=0,3;S S(X)=0
03.20 F X=0,3;D 4;S S(X)=A
 
04.10 S A=10*FRAN();S A=FITR(1+9*(A-FITR(A)))
04.20 S Z=1
04.30 F Y=0,3;S Z=Z*(FABS(A-S(Y)))
04.40 I (-Z)4.5,4.1
04.50 R
 
05.10 S B=0
05.20 F X=0,3;D 5.6
05.30 S C=-B
05.40 F X=0,3;F Y=0,3;D 5.7
05.50 R
05.60 I (-FABS(S(X)-G(X)))5.5,5.8
05.70 I (-FABS(S(X)-G(Y)))5.5,5.9
05.80 S B=B+1
05.90 S C=C+1</syntaxhighlight>
 
{{out}}
 
<pre>BULLS AND COWS
----- --- ----
 
GUESS:1234
BULLS= 0 COWS= 3
 
GUESS:3214
BULLS= 1 COWS= 2
 
GUESS:3124
BULLS= 2 COWS= 1
 
GUESS:3145
BULLS= 3 COWS= 0
 
GUESS:3146
BULLS= 3 COWS= 0
 
GUESS:3147
BULLS= 3 COWS= 0
 
GUESS:3148
BULLS= 3 COWS= 0
 
GUESS:3149
BULLS= 4 COWS= 0
 
YOU WON! GUESSES= 8</pre>
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">include random.fs
 
create hidden 4 allot
Line 2,032 ⟶ 3,140:
: 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 ;</langsyntaxhighlight>
{{out}}
init ok
<pre>init ok
guess: 1234 1 bulls, 0 cows ok
guess: 1567 1 bulls, 1 cows ok
guess: 1895 2 bulls, 1 cows ok
guess: 1879 4 bulls, 0 cows
You guessed it! ok</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module bac
implicit none
 
Line 2,125 ⟶ 3,233:
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
 
end program Bulls_and_Cows</langsyntaxhighlight>
=={{header|Frink}}==
<syntaxhighlight lang="frink">
// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]
 
// Put 4 random digits into target array
digits = array[1 to 9]
target = new array
for i = 0 to 3
{
target@i = digits.removeRandom[]
}
 
// Game variables
guessCount = 0
solved = 0
 
while solved == 0
{
// Round variables
bulls = 0
cows = 0
 
// Input guess from player
guess = input["Guess a 4 digit number with numbers 1 to 9: "]
 
// Valid Guess Tests. Set validGuess to 1. If any test fails it will be set to 0
validGuess = 1
// Test for exactly 4 digits
if length[guess] != 4
{
println["$guess is invalid. Your guess must be 4 digits."]
validGuess = 0
}
// Test for any characters not in 1 - 9 using regex
if guess =~ %r/[^1-9]/
{
println["$guess is invalid. Your guess can only contain the digits 1 through 9."]
validGuess = 0
}
// Check for duplicate digits in guess
comboCheck = 1
guessArr = charList[guess] // Split guess string into array of characters.
guessArrCombos = guessArr.combinations[2] // Divide the array into all possible 2 digits combinations.
for geussCombo = guessArrCombos
{
if geussCombo@0 == geussCombo@1 // If the two digits in the combinations are the same mark the comboCheck as failed.
comboCheck = 0
}
if comboCheck == 0
{
println["$guess is invalid. Each digit in your guess should be unique."]
validGuess = 0
}
 
// If all tests pass, continue with the game.
if validGuess == 1
{
guessCount = guessCount + 1
for i = 0 to 3
{
if parseInt[guessArr@i] == target@i // Convert guess from string to int. Frink imports all input as strings.
{
bulls = bulls + 1
next // If bull is found, skip the contains check.
}
if target.contains[parseInt[guessArr@i]]
{
cows = cows + 1
}
}
if bulls == 4
{
solved = 1 // Exit from While loop.
} else
{
// Print the results of the guess. Formatting for plurals.
bullsPlural = bulls == 1 ? "bull" : "bulls"
cowsPlural = cows == 1 ? "cow" : "cows"
println["Your guess of $guess had $bulls $bullsPlural and $cows $cowsPlural."]
}
}
}
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]
</syntaxhighlight>
{{Out}}
<pre>
Welcome to Bulls and Cows!
Your guess of 1234 had 1 bull and 2 cows.
Your guess of 5678 had 0 bulls and 1 cow.
Your guess of 2345 had 0 bulls and 2 cows.
Your guess of 3261 had 1 bull and 2 cows.
Your guess of 4173 had 0 bulls and 3 cows.
Your guess of 8231 had 2 bulls and 0 cows.
Your guess of 7134 had 1 bull and 2 cows.
Your guess of 3461 had 2 bulls and 2 cows.
Congratulations! Your guess of 6431 was correct! You solved this in 9 guesses.
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
include "NSLog.incl"
str15 guess, goal
short x, y
cgRect wndrect
 
begin enum 1
_window
_bullLabel
_cowLabel
_horzLine
_vertLine
_newGameBtn
_alert = 101
end enum
 
void local fn showStr( string as str15 )
short r
x = 20
for r = 1 to string[0]
print %(x,y)chr$( string[r] );
x += 39
next
end fn
 
void local fn NewGame
str15 ch
goal = "" : guess = "" :y = 20
window _window,,wndRect
text ,,fn colorRed
cls
fn showStr( "????" )
do
ch = chr$(rnd(9) or _"0")
if instr$(0, goal, ch) == 0 then goal += ch
until goal[0] == 4
nslog(@"%u",val&(goal)) //unrem for testing
y += 48
end fn
 
local fn SetWindowFrame
CGRect r = fn WindowContentRect( _window )
r.size.height += 32
r.origin.y -= 32
window _window,,r
if ( r.origin.y < 150 )
alert _alert,, @"Too many guesses!",, @"Give up", YES
fn newGame
end if
end fn
 
local fn play( ch as str15 )
short r, bulls = 0, cows = 0
if instr$(0, guess, ch) then exit fn
guess += ch
text,,fn colorDarkGray
fn showStr( guess )
if guess[0] < 4 then exit fn
for r = 1 to 4
if goal[r] == guess[r] then bulls++ : continue
if instr$(0, goal, chr$(guess[r]) ) then cows++
next
select
case bulls == 4
text ,,fn colorRed
print %(x + 31, y)("W I N!")
y = 20 : fn showStr( goal )
case else : print %(x + 35, y)bulls;" "; cows
y += 32 : guess = ""
end select
fn SetWindowFrame
end fn
 
 
void local fn BuildWindow
subclass window _window, @"Bulls and cows", (0,0,311,114), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
wndrect = = fn WindowContentRect( _window )
textlabel _bullLabel, @"🐂", (198,59,38,40)
textlabel _cowLabel, @"🐄", (255,59,38,40)
ControlSetFontWithName( _bullLabel, NULL, 30 )
ControlSetFontWithName( _cowLabel, NULL, 30 )
box _horzLine,, (12,50,287,5), NSBoxSeparator
box _vertLine,, (180,12,5,90), NSBoxSeparator
ViewSetAutoresizingMask( _vertLine, NSViewHeightSizable )
button _newGameBtn,,, @"New Game", (198,13,100,32)
ViewSetAutoresizingMask( _newGameBtn, NSViewMaxYMargin )
text @"menlo bold",24,,fn ColorWindowBackground
end fn
 
void local fn DoDialog( evt as long, tag as long )
select ( evt )
case _windowKeyDown //: stop
short ch = intval( fn EventCharacters )
if ch then fn play( chr$( ch or _"0" ) ):DialogEventSetBool(YES)
case _btnClick : fn NewGame
case _windowWillClose : end
end select
end fn
 
on dialog fn DoDialog
fn buildWindow
fn newGame
 
HandleEvents
</syntaxhighlight>
{{out}}
[[File:Bulls and Cows in FutureBasic.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,195 ⟶ 3,516:
}
}
}</langsyntaxhighlight>
 
=={{header|Golo}}==
<langsyntaxhighlight lang="golo">#!/usr/bin/env golosh
----
This module is the Bulls and Cows game.
Line 2,210 ⟶ 3,530:
 
function main = |args| {
 
while true {
let secret = create4RandomNumbers()
Line 2,218 ⟶ 3,537:
println("(with only the digits 1 to 9 and no repeated digits, for example 2537)")
let guess = readln("guess: ")
let guessResultresult = validateGuess(guess)
if guessResultresult: isValid() {
let bulls, cows = bullsAndOrCows(guessResultresult: digits(), secret)
if bulls is 4 {
println("You win!")
Line 2,228 ⟶ 3,547:
println("cows: " + cows)
} else {
println(guessResultresult: message())
}
}
Line 2,241 ⟶ 3,560:
}
 
union GuessResultResult = {
Valid = { digits }
Invalid = { message }
Line 2,253 ⟶ 3,572:
digits = number: digits()
if digits: exists(|d| -> d is 0) {
return GuessResultResult.Invalid("No zeroes please")
}
if digits: size() isnt 4 {
return GuessResultResult.Invalid("Four digits please")
}
let digitSet = set[ digit foreach digit in digits ]
if digitSet: size() < digits: size() {
return GuessResultResult.Invalid("No duplicate numbers please")
}
} catch(e) {
return GuessResultResult.Invalid("Numbers only please")
}
return GuessResultResult.Valid(digits)
}
 
Line 2,289 ⟶ 3,608:
 
function digits = |this| {
 
var remaining = this
let digits = vector[]
Line 2,298 ⟶ 3,616:
return digits
}
}
}</lang>
</syntaxhighlight>
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">class BullsAndCows {
static void main(args) {
def inputReader = System.in.newReader()
def numberGenerator = new Random()
def targetValue
while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue
def targetStr = targetValue.toString()
def guessed = false
def guesses = 0
while (!guessed) {
def bulls = 0, cows = 0
print 'Guess a 4-digit number with no duplicate digits: '
def guess = inputReader.readLine()
if (guess.length() != 4 || !guess.isInteger() || targetValueIsInvalid(guess.toInteger())) {
continue
}
guesses++
4.times {
if (targetStr[it] == guess[it]) {
bulls++
} else if (targetStr.contains(guess[it])) {
cows++
}
}
if (bulls == 4) {
guessed = true
} else {
println "$cows Cows and $bulls Bulls."
}
}
println "You won after $guesses guesses!"
}
 
static targetValueIsInvalid(value) {
def digitList = []
while (value > 0) {
if (digitList[value % 10] == 0 || digitList[value % 10]) {
return true
}
digitList[value % 10] = true
value = value.intdiv(10)
}
false
}
}
 
</syntaxhighlight>
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (partition, intersect, nub)
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
Line 2,350 ⟶ 3,716:
f (n - 1) (left ++ right) g' (max - 1) (picked : ps)
where (i, g') = randomR (0, max) g
(left, picked : right) = splitAt i l</langsyntaxhighlight>
 
=={{header|Hy}}==
 
<langsyntaxhighlight lang="lisp">(import random)
 
(def +size+ 4)
Line 2,379 ⟶ 3,744:
cows (if (= cows 1) "" "s"))))
(print "A winner is you!")</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
The following works in both Icon and Unicon.
 
<langsyntaxhighlight Uniconlang="unicon">procedure main()
digits := "123456789"
every !digits :=: ?digits
Line 2,408 ⟶ 3,772:
write("\t",bulls," bulls and ",cows," cows")
return (bulls = *num)
end</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'misc'
plural=: conjunction define
Line 2,434 ⟶ 3,797:
end.
smoutput 'you win'
)</langsyntaxhighlight>
 
For example:
 
<langsyntaxhighlight lang="j"> bullcow''
Guess my number: 1234
0 bulls and 1 cow.
Line 2,453 ⟶ 3,816:
Guess my number: 5178
4 bulls and 0 cows.
you win</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java5">import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
Line 2,463 ⟶ 3,825:
public static void main(String[] args){
Random gen= new Random();
int target= 0;
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
String targetStr = target +"";
Line 2,507 ⟶ 3,869:
return false;
}
}</langsyntaxhighlight>
Output:
<pre>Guess a 4-digit number with no duplicate digits: 5834
Line 2,529 ⟶ 3,891:
Guess a 4-digit number with no duplicate digits: 3957
You won after 10 guesses!</pre>
 
 
 
=={{header|JavaScript}}==
=== Spidermonkey version ===
<langsyntaxhighlight lang="javascript">#!/usr/bin/env js
 
function main() {
Line 2,622 ⟶ 3,981:
 
main();
</syntaxhighlight>
</lang>
 
Example game (cheating!):
Line 2,652 ⟶ 4,011:
Bulls: 4, cows: 0
You win! Guesses needed: 8
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
'''Adapted from [[#Wren|Wren]]'''
 
The following program reads the user's input from STDIN, and reads
random digits from /dev/random using the --slurpfile command-line
option. This makes the program more convoluted than would have been
the case had the generation of the initial four-digit pseudo-random
integer been done in a separate step, but it does illustrate how
the limitations of jq's I/O can be circumvented
in this case.
 
In a bash or bash-like environment, a suitable invocation
would be as follows:
<pre>
jq -nrR --slurpfile raw <(< /dev/random tr -cd '0-9' | fold -w 1 | head -n 100) -f bc.jq
</pre>
 
'''bc.jq'''
<syntaxhighlight lang=jq>
# A PRNG for generating a pseudo-random integer in range(0; .).
# $array must be a sufficiently large array of pseudo-random integers in range(0;10).
# $start specifies the position in $array to begin searching.
# Output: {prn, start) where .prn is a PRN in range(0; .) and .start is the corresponding position in $array.
def prn($array; $start):
def a2n: map(tostring) | join("") | tonumber;
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| {$start}
| until( $array[.start: .start + $w] | a2n < $n; .start+=1 )
| {start, prn: ($raw[.start: .start + $w] | a2n)}
end;
 
# Generate a 4-digit PRN from 1234 to 9876 inclusive, with no zeros or repeated digits.
# Global variable: $raw (see documentation for $array above)
def num:
def _num($start):
(8643|prn($raw; $start)) as $prn
| (1234 + $prn.prn)
| . as $n
| tostring
| if (test("0")|not) and ((explode|unique|length) == 4)
then $n
else _num($prn.start+4)
end;
_num(0);
 
def MAX_GUESSES: 20; # say
 
def instructions:
"All guesses should have exactly 4 distinct digits excluding zero.",
"Keep guessing until you guess the chosen number (maximum \(MAX_GUESSES) valid guesses).\n";
 
def play:
num as $num
| ($num|tostring|explode) as $numArray
| { guesses: 0 }
| instructions, "Enter your guess:",
(label $out
| foreach range(0; infinite) as $i (.;
if .bulls == 4 or .guesses == MAX_GUESSES then break $out
else .guess = input
| if .guess == $num then .emit = "You have won with \(.guesses+1) valid guesses!"
else .n = (.guess | try tonumber catch null)
| if .n == null then .emit = "Not a valid number"
elif .guess|test("[+-.]") then .emit = "The guess should not contain a sign or decimal point."
elif .guess|test("0") then .emit = "The guess cannot contain zero."
elif .guess|length != 4 then .emit = "The guess must have exactly 4 digits."
else .guessArray = (.guess | explode )
| if .guessArray | unique | length < 4 then .emit = "All digits must be distinct."
else . + {bulls: 0, cows: 0 }
| reduce range(0; .guessArray|length) as $i ( .;
if $numArray[$i] == .guessArray[$i] then .bulls += 1
elif (.guessArray[$i] | IN($numArray[])) then .cows += 1
else .
end)
| .emit = "Your score for this guess: Bulls = \(.bulls) Cows = \(.cows)"
| .guesses += 1
end
end
end
end;
 
select(.emit).emit,
if .bulls == 4 then "Congratulations!"
elif .guesses == MAX_GUESSES
then "\nYou have now had \(.guesses) valid guesses, the maximum allowed. Bye!"
else "Enter your next guess:"
end ) );
 
play
</syntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function cowsbulls()
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
You get one bull for every right number in the right position.\n
Line 2,685 ⟶ 4,139:
end
end
end</langsyntaxhighlight>
The following version checks thoroughly that the input of the player is constituted of four distincts digits.
<langsyntaxhighlight lang="julia">function bullsandcows ()
bulls = cows = turns = 0
result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
Line 2,703 ⟶ 4,157:
end
println("You win! You succeeded in $turns guesses.")
end</langsyntaxhighlight>
{{Out}}
<pre>julia> bullsandcows()
Line 2,722 ⟶ 4,176:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
<lang scala>// version 1.1.2
 
import java.util.Random
 
const val MAX_GUESSES = 20 // say
 
fun main(args: Array<String>) {
val num = ('1'..'9').shuffled().take(4).joinToString("")
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.")
Line 2,741 ⟶ 4,188:
while (true) {
print("Enter your guess : ")
val guess = readLinereadln().trim()!!
if (guess == num) {
println("You've won with ${++guesses} valid guesses!")
returnbreak
}
val n = guess.toIntOrNull()
Line 2,770 ⟶ 4,217:
}
}
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 2,796 ⟶ 4,243:
=={{header|Lasso}}==
This game uses an HTML form to submit the answer. The random number and history are stored in a session using Lasso's built in session management.
<syntaxhighlight lang="lasso">[
<lang Lasso>[
define randomizer() => {
local(n = string)
Line 2,866 ⟶ 4,313:
'<a href="?restart">Restart</a>'
^}]
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,909 ⟶ 4,356:
5493: Bulls: 4, Cows: 0 - YOU WIN!
Restart</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
 
do while len( secret$) <4
Line 2,974 ⟶ 4,420:
close #w
end
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to ok? :n
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end
Line 2,996 ⟶ 4,441:
(print :bulls "bulls, :cows "cows)
if :bulls = 4 [print [You guessed it!]]
end</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function ShuffleArray(array)
for i=1,#array-1 do
local t = math.random(i, #array)
Line 3,099 ⟶ 4,543:
print("\nGoodbye!")
end
until quit</langsyntaxhighlight>
 
 
Another version:
<syntaxhighlight lang="lua">function createNewNumber ()
math.randomseed(os.time())
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
local tNumb = {} -- list of numbers
for i = 1, 4 do
table.insert(tNumb, math.random(#tNumb+1), table.remove(numbers, math.random(#numbers)))
end
return tNumb
end
 
TNumber = createNewNumber ()
print ('(right number: ' .. table.concat (TNumber) .. ')')
 
function isValueInList (value, list)
for i, v in ipairs (list) do
if v == value then return true end
end
return false
end
 
local nGuesses = 0
 
while not GameOver do
nGuesses = nGuesses + 1
print("Enter your guess (or 'q' to quit): ")
local input
while not input do
input = io.read()
end
if input == "q" then
GameOver = true
return
end
local tInput = {}
for i=1, string.len(input) do
local number = tonumber(string.sub(input,i,i))
if number and not isValueInList (number, tInput) then
table.insert (tInput, number)
end
end
local malformed = false
if not (string.len(input) == 4) or not (#tInput == 4) then
print (nGuesses, 'bad input: too short or too long')
malformed = true
end
if not malformed then
print (nGuesses, 'parsed input:', table.concat(tInput, ', '))
local nBulls, nCows = 0, 0
for i, number in ipairs (tInput) do
if TNumber[i] == number then
nBulls = nBulls + 1
elseif isValueInList (number, TNumber) then
nCows = nCows + 1
end
end
print (nGuesses, 'Bulls: '.. nBulls .. ' Cows: ' .. nCows)
if nBulls == 4 then
print (nGuesses, 'Win!')
GameOver = true
end
end
end</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Game {
Malformed=lambda (a$)->{
Line 3,151 ⟶ 4,660:
}
Game
</syntaxhighlight>
</lang>
 
 
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">BC := proc(n) #where n is the number of turns the user wishes to play before they quit
local target, win, numGuesses, guess, bulls, cows, i, err;
target := [0, 0, 0, 0]:
Line 3,210 ⟶ 4,716:
end if;
return NULL;
end proc:</langsyntaxhighlight>
{{out}}
<pre>
Line 3,223 ⟶ 4,729:
...
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<syntaxhighlight lang="mathematica">digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
=={{header|Mathematica}}==
<lang Mathematica>
digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
Line 3,237 ⟶ 4,741:
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
Print["Guess four digits."]]]]]]]</syntaxhighlight>
</lang>
Output:
<pre>{8, 2, 6, 1}
{8, 2, 6, 1}
3432: 0 bull(s), 1 cow(s).
Illegal input.
8261: You got it!</pre>
</pre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function BullsAndCows
% Plays the game Bulls and Cows as the "game master"
Line 3,309 ⟶ 4,809:
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end</langsyntaxhighlight>
{{out}}
<pre>Welcome to Bulls and Cows!
Line 3,340 ⟶ 4,840:
You win! Bully for you! Only 8 guesses.</pre>
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
numCount = 4 -- number of digits to use
 
Line 3,409 ⟶ 4,909:
format "\nBulls: % Cows: %\n" bulls cows
)
)</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
OK
Rules:
Line 3,432 ⟶ 4,932:
Enter your number: 1357
Bulls: 0 Cows: 1
</syntaxhighlight>
</lang>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")
 
while true
guess = input("Your guess? ").split("")
if guess.len != 4 then
print "Please enter 4 numbers, with no spaces."
continue
end if
bulls = 0
cows = 0
for i in guess.indexes
if secret[i] == guess[i] then
bulls = bulls + 1
else if secret.indexOf(guess[i]) != null then
cows = cows + 1
end if
end for
if bulls == 4 then
print "You got it! Great job!"
break
end if
print "You score " + bulls + " bull" + "s"*(bulls!=1) +
" and " + cows + " cow" + "s"*(cows!=1) + "."
end while</syntaxhighlight>
{{out}}
<pre>Your guess? 2385
You score 0 bulls and 2 cows.
Your guess? 2323
You score 0 bulls and 2 cows.
Your guess? 2211
You score 2 bulls and 1 cow.
...
Your guess? 8542
You score 3 bulls and 0 cows.
Your guess? 8642
You got it! Great job!</pre>
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">BullCow New bull,cow,guess,guessed,ii,number,pos,x
Set number="",x=1234567890
For ii=1:1:4 Do
Line 3,499 ⟶ 5,037:
Your guess: 2907
You guessed 2907. That earns you 4 bulls.
That's a perfect score.</langsyntaxhighlight>
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang="nanoquery">import Nanoquery.Util; random = new(Random)
 
// a function to verify the user's input
def verify_digits(input)
global size
seen = ""
 
if len(input) != size
return false
else
for char in input
if not char in "0123456789"
return false
else if char in seen
return false
end
 
seen += char
end
end
 
return true
end
 
size = 4
chosen = ""
while len(chosen) < size
digit = random.getInt(8) + 1
 
if not str(digit) in chosen
chosen += str(digit)
end
end
 
println "I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order."
println "You need to input a 4 digit, unique digit number as a guess at what I have chosen."
 
guesses = 1
won = false
while !won
print "\nNext guess [" + str(guesses) + "]: "
guess = input()
 
if !verify_digits(guess)
println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
else
if guess = chosen
won = true
else
bulls = 0
cows = 0
for i in range(0, size - 1)
if guess[i] = chosen[i]
bulls += 1
else if guess[i] in chosen
cows += 1
end
end
 
println format(" %d Bulls\n %d Cows", bulls, cows)
guesses += 1
end
end
end
 
println "\nCongratulations you guess correctly in " + guesses + " attempts"</syntaxhighlight>
 
{{out}}
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
You need to input a 4 digit, unique digit number as a guess at what I have chosen.
 
Next guess [1]: 1234
1 Bulls
2 Cows
 
Next guess [2]: 1324
0 Bulls
3 Cows
 
...
 
Next guess [10]: 2534
2 Bulls
2 Cows
 
Next guess [11]: 4532
 
Congratulations you guess correctly in 11 attempts</pre>
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import random, strutils, rdstdinstrformat, sequtils
randomize()
 
proc random(a: string): char = a[random(0..a.len)]
 
const
digitsDigits = "123456789"
DigitSet = {Digits[0]..Digits[^1]}
size = 4
Size = 4
 
proc sample(s: string; n: Positive): string =
var digitsSet: set[char] = {}
## Return a random sample of "n" characters extracted from string "s".
for d in digits: digitsSet.incl d
var s = s
s.shuffle()
result = s[0..<n]
 
proc plural(n: int): string =
var chosen = newString(size)
if n > 1: "s" else: ""
for i in 0..chosen.high: chosen[i] = random(digits)
 
let chosen = Digits.sample(Size)
echo """I have chosen a number from $# unique digits from 1 to 9 arranged in a random order.
 
You need to input a $# digit, unique digit number as a guess at what I have chosen""".format(size, size)
echo &"I have chosen a number from {Size} unique digits from 1 to 9 arranged in a random order."
echo &"You need to input a {Size} digit, unique digit number as a guess at what I have chosen."
 
var guesses = 0
Line 3,526 ⟶ 5,157:
var guess = ""
while true:
guess = readLineFromStdinstdout.write(&"\nNext guess [$#]{guesses}: ".format(guesses)).strip()
if guess.len == size and allCharsInSetstdin.readLine().strip(guess, digitsSet):
if guess.len == Size and allCharsInSet(guess, DigitSet) and guess.deduplicate.len == Size:
break
echo &"Problem, try again. You need to enter $#{Size} unique digits from 1 to 9".format(size)"
if guess == chosen:
echo &"\nCongratulations! youYou guessed correctly in ",{guesses,"} attempts."
break
var bulls, cows = 0
for i in 0 .. <sizeSize:
if guess[i] == chosen[i]: inc bulls
ifelif guess[i] in chosen: inc cows
echo &" $#{bulls} BullsBull{plural(bulls)}\n $#{cows} Cows".formatCow{plural(bulls, cows)}"</langsyntaxhighlight>
 
{{out}}
Sample output:
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
You need to input a 4 digit, unique digit number as a guess at what I have chosen.
1195
 
Next guess [1]: 791234
Problem, try again. You need to enter 4 unique digits from 1 to 9
 
Next guess [1]: 7983
0 Bulls
1 Cows
 
Next guess [2]: 1293
2 Bulls
20 CowsCow
 
Next guess [3]2: 11931256
31 BullsBull
0 Cow
 
Next guess 3: 2378
1 Bull
3 Cows
 
Next guess [4]: 11957238
 
Congratulations you guessed correctly in 4 attempts</pre>
 
Congratulations! You guessed correctly in 4 attempts.</pre>
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec input () =
let s = read_line () in
try
Line 3,612 ⟶ 5,241:
done;
print_endline "Congratulations you guessed correctly";
;;</langsyntaxhighlight>
 
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: bullsAndCows
| numbers guess digits bulls cows |
 
Line 3,634 ⟶ 5,261:
guess filter(#[numbers include]) size bulls - ->cows
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
] ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
The solution at [[#Version_2|Rexx Version 2]] is a valid ooRexx program.
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
Line 3,708 ⟶ 5,333:
fun {Id X} X end
in
{Main}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This simple implementation expects guesses in the form [a,b,c,d].
<langsyntaxhighlight lang="parigp">bc()={
my(u,v,bulls,cows);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
Line 3,722 ⟶ 5,346:
print("You have "bulls" bulls and "cows" cows")
)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program BullCow;
 
{$mode objFPC}
Line 3,913 ⟶ 5,536:
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Data::Random qw(rand_set);
use List::MoreUtils qw(uniq);
 
Line 3,954 ⟶ 5,576:
my $g = shift;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{trans|Python}}
 
{{works with|Rakudo|2015.12}}
 
<lang perl6>my $size = 4;
my @secret = pick $size, '1' .. '9';
 
for 1..* -> $guesses {
my @guess;
loop {
@guess = (prompt("Guess $guesses: ") // exit).comb;
last if @guess == $size and
all(@guess) eq one(@guess) & any('1' .. '9');
say 'Malformed guess; try again.';
}
my ($bulls, $cows) = 0, 0;
for ^$size {
when @guess[$_] eq @secret[$_] { ++$bulls; }
when @guess[$_] eq any @secret { ++$cows; }
}
last if $bulls == $size;
say "$bulls bulls, $cows cows.";
}
 
say 'A winner is you!';</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant N = 4
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\BullsAndCows.exw
-- =============================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (DEV lots of resizing issues)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">score</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">goal</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bulls</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">goal</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">b</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">bulls</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">bits</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">cows</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">bits</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">b</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">label</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
function mask(integer ch)
return power(2,ch-'1')
end function
 
function score(sequence guess, sequence goal)
integer bits = 0, bulls = 0, cows = 0, b
for i=1 to N do
b = goal[i]
if guess[i]=b then
bulls += 1
else
bits += mask(b)
end if
end for
for i=1 to N do
b = mask(guess[i])
if and_bits(bits,b)!=0 then
cows += 1
bits -= b
end if
end for
return {bulls, cows}
end function
 
procedure game()
sequence tgt = shuffle("123456789")[1..N]
integer attempt = 1, bulls = 0, cows
sequence guess
while bulls<N do
while 1 do
printf(1,"Enter a %d digit number using only the digits 1 to 9:",N)
guess = trim(gets(0))
if length(guess)=N then exit end if
if length(guess)=1 and lower(guess)="q" then
puts(1,"\nthe secret number was:"&tgt)
{} = wait_key()
abort(0)
end if
printf(1," - length is not %d (enter q to give up)\n",N)
end while
{bulls, cows} = score(guess,tgt)
printf(1," Guess %-2d (%s) bulls:%d cows:%d\n",{attempt,guess,bulls,cows})
attempt += 1
end while
puts(1,"Well done!\n")
end procedure
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">" Guess %-2d (%s) bulls:%d cows:%d\n"</span><span style="color: #0000FF;">,</span>
game()</lang>
<span style="color: #000000;">tgt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"123456789"</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">N</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">attempt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*guess*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">g</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">4</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">4</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">score</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tgt</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">&</span>
<span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">attempt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cows</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">bulls</span><span style="color: #0000FF;">=</span><span style="color: #000000;">N</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">"\nWell done!"</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">attempt</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"SIZE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">label</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter %d digits 1 to 9 without duplication"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">N</span><span style="color: #0000FF;">}))</span>
<span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"GAP=10,NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})},</span><span style="color: #008000;">"MARGIN=5x5"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">`TITLE="Bulls and Cows"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<small>(as shown in the res label)</small>
<pre>
Enter a 4 digit number using only the digits 1 to 9:5739 Guess 1 (5739) bulls:0 cows:3
Enter a 4 digit number using only the digits 1 to 9:7193 Guess 2 (7193) bulls:2 cows:1
Enter a 4 digit number using only the digits 1 to 9:3495 Guess 3 (3495) bulls:0 cows:2
Enter a 4 digit number using only the digits 1 to 9:7983 Guess 4 (7983) bulls:3 cows:0
Enter a 4 digit number using only the digits 1 to 9:7963 Guess 5 (7963) bulls:3 cows:0
Enter a 4 digit number using only the digits 1 to 9:7923 Guess 6 (7923) bulls:4 cows:0
 
Well done!
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$size = 4;
 
Line 4,085 ⟶ 5,706:
preg_match("/^[1-9]{{$size}}$/", $g);
}
?></langsyntaxhighlight>
=={{header|Picat}}==
{{trans|Python}}
<syntaxhighlight lang="picat">main =>
Digits = to_array("123456789"),
Size = 4,
random_sample(Size,Size,[],ChosenIndecies),
Chosen = {Digits[I] : I in ChosenIndecies},
printf("I have chosen a number from %d unique digits from 1 to 9 arranged in a random order.\n", Size),
printf("You need to input a %d digit, unique digit number as a guess at what I have chosen.\n", Size),
guess(Chosen,Size,1).
 
guess(Chosen,Size,NGuess) =>
Input = read_line(),
Guess = Input.to_array(),
if len(Guess) != Size || len(sort_remove_dups(Input)) != Size || (member(D, Input), (D @< '1' || D @> '9')) then
printf("Problem, try again. You need to enter %d unique digits from 1 to 9\n", Size),
guess(Chosen,Size,NGuess)
elseif Guess == Chosen then
printf("\nCongratulations you guessed correctly in %d attempts\n", NGuess)
else
Bulls = sum([cond(Chosen[I] == Guess[I], 1, 0) : I in 1..Size]),
Cows = sum([cond(member(Chosen[I], Input), 1, 0) : I in 1..Size]),
printf("%d Bulls\n%d Cows\n", Bulls, Cows),
guess(Chosen, Size, NGuess+1)
end.
 
random_sample(_N,0,Chosen0,Chosen) => Chosen = Chosen0.
random_sample(N,I,Chosen0,Chosen) =>
R = random() mod N + 1,
(not member(R, Chosen0) ->
random_sample(N,I-1,[R|Chosen0],Chosen)
;
random_sample(N,I,Chosen0,Chosen)
).
</syntaxhighlight>
=={{header|PicoLisp}}==
<langsyntaxhighlight lang="lisp">(de ok? (N)
(let D (mapcar 'format (chop N))
(and (num? N)
Line 4,108 ⟶ 5,763:
(pack Bulls " bulls, " Cows " cows") ) ) )
" Bad guess! (4 unique digits, 1-9)" ) ) )
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
Line 4,159 ⟶ 5,813:
 
Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,175 ⟶ 5,829:
You won after 7 guesses.
</pre>
 
 
=={{header|Processing}}==
Produces both a console transcript and a GUI interface to the game.
Creates a new game each time the guess is correct; tracks number of games won.
<langsyntaxhighlight lang="processing">IntDict score;
StringList choices;
StringList guess;
Line 4,241 ⟶ 5,893:
}
return result;
}</langsyntaxhighlight>
 
 
=={{header|Prolog}}==
Works with SWI-Prolog 6.1.8 (for predicate '''foldl'''), module lambda, written by '''Ulrich Neumerkel''' found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl and module clpfd written by '''Markus Triska'''.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
:- use_module(library(clpfd)).
 
Line 4,302 ⟶ 5,952:
Solution, 0, TT),
Cows is TT - Bulls.
</syntaxhighlight>
</lang>
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Define.s secret, guess, c
Define.i bulls, cows, guesses, i
 
Line 4,373 ⟶ 6,023:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">'''
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
Line 4,408 ⟶ 6,057:
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)</langsyntaxhighlight>
Sample output:
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
Line 4,423 ⟶ 6,072:
 
Congratulations you guessed correctly in 2 attempts</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Const MaxDigit = 4, Min = 1, Max = 9
Dim As String NumberToGuess, NumberToTest, Newdigit, Result
Dim As Integer Counter, Number
Randomize Timer
Do
Counter = Counter + 1
Newdigit = _Trim$(Str$(Int(Rnd * Max) + Min))
If InStr(NumberToGuess, Newdigit) = 0 Then NumberToGuess = NumberToGuess + Newdigit Else Counter = Counter - 1
Loop While Counter < MaxDigit
Print NumberToGuess 'debug output
Do While NumberToGuess <> NumberToTest
Input "Please enter your guess of 4 digits... ", Number
NumberToTest = _Trim$(Str$(Number))
If NumberToGuess <> NumberToTest Then
Result = ""
For Counter = 1 To 4 Step 1
Newdigit = Mid$(NumberToTest, Counter, 1)
If InStr(NumberToGuess, Newdigit) - Counter = 0 Then
Result = Result + " Bull "
ElseIf InStr(NumberToGuess, Newdigit) > 0 Then
Result = Result + " Cow "
End If
Next Counter
Print NumberToTest, Result
Else
Print "You Win!"
End If
Loop
</syntaxhighlight>
 
=={{header|Quackery}}==
 
<code>transpose</code> is defined at [[Matrix transposition#Quackery]].
 
<syntaxhighlight lang="Quackery"> [ size 4 = dup not if
[ say "Must be four digits." cr ] ] is 4chars ( $ --> b )
 
[ true swap witheach
[ char 1 char 9 1+ within not if
[ say "Must be 1-9 only." cr
not conclude ] ] ] is 1-9 ( $ --> b )
 
[ 0 9 of
swap witheach
[ 1 unrot char 1 - poke ]
0 swap witheach +
4 = dup not if
[ say "Must all be different." cr ] ] is all-diff ( $ --> b )
 
 
[ $ "Guess four digits, 1-9, no duplicates: "
input
dup 4chars not iff drop again
dup 1-9 not iff drop again
dup all-diff not iff drop again ] is guess ( $ --> $ )
 
[ $ "123456789" shuffle 4 split drop ] is rand$ ( --> $ )
 
[ 2 pack transpose
[] swap witheach
[ dup unpack != iff
[ nested join ]
else drop ]
dup [] != if
[ transpose unpack ]
4 over size - ] is -bulls ( $ $ --> $ $ n )
 
[ join sort
0 swap
behead swap witheach
[ tuck = if [ dip 1+ ] ]
drop ] is cows ( $ $ --> n )
 
[ say "Guess the four numbers." cr cr
say "They are all different and"
say " between 1 and 9 inclusive." cr cr
randomise rand$
[ guess
over -bulls
dup 4 = iff say "Correct." done
dup echo 1 = iff
[ say " bull." cr ]
else
[ say " bulls." cr ]
cows
dup echo 1 = iff
[ say " cow." cr ]
else
[ say " cows." cr ]
again ]
cr drop 2drop ] is play ( --> )</syntaxhighlight>
 
{{out}}
 
<pre>Guess the four numbers.
 
They are all different and between 1 and 9 inclusive.
 
Guess four digits, 1-9, no duplicates: 1234
0 bulls.
0 cows.
Guess four digits, 1-9, no duplicates: 5678
1 bull.
3 cows.
Guess four digits, 1-9, no duplicates: 5786
1 bull.
3 cows.
Guess four digits, 1-9, no duplicates: 5867
0 bulls.
4 cows.
Guess four digits, 1-9, no duplicates: 7658
2 bulls.
2 cows.
Guess four digits, 1-9, no duplicates: 7685
0 bulls.
4 cows.
Guess four digits, 1-9, no duplicates: 6758
Correct.
</pre>
 
=={{header|R}}==
{{works with|R|2.8.1}}
<langsyntaxhighlight Rlang="r">target <- sample(1:9,4)
bulls <- 0
cows <- 0
Line 4,444 ⟶ 6,214:
} else {print("Malformed input!")}
}
print(paste("You won in",attempts,"attempt(s)!"))</langsyntaxhighlight>
 
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 4,507 ⟶ 6,275:
(main-loop state (add1 step))))))))))
 
(main-loop game 0)</langsyntaxhighlight>
 
Output:
Line 4,530 ⟶ 6,298:
You won after 8 guesses.
</pre>
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Python}}
 
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" line>my $size = 4;
my @secret = pick $size, '1' .. '9';
 
for 1..* -> $guesses {
my @guess;
loop {
@guess = (prompt("Guess $guesses: ") // exit).comb;
last if @guess == $size and
all(@guess) eq one(@guess) & any('1' .. '9');
say 'Malformed guess; try again.';
}
my ($bulls, $cows) = 0, 0;
for ^$size {
when @guess[$_] eq @secret[$_] { ++$bulls; }
when @guess[$_] eq any @secret { ++$cows; }
}
last if $bulls == $size;
say "$bulls bulls, $cows cows.";
}
 
say 'A winner is you!';</syntaxhighlight>
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
Red[]
a: "0123456789"
Line 4,549 ⟶ 6,343:
]
print "You won!"
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
This game is also known as:
Line 4,558 ⟶ 6,351:
:::::::* Master Mind
===version 1===
'''See version 2 for a better formatted progtam that also runs on ooRexx.'''<br>
This REXX version of Bulls and Cows doesn't allow repeated digits (in the computer-generated number),
<br>nor the use of the zero digit.
Line 4,564 ⟶ 6,358:
<br>and also change the prompt message.
<br>The REXX statement that contains the &nbsp; '''translate''' &nbsp; statement can be removed if repeated digits aren't allowed.
<langsyntaxhighlight lang="rexx">/*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
?=; do until length(?)==4; r= random(1, 9) /*generate a unique four-digit number. */
if pos(r, ?)\==0 then iterate; ?= ? || r /*don't allow a repeated digit/numeral. */
end /*until ?=? || r length*/ /*add random[↑] digit bybuilds concatenation.a unique four-digit number*/
$= '──────── [Bulls & Cows] ' end /*until length ···*/ /*a [↑]literal that buildsis apart uniqueof four-digitthe numprompt. */
do until bulls==4; say /*play until guessed or enters "Quit".*/
$= '──────── [Bulls & Cows] '
say $ 'Please enter a 4-digit guess (with no zeroes) [or Quit]:'
do until bulls==4; say /*play until guessed or enters "QUIT".*/
pull n; n=space(n, say0); $ if abbrev('PleaseQUIT', entern, a1) 4-digit guessthen (withexit no zeroes) /*user wants [orto Quit]:'quit?*/
q=?; L= pull length(n); n bulls=space(n, 0); ifcows= abbrev('QUIT',0 n,/*initialize 1)some REXX variables. then exit /*wants to quit ?*/
qdo j=?; 1 for L=length(n); bulls=0; if cows=0substr(n, j, /*initialize1)\==substr(q, somej, REXX variables.1) then iterate /*is bull?*/
bulls= bulls +1; q= overlay(., q, j) /*bump the bull count; disallow for cow.*/
 
end /*j*/ /* [↑] bull count───────────────────────*/
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 /*is cow.? */
do k=1 for L; end _= /*j*/substr(n, k, 1); if pos(_, q)==0 then /* [↑] bull count────────~─────────*/iterate
cows=cows + 1; q= translate(q, , _) /*bump the cow count; allow mult digits.*/
/*cow ?*/
end /*k*/ do k=1 for L; _=substr(n, k, 1); if/* pos(_,[↑] q)==0 cow then iteratecount───────────────────────*/
say; cows=cows + 1; q=translate(q, , _) @= /*bump'You cow count;got' allow mult digits.*/bulls
if L\==0 & bulls\==4 then say $ @ 'bull's(bulls) "and" cows 'cow's(cows).
end /*k*/ /* [↑] cow count─────────~────────*/
end say; @= 'You got' /*until bulls*/
say " ┌─────────────────────────────────────────┐"
if L\==0 & bulls\==4 then say $ @ 'bull's(bulls) "and" cows 'cow's(cows).
say " │ │"
end /*until bulls==4*/
say " │ Congratulations, you've guessed it !! │"
say
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. */</langsyntaxhighlight><br><br>
 
===Version 2===
<langsyntaxhighlight lang="rexx">
/*REXX program to play the game of "Bulls & Cows". *******************
* Changes from Version 1:
Line 4,698 ⟶ 6,489:
 
ser: Say '*** error ***' arg(1); Return
</syntaxhighlight>
</lang>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Bulls and cows
 
Line 4,741 ⟶ 6,532:
see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
end
</syntaxhighlight>
</lang>
=={{header|RPL}}==
{{works with|HP|49}}
« CLEAR 0 ""
1 4 '''START'''
'''WHILE''' RAND 9 * CEIL R→I →STR DUP2 POS '''REPEAT''' '''DROP''' END +
'''NEXT'''
→ count solution
« '''DO''' 1 CF
'''DO''' "Guess? [CONT]" PROMPT →STR
'''CASE'''
DUP SIZE 4 ≠ '''THEN''' DROP "Not 4 characters" 1 DISP 0.5 WAIT '''END'''
{ 9 } 0 CON
1 4 '''FOR''' j
OVER j DUP SUB STR→
'''IFERR''' 1 PUT '''THEN''' 3 DROPN "Invalid character" 1 DISP 0.5 WAIT '''END'''
'''NEXT'''
DUP 1 CON DOT 4 ≠ '''THEN''' DROP "Repeated digits" 1 DISP 0.5 WAIT '''END'''
1 SF
'''END'''
'''UNTIL''' 1 FS? '''END'''
" → " + 0
1 4 '''FOR''' j
solution PICK3 j DUP SUB POS
'''IF''' DUP '''THEN''' IF j == '''THEN''' 1 '''ELSE''' .1 '''END END''' +
'''NEXT'''
SWAP OVER + 'count' INCR DROP
'''UNTIL''' SWAP 4 == '''END'''
count "guess" →TAG
» » '<span style="color:blue">BU&CO</span>' ST0
 
=={{header|Ruby}}==
Inspired by Tcl
{{works with|Ruby|1.8.7+}}
<langsyntaxhighlight lang="ruby">def generate_word(len)
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
end
Line 4,786 ⟶ 6,606:
puts "that guess has %d bulls and %d cows" % score(word, guess)
end
puts "you guessed correctly in #{count} tries."</langsyntaxhighlight>
 
Inspired by Python
{{works with|Ruby|2.0+}}
<langsyntaxhighlight lang="ruby">size = 4
secret = [*'1' .. '9'].sample(size)
guess = nil
Line 4,824 ⟶ 6,644:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">use std::io;
use rand::{Rng,thread_rng};
 
Line 4,909 ⟶ 6,729:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.util.Random
 
object BullCow {
Line 4,953 ⟶ 6,772:
 
def hasDups(input:List[Int])=input.size!=input.distinct.size
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|any R6RS Scheme}}
 
<langsyntaxhighlight lang="scheme">
 
;generate a random non-repeating list of 4 digits, 1-9 inclusive
Line 5,025 ⟶ 6,843:
 
(bull-cow (get-num))
</syntaxhighlight>
</lang>
 
=== Sample game play ===
Line 5,052 ⟶ 6,870:
You win!
</pre>
=={{header|Scratch}}==
 
Scratch is a graphical programming language. Follow the link to see an example solution for Bulls and Cows<br>
[https://scratch.mit.edu/projects/370296926/ '''Scratch - Bulls and Cows''']<br>
<br>
The program "says" the score of the current guess and uses a list to display previous guesses.<br>
Malformed guesses are rejected for the following reasons:
* Guess is longer or shorter than 4 characters
* Guess contains character other than the digits 1 - 9
* Guess contains a digit more than once (i.e. 3484 - this would be rejected because "4" appears in the guess two times)
<br>
Since Scratch is an educational language, I've included comments in the code to explain what the program is doing.<br>
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 5,102 ⟶ 6,930:
until guess = chosen;
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,120 ⟶ 6,948:
Congratulations you guessed correctly in 4 attempts
</pre>
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">repeat forever
repeat forever
put random(1111,9999) into num
if character 1 of num is not equal to character 2 of num
if character 1 of num is not equal to character 3 of num
if character 1 of num is not equal to character 4 of num
if character 2 of num is not equal to character 3 of num
if character 2 of num is not equal to character 4 of num
if character 3 of num is not equal to character 4 of num
if num does not contain 0
exit repeat
end if
end if
end if
end if
end if
end if
end if
end repeat
set description to "Guess the 4 digit number" & newline & "- zero's excluded" & newline & "- each digit is unique" & newline & newline & "Receive 1 Bull for each digit that equals the corresponding digit in the random number." & newline & newline & "Receive 1 Cow for each digit that appears in the wrong position." & newline
repeat forever
repeat forever
Ask "Guess the number" title "Bulls & Cows" message description
put it into guess
if number of characters in guess is equal to 4
exit repeat
else if guess is ""
Answer "" with "Play" or "Quit" title "Quit Bulls & Cows?"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
end if
end repeat
set score to {
bulls: {
qty: 0,
values: []
},
cows: {
qty: 0,
values: []
}
}
repeat the number of characters in num times
if character the counter of guess is equal to character the counter of num
add 1 to score.bulls.qty
insert character the counter of guess into score.bulls.values
else
if num contains character the counter of guess
if character the counter of guess is not equal to character the counter of num
if score.bulls.values does not contain character the counter of guess and score.cows.values does not contain character the counter of guess
add 1 to score.cows.qty
insert character the counter of guess into score.cows.values
end if
end if
end if
end if
end repeat
set showScores to "Your score is:" & newline & newline & "Bulls:" && score.bulls.qty & newline & newline & "Cows:" && score.cows.qty
if guess is not equal to num
Answer showScores with "Guess Again" or "Quit" title "Score"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
else
set winShowScores to showScores & newline & newline & "Your Guess:" && guess & newline & "Random Number:" && num & newline
Answer winShowScores with "Play Again" or "Quit" title "You Win!"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
exit repeat
end if
end repeat
end repeat</syntaxhighlight>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program bulls_and_cows;
setrandom(0);
 
print("Bulls and cows");
print("--------------");
print;
 
secret := make_secret();
 
loop do
guess := read_guess();
tries +:= 1;
bulls := count_bulls(guess, secret);
cows := count_cows(guess, secret);
print(bulls, "bulls,", cows, "cows.");
if bulls = 4 then
print("You win! Tries:", tries);
exit;
end if;
end loop;
 
proc make_secret();
digits := [];
loop for i in [1..4] do
loop until not digit in digits do
digit := 1 + random(8);
end loop;
digits with:= digit;
end loop;
return digits;
end proc;
 
proc read_guess();
loop do
putchar("Guess? ");
flush(stdout);
guess := getline(stdin);
if exists d in guess | not d in "123456789" then
print("invalid input:", d);
elseif #guess /= #{d : d in guess} then
print("no duplicates allowed");
elseif #guess /= 4 then
print("need 4 digits");
else
exit;
end if;
end loop;
return [val d : d in guess];
end proc;
 
proc count_bulls(guess, secret);
return #[i : i in [1..4] | guess(i) = secret(i)];
end proc;
 
proc count_cows(guess, secret);
return #[d : d in guess | d in secret] - count_bulls(guess, secret);
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Bulls and cows
--------------
 
Guess? 1234
0 bulls, 1 cows.
Guess? 5678
2 bulls, 1 cows.
Guess? 5978
2 bulls, 0 cows.
Guess? 5968
1 bulls, 1 cows.
Guess? 5976
1 bulls, 1 cows.
Guess? 6978
3 bulls, 0 cows.
Guess? 6971
2 bulls, 0 cows.
Guess? 6918
2 bulls, 0 cows.
Guess? 1978
2 bulls, 0 cows.
Guess? 6178
3 bulls, 0 cows.
Guess? 6278
3 bulls, 0 cows.
Guess? 6378
4 bulls, 0 cows.
You win! Tries: 12</pre>
=={{header|Shale}}==
 
<syntaxhighlight lang="shale">#!/usr/local/bin/shale
 
maths library
file library
string library
 
n0 var
n1 var
n2 var
n3 var
g0 var
g1 var
g2 var
g3 var
 
init dup var {
c guess:: var
} =
 
getNum dup var {
random maths::() 15 >> 9 % 1 +
} =
 
game dup var {
haveWon dup var false =
ans var
i var
c var
b var
 
c guess:: 0 =
 
n0 getNum() =
n1 getNum() =
{ n1 n0 == } {
n1 getNum() =
} while
n2 getNum() =
{ n2 n0 == n2 n1 == or } {
n2 getNum() =
} while
n3 getNum() =
{ n3 n0 == n3 n1 == n3 n2 == or or } {
n3 getNum() =
} while
 
"New game" println
{ haveWon not } {
"> " print
stdin file:: fgets file::() {
ans swap atoi string::() =
g3 ans 10 % =
g2 ans 10 / 10 % =
g1 ans 100 / 10 % =
g0 ans 1000 / 10 % =
g0 0 > g0 10 < and g1 0 > g1 10 < and g2 0 > g2 10 < and g3 0 > g3 10 < and and and and {
c 0 =
b 0 =
 
g0 n0 == {
b++
} {
g0 n1 == g0 n2 == g0 n3 == or or { c++ } ifthen
} if
 
g1 n1 == {
b++
} {
g1 n0 == g1 n2 == g1 n3 == or or { c++ } ifthen
} if
 
g2 n2 == {
b++
} {
g2 n0 == g2 n1 == g2 n3 == or or { c++ } ifthen
} if
 
g3 n3 == {
b++
} {
g3 n0 == g3 n1 == g3 n2 == or or { c++ } ifthen
} if
 
i c guess:: =
i.value guess:: guess:: defined not {
i.value guess:: guess:: var
i.value cow:: guess:: var
i.value bull:: guess:: var
} ifthen
i.value guess:: guess:: ans =
i.value cow:: guess:: c =
i.value bull:: guess:: b =
c guess::++
 
"Go Guess Cows Bulls" println
i 0 =
{ i c guess:: < } {
i.value bull:: guess:: i.value cow:: guess:: i.value guess:: guess:: i 1 + "%2d %d %4d %5d\n" printf
i++
} while
 
b 4 == { haveWon true = } ifthen
} {
"Illegal input" println
} if
} {
0 exit
} if
} while
 
} =
 
play dup var {
{ true } {
game()
} while
} =
 
init()
play()</syntaxhighlight>
 
{{out}}
 
<pre>New game
> 1234
Go Guess Cows Bulls
1 1234 2 0
> 2345
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
> 3456
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
3 3456 0 2
> 4567
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
3 3456 0 2
4 4567 1 0
> 5678
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
3 3456 0 2
4 4567 1 0
5 5678 1 1
> 6789
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
3 3456 0 2
4 4567 1 0
5 5678 1 1
6 6789 1 0
> 3158
Go Guess Cows Bulls
1 1234 2 0
2 2345 2 0
3 3456 0 2
4 4567 1 0
5 5678 1 1
6 6789 1 0
7 3158 0 4
New game
></pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var size = 4
var num = @(1..9).shuffle.first(size)
 
Line 5,157 ⟶ 7,321:
 
"Bulls: %d; Cows: %d\n".printf(bulls, cows)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,169 ⟶ 7,333:
You did it in 4 attempts!
</pre>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Object subclass: BullsCows [
|number|
BullsCows class >> new: secretNum [ |i|
Line 5,229 ⟶ 7,392:
'Do you want to play again? [y/n]' display.
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ].</langsyntaxhighlight>
 
 
=={{header|Smart BASIC}}==
<langsyntaxhighlight lang="smart BASICbasic">
'by rbytes, January 2017
OPTION BASE 1
Line 5,321 ⟶ 7,482:
END DEF
END
</syntaxhighlight>
</Lang>
 
=={{header|Swift}}==
{{works with|Swift|5.7}}
 
This is the same as the original solution but takes advantage of Swift 5's richer standard library to clean things up a bit.
 
<syntaxhighlight lang="swift">func generateRandomNumArray(numDigits: Int = 4) -> [Character]
{
guard (1 ... 9).contains(numDigits) else { fatalError("number out of range") }
 
return Array("123456789".shuffled()[0 ..< numDigits])
}
 
func parseGuess(_ guess: String, numDigits: Int = 4) -> String?
{
guard guess.count == numDigits else { return nil }
// Only digits 0 to 9 allowed, no Unicode fractions or numbers from other languages
let guessArray = guess.filter{ $0.isASCII && $0.isWholeNumber }
 
guard Set(guessArray).count == numDigits else { return nil }
 
return guessArray
}
 
func pluralIfNeeded(_ count: Int, _ units: String) -> String
{
return "\(count) " + units + (count == 1 ? "" : "s")
}
 
var guessAgain = "y"
while guessAgain == "y"
{
let num = generateRandomNumArray()
var bulls = 0
var cows = 0
 
print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")
 
if let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr)
{
for (guess, actual) in zip(guess, num)
{
if guess == actual
{
bulls += 1
}
else if num.contains(guess)
{
cows += 1
}
}
 
print("Actual number: " + num)
print("Your score: \(pluralIfNeeded(bulls, "bull")) and \(pluralIfNeeded(cows, "cow"))\n")
print("Would you like to play again? (y): ")
 
guessAgain = readLine(strippingNewline: true)?.lowercased() ?? "n"
}
else
{
print("Invalid input")
}
}
</syntaxhighlight>
 
<langsyntaxhighlight lang="swift">import Foundation
 
func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
Line 5,383 ⟶ 7,605:
exit(0)
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,401 ⟶ 7,623:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc main {} {
fconfigure stdout -buffering none
set length 4
Line 5,485 ⟶ 7,707:
}
 
main</langsyntaxhighlight>
=={{header|Transd}}==
{{trans|C++}}
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
 
contains-duplicates: (λ s String() -> Bool()
(with str String(s) (sort str)
(ret (neq (find-adjacent str) (end str))))
),
 
play: (λ locals:
syms "0123456789"
len 4
thenum String()
guess String()
 
(shuffle syms)
(= thenum (substr syms 0 len))
(textout "Your guess: ")
(while (getline guess)
(if (eq guess "q") break)
(if (or (neq (size guess) len)
(neq (find-first-not-of guess syms) -1)
(contains-duplicates guess))
(lout guess " is not valid guess")
(textout "Your guess: ")
continue
)
(with bulls 0 cows 0 pl 0
(for i in Range(len) do
(= pl (index-of thenum (subn guess i)))
(if (eq pl i) (+= bulls 1)
elsif (neq pl -1) (+= cows 1))
)
(lout "bulls: " bulls ", cows: " cows)
(if (eq bulls len)
(lout "Congratulations! You have found out the number!")
(ret null)
else (textout "Your guess: "))
)
)
(lout "You quit the game.")
),
 
_start: (λ locals: s String()
(lout "Welcome to \"Bulls and cows\"!")
(while true
(while true
(textout "Do you want to play? (yes|no) : ")
(getline s)
(if (not (size s))
(lout "Didn't receive an answer. Exiting.") (exit)
elsif (== (sub (tolower s) 0 1) "n") (lout "Bye!")(exit)
elsif (== (sub (tolower s) 0 1) "y") break
else (lout "(Hint: \"yes\" or \"no\".)"))
)
(play)
(lout "Another game?")
)
)
}</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE tuscript
SET nr1=RANDOM_NUMBERS (1,9,1)
Line 5,526 ⟶ 7,811:
ENDIF
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,541 ⟶ 7,826:
BINGO
</pre>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Local(2) ' Let's use no globals
 
Proc _Initialize ' Get our secret number
Line 5,620 ⟶ 7,904:
Next ' Increment with valid digits
Next
Return (c@) ' Return number of valid digits</langsyntaxhighlight>
The addition of strings allows for much simpler code.
<syntaxhighlight lang="text">Do
s = Str(1234 + RND(8643))
Until FUNC(_Check(s))
Next
 
Do
Do
g = Ask("Enter your guess: ")
If (Val(g) = Info("nil")) + (Len(g) # 4) Then Continue
Until FUNC(_Check(g))
Loop
 
b = 0 : c = 0
 
For i = 0 To 3
For j = 0 to 3
If Peek(s, i) = Peek(g, j) Then
If i = j Then
b = b + 1
Else
c = c + 1
EndIf
EndIf
Next
Next
 
Print "You scored ";b;" bulls and ";c; " cows.\n"
 
Until b = 4
Loop
End
 
_Check
Param (1)
Local (2)
 
b@ = 0
 
For c@ = 0 To 3
If Peek(a@, c@) = Ord ("0") Then Unloop : Return (0)
If And(b@, 2^(Peek(a@, c@) - Ord ("0"))) Then Unloop : Return (0)
b@ = b@ + 2^(Peek(a@, c@) - Ord ("0"))
Next
Return (1)</syntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|bash|3}}
 
<langsyntaxhighlight lang="bash">#!/bin/bash
 
rand() {
Line 5,774 ⟶ 8,102:
[ "${guess}" == "${secret}" ] && echo "You win!" && exit
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
done</langsyntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 5,852 ⟶ 8,179:
AskToUser = strIn
End Function
</syntaxhighlight>
</lang>
=={{header|VBScript}}==
VBS functions return variants. I use t to return a single error value or a pair bulls, cows on result<br />
VBS does'nt have a continue so i used the classic do loop inside do loop in the main program
<syntaxhighlight lang="vb">
randomize timer
fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same")
p=dopuzzle()
wscript.echo "Bulls and Cows. Guess my 4 figure number!"
do
do
wscript.stdout.write vbcrlf & "your move ": s=trim(wscript.stdin.readline)
c=checkinput(s)
if not isarray (c) then wscript.stdout.write fail(c) :exit do
bu=c(0)
wscript.stdout.write "bulls: " & c(0) & " | cows: " & c(1)
loop while 0
loop until bu=4
wscript.stdout.write vbcrlf & "You won! "
 
 
function dopuzzle()
dim b(10)
for i=1 to 4
do
r=fix(rnd*10)
loop until b(r)=0
b(r)=1:dopuzzle=dopuzzle+chr(r+48)
next
end function
 
function checkinput(s)
dim c(10)
bu=0:co=0
if len(s)<>4 then checkinput=0:exit function
for i=1 to 4
b=mid(s,i,1)
if instr("0123456789",b)=0 then checkinput=1 :exit function
if c(asc(b)-48)<>0 then checkinput=2 :exit function
c(asc(b)-48)=1
for j=1 to 4
if asc(b)=asc(mid(p,j,1)) then
if i=j then bu=bu+1 else co=co+1
end if
next
next
checkinput=array(bu,co)
end function
</syntaxhighlight>
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">Buf_Switch(Buf_Free)
#90 = Time_Tick // seed for random number generator
#91 = 10 // random numbers in range 0 to 9
Line 5,901 ⟶ 8,275:
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">Imports System
Imports System.Text.RegularExpressions
 
Line 5,960 ⟶ 8,333:
Console.WriteLine("The number was guessed in {0} attempts. Congratulations!", attempt)
End Sub
End Module</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import rand
import os
 
fn main() {
valid := ['1','2','3','4','5','6','7','8','9']
mut value := []string{}
mut guess, mut elem := '', ''
mut cows, mut bulls := 0, 0
println('Cows and Bulls')
println('Guess four digit numbers of unique digits in the range 1 to 9.')
println('A correct digit, but not in the correct place is a cow.')
println('A correct digit, and in the correct place is a bull.')
// generate pattern
for value.len < 4 {
elem = rand.string_from_set('123456789', 1)
if value.any(it == elem) == false {
value << elem
}
}
// start game
input: for _ in 0..3 {
guess = os.input('Guess: ').str()
// deal with malformed guesses
if guess.len != 4 {println('Please input a four digit number.') continue input}
for val in guess {
if valid.contains(val.ascii_str()) == false {
{println('Please input a number between 1 to 9.') continue input}
}
if guess.count(val.ascii_str()) > 1 {
{println('Please do not repeat the same digit.') continue input}
}
}
// score guesses
for idx, gval in guess {
match true {
gval.ascii_str() == value[idx] {
bulls++
println('${gval.ascii_str()} was correctly guessed, and in the correct location! ')
 
}
gval.ascii_str() in value {
cows++
println('${gval.ascii_str()} was correctly quessed, but not in the exact location! ')
}
else {}
}
if bulls == 4 {println('You are correct and have won!!! Congratulations!!!') exit(0)}
}
println('score: bulls: $bulls cows: $cows')
}
println('Only 3 guesses allowed. The correct value was: $value')
println('Sorry, you lost this time, try again.')
}
</syntaxhighlight>
 
{{out}}
<pre>
Cows and Bulls
Guess four digit numbers of unique digits in the range 1 to 9.
A correct digit, but not in the correct place is a cow.
A correct digit, and in the correct place is a bull.
Guess: 2673
6 was correctly quessed, but not in the exact location!
score: bulls: 0 cows: 1
Guess: 1658
6 was correctly quessed, but not in the exact location!
5 was correctly quessed, but not in the exact location!
8 was correctly quessed, but not in the exact location!
score: bulls: 0 cows: 4
Guess: 6859
6 was correctly quessed, but not in the exact location!
8 was correctly guessed, and in the correct location!
5 was correctly quessed, but not in the exact location!
score: bulls: 1 cows: 6
Only 3 guesses allowed. The correct value was: ['5', '8', '4', '6']
Sorry, you lost this time, try again.
</pre>
 
=={{header|VTL-2}}==
<syntaxhighlight lang="VTL2">10 I=1
20 J=1
30 :I)='/10*0+%
40 #=:I)=0*30+(0<:I)*70
50 #=:I)=:J)*20
60 J=J+1
70 #=J<I*50
80 I=I+1
90 #=4>I*20
100 ?="BULLS AND COWS"
110 ?="--------------"
120 ?=""
125 T=0
130 T=T+1
140 ?="GUESS? ";
150 G=?
160 #=G<1234+(G>9877)*510
170 I=8
180 G=G/10
190 :I)=%
200 I=I-1
210 #=4<I*180
220 #=:5)*:6)*:7)*:8)=0*510
230 I=6
240 J=5
250 #=:I)=:J)*510
260 J=J+1
270 #=J<I*250
280 I=I+1
290 #=I<9*240
300 B=0
310 C=0
320 I=1
330 B=:I)=:I+4)+B
340 J=1
350 C=(I=J=0)*(:I)=:J+4))+C
360 J=J+1
370 #=4>J*350
380 I=I+1
390 #=4>I*330
400 ?="BULLS: ";
410 ?=B
420 ?=", COWS: ";
430 ?=C
440 ?=""
450 #=B<4*130
460 ?=""
470 ?="YOU GOT IT IN ";
480 ?=T
490 ?=" TRIES!"
500 #=1000
510 ?="BAD GUESS - GUESS NEEDS TO BE 4 UNIQUE DIGITS WITHOUT ZEROES"
520 #=140</syntaxhighlight>
{{out}}
<pre>BULLS AND COWS
--------------
 
GUESS? 1234
BULLS: 0, COWS: 1
GUESS? 5678
BULLS: 0, COWS: 2
GUESS? 1978
BULLS: 1, COWS: 2
GUESS? 2978
BULLS: 1, COWS: 2
GUESS? 3978
BULLS: 1, COWS: 2
GUESS? 4978
BULLS: 1, COWS: 3
GUESS? 7984
BULLS: 1, COWS: 3
GUESS? 8947
BULLS: 4, COWS: 0
 
YOU GOT IT IN 8 TRIES!</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-set}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="wren">import "random" for Random
import "./set" for Set
import "./ioutil" for Input
 
var MAX_GUESSES = 20 // say
var r = Random.new()
var num
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
while (true) {
num = (1234 + r.int(8643)).toString
if (!num.contains("0") && Set.new(num).count == 4) break
}
 
System.print("All guesses should have exactly 4 distinct digits excluding zero.")
System.print("Keep guessing until you guess the chosen number (maximum %(MAX_GUESSES) valid guesses).\n")
var guesses = 0
while (true) {
var guess = Input.text("Enter your guess : ")
if (guess == num) {
System.print("You've won with %(guesses+1) valid guesses!")
return
}
var n = Num.fromString(guess)
if (!n) {
System.print("Not a valid number")
} else if (guess.contains("-") || guess.contains("+") || guess.contains(".")) {
System.print("Can't contain a sign or decimal point")
} else if (guess.contains("e") || guess.contains("E")) {
System.print("Can't contain an exponent")
} else if (guess.contains("0")) {
System.print("Can't contain zero")
} else if (guess.count != 4) {
System.print("Must have exactly 4 digits")
} else if (Set.new(guess).count < 4) {
System.print("All digits must be distinct")
} else {
var bulls = 0
var cows = 0
var i = 0
for (c in guess) {
if (num[i] == c) {
bulls = bulls + 1
} else if (num.contains(c)) {
cows = cows + 1
}
i = i + 1
}
System.print("Your score for this guess: Bulls = %(bulls) Cows = %(cows)")
guesses = guesses + 1
if (guesses == MAX_GUESSES) {
System.print("You've now had %(guesses) valid guesses, the maximum allowed")
return
}
}
}</syntaxhighlight>
 
{{out}}
Sample game:
<pre>
All guesses should have exactly 4 distinct digits excluding zero.
Keep guessing until you guess the chosen number (maximum 20 valid guesses).
 
Enter your guess : 1234
Your score for this guess: Bulls = 1 Cows = 1
Enter your guess : 1567
Your score for this guess: Bulls = 0 Cows = 1
Enter your guess : 8239
Your score for this guess: Bulls = 2 Cows = 1
Enter your guess : 8294
Your score for this guess: Bulls = 2 Cows = 0
Enter your guess : 8273
Your score for this guess: Bulls = 3 Cows = 0
Enter your guess : 8275
Your score for this guess: Bulls = 2 Cows = 1
Enter your guess : 8263
Your score for this guess: Bulls = 3 Cows = 0
Enter your guess : 8213
Your score for this guess: Bulls = 3 Cows = 0
Enter your guess : 8253
You've won with 9 valid guesses!
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">int Bulls, Cows, Secret(4), Guess(4), Guesses, Used, I, J, Done, Digit, Okay;
[Used:= 0; \generate secret random number using digits
for I:= 0 to 3 do \ 1 to 9 without any repeated digits
[repeat Digit:= Ran(9)+1;
until (Used & 1<<Digit) = 0;
Used:= Used ! 1<<Digit;
Secret(I):= Digit + ^0;
];
Text(0, "Guess the secret number.^m^j");
Text(0, "Guesses must be four different digits, 1 to 9.^m^j");
Guesses:= 0;
loop [Done:= false; \main game loop
repeat Text(0, "Enter your guess: "); \get valid 4-digits from player
OpenI(0); Used:= 0; I:= 0;
loop [Digit:= ChIn(0);
Okay:= Digit>=^1 and Digit<=^9;
Digit:= Digit & $0F; \convert ASCII to binary
if not Okay or Used & 1<<Digit then
[Text(0,
"Please enter four distinct digits, 1 thru 9.^m^j");
quit;
];
Guess(I):= Digit + ^0;
Used:= Used ! 1<<Digit;
I:= I+1;
if I = 4 then [Done:= true; quit];
];
until Done;
Guesses:= Guesses+1;
Bulls:= 0; Cows:= 0;
for I:= 0 to 3 do
for J:= 0 to 3 do
if Guess(I) = Secret(J) then
if I=J then Bulls:= Bulls+1
else Cows:= Cows+1;
Text(0, "Bulls: "); IntOut(0, Bulls);
Text(0, " Cows: "); IntOut(0, Cows);
CrLf(0);
if Bulls = 4 then quit;
];
Text(0, "Congratulations! You won in "); IntOut(0, Guesses);
Text(0, " guesses.^m^j");
]</syntaxhighlight>
{{out}}
<pre>
Guess the secret number.
Guesses must be four different digits, 1 to 9.
Enter your guess: 1234
Bulls: 1 Cows: 1
Enter your guess: 3345
Please enter four distinct digits, 1 thru 9.
Enter your guess: 0987
Please enter four distinct digits, 1 thru 9.
Enter your guess: 1357
Bulls: 1 Cows: 0
Enter your guess:
</pre>
 
=={{header|zkl}}==
Play one game:
<langsyntaxhighlight lang="zkl">d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
abcd:=d.keys.shuffle();
while(1){
Line 5,975 ⟶ 8,650:
"%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println();
}
fcn s(n){ (n!=1) and "s" or "" }</langsyntaxhighlight>
{{out}}
<pre>
Line 5,985 ⟶ 8,660:
You got it!
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|QBasic}}
<lang zxbasic>10 DIM n(10): LET c$=""
20 FOR i=1 TO 4
30 LET d=INT (RND*9+1)
40 IF n(d)=1 THEN GO TO 30
50 LET n(d)=1
60 LET c$=c$+STR$ d
70 NEXT i
80 LET guesses=0
90 INPUT "Guess a 4-digit number (1 to 9) with no duplicate digits: ";guess
100 IF guess=0 THEN STOP
110 IF guess>9999 OR guess<1000 THEN PRINT "Only 4 numeric digits, please": GO TO 90
120 LET bulls=0: LET cows=0: LET guesses=guesses+1: LET g$=STR$ guess
130 FOR i=1 TO 4
140 IF g$(i)=c$(i) THEN LET bulls=bulls+1: GO TO 160
150 IF n(VAL g$(i))=1 THEN LET cows=cows+1
160 NEXT i
170 PRINT bulls;" bulls, ";cows;" cows"
180 IF c$=g$ THEN PRINT "You won after ";guesses;" guesses!": GO TO 10
190 GO TO 90
</lang>
47

edits