Bulls and cows: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 32: Line 32:
This is written to run under CP/M and includes an RNG to generate the secret.
This is written to run under CP/M and includes an RNG to generate the secret.


<lang 8080asm>bdos equ 5
<syntaxhighlight lang=8080asm>bdos equ 5
putchar equ 2
putchar equ 2
rawio equ 6
rawio equ 6
Line 237: Line 237:
secret: ds 4 ; Holds the secret code
secret: ds 4 ; Holds the secret code
bufdef: db 4,0 ; User input buffer
bufdef: db 4,0 ; User input buffer
buf: ds 4</lang>
buf: ds 4</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE DIGNUM="4"
<syntaxhighlight lang=Action!>DEFINE DIGNUM="4"


TYPE Score=[BYTE bulls,cows,err]
TYPE Score=[BYTE bulls,cows,err]
Line 317: Line 317:
PrintE(", try again:")
PrintE(", try again:")
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bulls_and_cows.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bulls_and_cows.png Screenshot from Atari 8-bit computer]
Line 338: Line 338:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Numerics.Discrete_Random;


Line 390: Line 390:
end;
end;
end loop;
end loop;
end Bulls_And_Cows;</lang>
end Bulls_And_Cows;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 400: Line 400:


{{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]}}
{{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]}}
<lang algol68>STRING digits = "123456789";
<syntaxhighlight lang=algol68>STRING digits = "123456789";


[4]CHAR chosen;
[4]CHAR chosen;
Line 454: Line 454:
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))</lang>
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 469: Line 469:
Bulls and Cows in the APL session.
Bulls and Cows in the APL session.


<lang APL>input ← {⍞←'Guess: ' ⋄ 7↓⍞}
<syntaxhighlight lang=APL>input ← {⍞←'Guess: ' ⋄ 7↓⍞}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
isdigits← ∧/⎕D∊⍨⊢
Line 479: Line 479:
random ← 4∘⊣?9∘⊣
random ← 4∘⊣?9∘⊣
moo ← 'You win!'⊣(random game⊢)
moo ← 'You win!'⊣(random game⊢)
</syntaxhighlight>
</lang>




Line 486: Line 486:
referred to twice. The following definition of <code>moo</code> is exactly equivalent to the above:
referred to twice. The following definition of <code>moo</code> is exactly equivalent to the above:


<lang APL>moo←'You win!'⊣((4∘⊣?9∘⊣)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢)</lang>
<syntaxhighlight lang=APL>moo←'You win!'⊣((4∘⊣?9∘⊣)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢)</syntaxhighlight>




Line 493: Line 493:
GUI implementation; the prompt for a guess includes a list of all past guesses and their scores.
GUI implementation; the prompt for a guess includes a list of all past guesses and their scores.


<lang applescript>on pickNumber()
<syntaxhighlight lang=applescript>on pickNumber()
set theNumber to ""
set theNumber to ""
repeat 4 times
repeat 4 times
Line 550: Line 550:
end if
end if
end repeat
end repeat
end run</lang>
end run</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>rand: first.n: 4 unique map 1..10 => [sample 0..9]
<syntaxhighlight lang=rebol>rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0
bulls: 0


Line 574: Line 574:
]
]
]
]
print color #green "** Well done! You made the right guess!!"</lang>
print color #green "** Well done! You made the right guess!!"</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>length:=4, Code:="" ; settings
<syntaxhighlight lang=autohotkey>length:=4, Code:="" ; settings


While StrLen(Code) < length {
While StrLen(Code) < length {
Line 628: Line 628:
Cows++
Cows++
Return Bulls "," Cows
Return Bulls "," Cows
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK># Usage: GAWK -f BULLS_AND_COWS.AWK
<syntaxhighlight lang=AWK># Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
BEGIN {
srand()
srand()
Line 684: Line 684:
}
}
return bulls == 4
return bulls == 4
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 709: Line 709:
=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>DEFINT A-Z
<syntaxhighlight lang=qbasic>DEFINT A-Z


DIM secret AS STRING
DIM secret AS STRING
Line 749: Line 749:
END IF
END IF
looper:
looper:
LOOP</lang>
LOOP</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>100 D$ = "123456789"
<syntaxhighlight lang=ApplesoftBasic>100 D$ = "123456789"
110 FOR I = 1 TO 4
110 FOR I = 1 TO 4
120 P = INT(RND(1) * LEN(D$)) + 1
120 P = INT(RND(1) * LEN(D$)) + 1
Line 779: Line 779:
380 PRINT B " BULLS, " C " COWS"
380 PRINT B " BULLS, " C " COWS"
390 Q = G$ = N$
390 Q = G$ = N$
400 NEXT Q</lang>
400 NEXT Q</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Line 789: Line 789:
* Other formatting (clear screen, etc.) unique to Commodore BASIC.
* Other formatting (clear screen, etc.) unique to Commodore BASIC.


<lang FreeBasic>100 D$="123456789"
<syntaxhighlight lang=FreeBasic>100 D$="123456789"
110 FOR I=1 TO 4
110 FOR I=1 TO 4
120 P=INT(RND(1)*LEN(D$))+1
120 P=INT(RND(1)*LEN(D$))+1
Line 827: Line 827:
730 IF NOT M THEN NEXT J,I
730 IF NOT M THEN NEXT J,I
740 RETURN
740 RETURN
</syntaxhighlight>
</lang>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Bulls.bas"
<syntaxhighlight lang=IS-BASIC>100 PROGRAM "Bulls.bas"
110 RANDOMIZE
110 RANDOMIZE
120 STRING C$*4
120 STRING C$*4
Line 860: Line 860:
380 IF POS(S$(:I-1),S$(I)) OR POS(S$(I+1:),S$(I)) THEN LET CHECK$=""
380 IF POS(S$(:I-1),S$(I)) OR POS(S$(I+1:),S$(I)) THEN LET CHECK$=""
390 NEXT
390 NEXT
400 END DEF</lang>
400 END DEF</syntaxhighlight>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
{{trans|QBasic}}
{{trans|QBasic}}
<lang zxbasic>10 DIM n(10): LET c$=""
<syntaxhighlight lang=zxbasic>10 DIM n(10): LET c$=""
20 FOR i=1 TO 4
20 FOR i=1 TO 4
30 LET d=INT (RND*9+1)
30 LET d=INT (RND*9+1)
Line 883: Line 883:
180 IF c$=g$ THEN PRINT "You won after ";guesses;" guesses!": GO TO 10
180 IF c$=g$ THEN PRINT "You won after ";guesses;" guesses!": GO TO 10
190 GO TO 90
190 GO TO 90
</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>:: Bulls and Cows Task from Rosetta Code
<syntaxhighlight lang=dos>:: Bulls and Cows Task from Rosetta Code
:: Batch File Implementation
:: Batch File Implementation
Line 986: Line 986:
set /p "opt=Play again? "
set /p "opt=Play again? "
if /i "!opt!" equ "y" goto begin
if /i "!opt!" equ "y" goto begin
exit /b 0</lang>
exit /b 0</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,033: Line 1,033:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> secret$ = ""
<syntaxhighlight lang=bbcbasic> secret$ = ""
REPEAT
REPEAT
c$ = CHR$(&30 + RND(9))
c$ = CHR$(&30 + RND(9))
Line 1,065: Line 1,065:
UNTIL FALSE
UNTIL FALSE
</syntaxhighlight>
</lang>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang=bcpl>get "libhdr"


static $( randstate = ? $)
static $( randstate = ? $)
Line 1,137: Line 1,137:
gensecret(secret)
gensecret(secret)
play(secret)
play(secret)
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>Bulls and cows
<pre>Bulls and cows
Line 1,163: Line 1,163:
You win in 9 tries.</pre>
You win in 9 tries.</pre>
=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>secret_length = 4
<syntaxhighlight lang=brat>secret_length = 4


secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
Line 1,201: Line 1,201:
guesses = guesses + 1
guesses = guesses + 1
}
}
}</lang>
}</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
{{libheader|ncurses}}
{{libheader|ncurses}}
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <stdarg.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdlib.h>
Line 1,264: Line 1,264:
}
}
}
}
}</lang>
}</syntaxhighlight>


The following function contains the code to check how many bulls and cows there are.
The following function contains the code to check how many bulls and cows there are.


<lang c>bool take_it_or_not()
<syntaxhighlight lang=c>bool take_it_or_not()
{
{
int i;
int i;
Line 1,352: Line 1,352:
nocbreak(); echo(); endwin();
nocbreak(); echo(); endwin();
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


namespace BullsnCows
namespace BullsnCows
Line 1,434: Line 1,434:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <string>
#include <string>
#include <algorithm>
#include <algorithm>
Line 1,514: Line 1,514:
std::cout << "Another game? ";
std::cout << "Another game? ";
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>import ceylon.random {
<syntaxhighlight lang=ceylon>import ceylon.random {
DefaultRandom
DefaultRandom
}
}
Line 1,586: Line 1,586:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>
<syntaxhighlight lang=clojure>
(ns bulls-and-cows)
(ns bulls-and-cows)
Line 1,628: Line 1,628:
(bulls-and-cows)
(bulls-and-cows)
</syntaxhighlight>
</lang>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% This program needs to be merged with PCLU's "misc" library
<syntaxhighlight lang=clu>% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
% to use the random number generator.
%
%
Line 1,762: Line 1,762:
stream$putl(po, "Bulls and cows\n----- --- ----\n")
stream$putl(po, "Bulls and cows\n----- --- ----\n")
play_game(make_secret())
play_game(make_secret())
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Bulls and cows
<pre>Bulls and cows
Line 1,785: Line 1,785:
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:
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:


<lang coco>say = print
<syntaxhighlight lang=coco>say = print
prompt = (str) ->
prompt = (str) ->
putstr str
putstr str
readline! ? quit!</lang>
readline! ? quit!</syntaxhighlight>


We can now solve the task using <code>say</code> and <code>prompt</code>:
We can now solve the task using <code>say</code> and <code>prompt</code>:


<lang coco>const SIZE = 4
<syntaxhighlight lang=coco>const SIZE = 4


secret = _.sample ['1' to '9'], SIZE
secret = _.sample ['1' to '9'], SIZE
Line 1,813: Line 1,813:
say "#bulls bull#{[if bulls !== 1 then 's']}, #cows cow#{[if cows !== 1 then 's']}."
say "#bulls bull#{[if bulls !== 1 then 's']}, #cows cow#{[if cows !== 1 then 's']}."


say 'A winner is you!'</lang>
say 'A winner is you!'</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun get-number ()
<syntaxhighlight lang=lisp>(defun get-number ()
(do ((digits '()))
(do ((digits '()))
((>= (length digits) 4) digits)
((>= (length digits) 4) digits)
Line 1,857: Line 1,857:
(format stream "~&Correct, you win!")
(format stream "~&Correct, you win!")
(format stream "~&Score: ~a cows, ~a bulls."
(format stream "~&Score: ~a cows, ~a bulls."
cows bulls)))))))</lang>
cows bulls)))))))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang Ruby>size = 4
<syntaxhighlight lang=Ruby>size = 4
secret = ('1'..'9').to_a.sample(size)
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
guess = [] of Char
Line 1,895: Line 1,895:


puts "Bulls: #{bulls}; Cows: #{cows}"
puts "Bulls: #{bulls}; Cows: #{cows}"
end</lang>
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang=d>void main() {
import std.stdio, std.random, std.string, std.algorithm,
import std.stdio, std.random, std.string, std.algorithm,
std.range, std.ascii;
std.range, std.ascii;
Line 1,915: Line 1,915:
" Bad guess! (4 unique digits, 1-9)".writeln;
" Bad guess! (4 unique digits, 1-9)".writeln;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Next guess: 6548
<pre>Next guess: 6548
Line 1,942: Line 1,942:
Note: This example was deliberately written in an abstracted style, separating out the algorithms, game logic, and UI.
Note: This example was deliberately written in an abstracted style, separating out the algorithms, game logic, and UI.


<lang e>def Digit := 1..9
<syntaxhighlight lang=e>def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]
def Number := Tuple[Digit,Digit,Digit,Digit]


Line 2,023: Line 2,023:
return gameTurn()
return gameTurn()
}</lang>
}</syntaxhighlight>


===REPL user interface===
===REPL user interface===
Line 2,045: Line 2,045:
{{works with|E-on-Java}} (Java Swing)
{{works with|E-on-Java}} (Java Swing)


<lang e>def guiBullsAndCows() {
<syntaxhighlight lang=e>def guiBullsAndCows() {
var lastGuess := ""
var lastGuess := ""
def op := <unsafe:javax.swing.makeJOptionPane>
def op := <unsafe:javax.swing.makeJOptionPane>
Line 2,059: Line 2,059:
op.showMessageDialog(null, msg)
op.showMessageDialog(null, msg)
}, entropy)
}, entropy)
}</lang>
}</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>dig[] = [ 1 2 3 4 5 6 7 8 9 ]
<syntaxhighlight lang=text>dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
for i range 4
h = i + random (9 - i)
h = i + random (9 - i)
Line 2,103: Line 2,103:
until bulls = 4
until bulls = 4
.
.
print "Well done! " & attempts & " attempts needed."</lang>
print "Well done! " & attempts & " attempts needed."</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang Eiffel>
<syntaxhighlight lang=Eiffel>
class
class
BULLS_AND_COWS
BULLS_AND_COWS
Line 2,219: Line 2,219:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,249: Line 2,249:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang=elena>import system'routines;
import extensions;
import extensions;


Line 2,338: Line 2,338:
console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,357: Line 2,357:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
{{works with|Elixir|1.2}}
<lang elixir>defmodule Bulls_and_cows do
<syntaxhighlight lang=elixir>defmodule Bulls_and_cows do
def play(size \\ 4) do
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
Line 2,398: Line 2,398:
end
end


Bulls_and_cows.play</lang>
Bulls_and_cows.play</syntaxhighlight>


{{out}}
{{out}}
Line 2,416: Line 2,416:
=={{header|Erlang}}==
=={{header|Erlang}}==
Module:
Module:
<lang erlang>-module(bulls_and_cows).
<syntaxhighlight lang=erlang>-module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).
-export([generate_secret/0, score_guess/2, play/0]).


Line 2,460: Line 2,460:
read_guess() ->
read_guess() ->
lists:map(fun(D)->D-48 end,
lists:map(fun(D)->D-48 end,
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).</lang>
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).</syntaxhighlight>


Script:
Script:
<lang erlang>#!/usr/bin/escript
<syntaxhighlight lang=erlang>#!/usr/bin/escript
% Play Bulls and Cows
% Play Bulls and Cows
main(_) -> random:seed(now()), bulls_and_cows:play().</lang>
main(_) -> random:seed(now()), bulls_and_cows:play().</syntaxhighlight>


Sample play:<pre>Enter your 4-digit guess: 8376
Sample play:<pre>Enter your 4-digit guess: 8376
Line 2,481: Line 2,481:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<lang euphoria>include std\text.e
<syntaxhighlight lang=euphoria>include std\text.e
include std\os.e
include std\os.e
include std\sequence.e
include std\sequence.e
Line 2,586: Line 2,586:




</syntaxhighlight>
</lang>
Output :
Output :
<pre>
<pre>
Line 2,611: Line 2,611:


=={{header|Factor}}==
=={{header|Factor}}==
<lang Factor>USING: accessors assocs combinators fry grouping hashtables kernel
<syntaxhighlight lang=Factor>USING: accessors assocs combinators fry grouping hashtables kernel
locals math math.parser math.ranges random sequences strings
locals math math.parser math.ranges random sequences strings
io ascii ;
io ascii ;
Line 2,674: Line 2,674:
[ main-loop ] [ drop win ] if ;
[ main-loop ] [ drop win ] if ;


: main ( -- ) new-number drop narr>nhash main-loop ;</lang>
: main ( -- ) new-number drop narr>nhash main-loop ;</syntaxhighlight>


=={{header|Fan}}==
=={{header|Fan}}==
<lang Fan>**
<syntaxhighlight lang=Fan>**
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
**
Line 2,726: Line 2,726:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>01.10 T %1,"BULLS AND COWS"!"----- --- ----"!!
<syntaxhighlight lang=FOCAL>01.10 T %1,"BULLS AND COWS"!"----- --- ----"!!
01.20 S T=0;D 3
01.20 S T=0;D 3
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
Line 2,762: Line 2,762:
05.70 I (-FABS(S(X)-G(Y)))5.5,5.9
05.70 I (-FABS(S(X)-G(Y)))5.5,5.9
05.80 S B=B+1
05.80 S B=B+1
05.90 S C=C+1</lang>
05.90 S C=C+1</syntaxhighlight>


{{out}}
{{out}}
Line 2,797: Line 2,797:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>include random.fs
<syntaxhighlight lang=forth>include random.fs


create hidden 4 allot
create hidden 4 allot
Line 2,833: Line 2,833:
: guess: ( "1234" -- )
: guess: ( "1234" -- )
bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
drop check? if cr ." You guessed it!" then ;</lang>
drop check? if cr ." You guessed it!" then ;</syntaxhighlight>
{{out}}
{{out}}
<pre>init ok
<pre>init ok
Line 2,844: Line 2,844:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>module bac
<syntaxhighlight lang=fortran>module bac
implicit none
implicit none


Line 2,927: Line 2,927:
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"


end program Bulls_and_Cows</lang>
end program Bulls_and_Cows</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang=fsharp>
open System
open System


Line 2,999: Line 2,999:
shouldEnd <- false
shouldEnd <- false
0
0
</syntaxhighlight>
</lang>


=={{Header|FreeBASIC}}==
=={{Header|FreeBASIC}}==
<lang>function get_digit( num as uinteger, ps as uinteger ) as uinteger
<syntaxhighlight lang=text>function get_digit( num as uinteger, ps as uinteger ) as uinteger
return (num mod 10^(ps+1))\10^ps
return (num mod 10^(ps+1))\10^ps
end function
end function
Line 3,051: Line 3,051:
wend
wend


print using "Correct. That took you ### guesses."; count</lang>
print using "Correct. That took you ### guesses."; count</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang=frink>
// Bulls and Cows - Written in Frink
// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]
println["Welcome to Bulls and Cows!"]
Line 3,138: Line 3,138:
guessPlural = guessCount == 1 ? "guess" : "guesses"
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,154: Line 3,154:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 3,221: Line 3,221:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Golo}}==
=={{header|Golo}}==
<lang golo>#!/usr/bin/env golosh
<syntaxhighlight lang=golo>#!/usr/bin/env golosh
----
----
This module is the Bulls and Cows game.
This module is the Bulls and Cows game.
Line 3,323: Line 3,323:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang Groovy>class BullsAndCows {
<syntaxhighlight lang=Groovy>class BullsAndCows {
static void main(args) {
static void main(args) {
def inputReader = System.in.newReader()
def inputReader = System.in.newReader()
Line 3,372: Line 3,372:
}
}


</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (partition, intersect, nub)
<syntaxhighlight lang=haskell>import Data.List (partition, intersect, nub)
import Control.Monad
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
import System.Random (StdGen, getStdRandom, randomR)
Line 3,424: Line 3,424:
f (n - 1) (left ++ right) g' (max - 1) (picked : ps)
f (n - 1) (left ++ right) g' (max - 1) (picked : ps)
where (i, g') = randomR (0, max) g
where (i, g') = randomR (0, max) g
(left, picked : right) = splitAt i l</lang>
(left, picked : right) = splitAt i l</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==


<lang lisp>(import random)
<syntaxhighlight lang=lisp>(import random)


(def +size+ 4)
(def +size+ 4)
Line 3,453: Line 3,453:
cows (if (= cows 1) "" "s"))))
cows (if (= cows 1) "" "s"))))
(print "A winner is you!")</lang>
(print "A winner is you!")</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 3,459: Line 3,459:
The following works in both Icon and Unicon.
The following works in both Icon and Unicon.


<lang Unicon>procedure main()
<syntaxhighlight lang=Unicon>procedure main()
digits := "123456789"
digits := "123456789"
every !digits :=: ?digits
every !digits :=: ?digits
Line 3,482: Line 3,482:
write("\t",bulls," bulls and ",cows," cows")
write("\t",bulls," bulls and ",cows," cows")
return (bulls = *num)
return (bulls = *num)
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>require 'misc'
<syntaxhighlight lang=j>require 'misc'
plural=: conjunction define
plural=: conjunction define
Line 3,508: Line 3,508:
end.
end.
smoutput 'you win'
smoutput 'you win'
)</lang>
)</syntaxhighlight>


For example:
For example:


<lang j> bullcow''
<syntaxhighlight lang=j> bullcow''
Guess my number: 1234
Guess my number: 1234
0 bulls and 1 cow.
0 bulls and 1 cow.
Line 3,527: Line 3,527:
Guess my number: 5178
Guess my number: 5178
4 bulls and 0 cows.
4 bulls and 0 cows.
you win</lang>
you win</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java5>import java.util.InputMismatchException;
<syntaxhighlight lang=java5>import java.util.InputMismatchException;
import java.util.Random;
import java.util.Random;
import java.util.Scanner;
import java.util.Scanner;
Line 3,581: Line 3,581:
return false;
return false;
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>Guess a 4-digit number with no duplicate digits: 5834
<pre>Guess a 4-digit number with no duplicate digits: 5834
Line 3,606: Line 3,606:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
=== Spidermonkey version ===
=== Spidermonkey version ===
<lang javascript>#!/usr/bin/env js
<syntaxhighlight lang=javascript>#!/usr/bin/env js


function main() {
function main() {
Line 3,694: Line 3,694:


main();
main();
</syntaxhighlight>
</lang>


Example game (cheating!):
Example game (cheating!):
Line 3,726: Line 3,726:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>function cowsbulls()
<syntaxhighlight 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
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
You get one bull for every right number in the right position.\n
Line 3,757: Line 3,757:
end
end
end
end
end</lang>
end</syntaxhighlight>
The following version checks thoroughly that the input of the player is constituted of four distincts digits.
The following version checks thoroughly that the input of the player is constituted of four distincts digits.
<lang julia>function bullsandcows ()
<syntaxhighlight lang=julia>function bullsandcows ()
bulls = cows = turns = 0
bulls = cows = turns = 0
result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
Line 3,775: Line 3,775:
end
end
println("You win! You succeeded in $turns guesses.")
println("You win! You succeeded in $turns guesses.")
end</lang>
end</syntaxhighlight>
{{Out}}
{{Out}}
<pre>julia> bullsandcows()
<pre>julia> bullsandcows()
Line 3,794: Line 3,794:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang=scala>// version 1.1.2


import java.util.Random
import java.util.Random
Line 3,842: Line 3,842:
}
}
}
}
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 3,868: Line 3,868:
=={{header|Lasso}}==
=={{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.
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.
<lang Lasso>[
<syntaxhighlight lang=Lasso>[
define randomizer() => {
define randomizer() => {
local(n = string)
local(n = string)
Line 3,938: Line 3,938:
'<a href="?restart">Restart</a>'
'<a href="?restart">Restart</a>'
^}]
^}]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,983: Line 3,983:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>
<lang lb>


do while len( secret$) <4
do while len( secret$) <4
Line 4,046: Line 4,046:
close #w
close #w
end
end
</syntaxhighlight>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<lang logo>to ok? :n
<syntaxhighlight lang=logo>to ok? :n
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end
end
Line 4,068: Line 4,068:
(print :bulls "bulls, :cows "cows)
(print :bulls "bulls, :cows "cows)
if :bulls = 4 [print [You guessed it!]]
if :bulls = 4 [print [You guessed it!]]
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function ShuffleArray(array)
<syntaxhighlight lang=Lua>function ShuffleArray(array)
for i=1,#array-1 do
for i=1,#array-1 do
local t = math.random(i, #array)
local t = math.random(i, #array)
Line 4,171: Line 4,171:
print("\nGoodbye!")
print("\nGoodbye!")
end
end
until quit</lang>
until quit</syntaxhighlight>




Another version:
Another version:
<lang Lua>function createNewNumber ()
<syntaxhighlight lang=Lua>function createNewNumber ()
math.randomseed(os.time())
math.randomseed(os.time())
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Line 4,237: Line 4,237:
end
end
end
end
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module Game {
Module Game {
Malformed=lambda (a$)->{
Malformed=lambda (a$)->{
Line 4,289: Line 4,289:
}
}
Game
Game
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>BC := proc(n) #where n is the number of turns the user wishes to play before they quit
<syntaxhighlight 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;
local target, win, numGuesses, guess, bulls, cows, i, err;
target := [0, 0, 0, 0]:
target := [0, 0, 0, 0]:
Line 4,346: Line 4,346:
end if;
end if;
return NULL;
return NULL;
end proc:</lang>
end proc:</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,361: Line 4,361:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
<syntaxhighlight lang=Mathematica>digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
codes=ToCharacterCode[StringJoin[ToString/@digits]];
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
Module[{r,bulls,cows},
Line 4,372: Line 4,372:
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
Print["Guess four digits."]]]]]]]</lang>
Print["Guess four digits."]]]]]]]</syntaxhighlight>
Output:
Output:
<pre>{8, 2, 6, 1}
<pre>{8, 2, 6, 1}
Line 4,380: Line 4,380:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function BullsAndCows
<syntaxhighlight lang=MATLAB>function BullsAndCows
% Plays the game Bulls and Cows as the "game master"
% Plays the game Bulls and Cows as the "game master"
Line 4,441: Line 4,441:
cows = ismember(guess(~bulls), correct);
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
score = [sum(bulls) sum(cows)];
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>Welcome to Bulls and Cows!
<pre>Welcome to Bulls and Cows!
Line 4,473: Line 4,473:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang MAXScript>
<syntaxhighlight lang=MAXScript>
numCount = 4 -- number of digits to use
numCount = 4 -- number of digits to use


Line 4,542: Line 4,542:
format "\nBulls: % Cows: %\n" bulls cows
format "\nBulls: % Cows: %\n" bulls cows
)
)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<lang>
<syntaxhighlight lang=text>
OK
OK
Rules:
Rules:
Line 4,565: Line 4,565:
Enter your number: 1357
Enter your number: 1357
Bulls: 0 Cows: 1
Bulls: 0 Cows: 1
</syntaxhighlight>
</lang>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>secret = range(1,9)
<syntaxhighlight lang=MiniScript>secret = range(1,9)
secret.shuffle
secret.shuffle
secret = secret[:4].join("")
secret = secret[:4].join("")
Line 4,593: Line 4,593:
print "You score " + bulls + " bull" + "s"*(bulls!=1) +
print "You score " + bulls + " bull" + "s"*(bulls!=1) +
" and " + cows + " cow" + "s"*(cows!=1) + "."
" and " + cows + " cow" + "s"*(cows!=1) + "."
end while</lang>
end while</syntaxhighlight>
{{out}}
{{out}}
<pre>Your guess? 2385
<pre>Your guess? 2385
Line 4,608: Line 4,608:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>BullCow New bull,cow,guess,guessed,ii,number,pos,x
<syntaxhighlight lang=MUMPS>BullCow New bull,cow,guess,guessed,ii,number,pos,x
Set number="",x=1234567890
Set number="",x=1234567890
For ii=1:1:4 Do
For ii=1:1:4 Do
Line 4,672: Line 4,672:
Your guess: 2907
Your guess: 2907
You guessed 2907. That earns you 4 bulls.
You guessed 2907. That earns you 4 bulls.
That's a perfect score.</lang>
That's a perfect score.</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang Nanoquery>import Nanoquery.Util; random = new(Random)
<syntaxhighlight lang=Nanoquery>import Nanoquery.Util; random = new(Random)


// a function to verify the user's input
// a function to verify the user's input
Line 4,741: Line 4,741:
end
end


println "\nCongratulations you guess correctly in " + guesses + " attempts"</lang>
println "\nCongratulations you guess correctly in " + guesses + " attempts"</syntaxhighlight>


{{out}}
{{out}}
Line 4,767: Line 4,767:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import random, strutils, strformat, sequtils
<syntaxhighlight lang=nim>import random, strutils, strformat, sequtils
randomize()
randomize()


Line 4,806: Line 4,806:
if guess[i] == chosen[i]: inc bulls
if guess[i] == chosen[i]: inc bulls
elif guess[i] in chosen: inc cows
elif guess[i] in chosen: inc cows
echo &" {bulls} Bull{plural(bulls)}\n {cows} Cow{plural(cows)}"</lang>
echo &" {bulls} Bull{plural(bulls)}\n {cows} Cow{plural(cows)}"</syntaxhighlight>


{{out}}
{{out}}
Line 4,830: Line 4,830:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let rec input () =
<syntaxhighlight lang=ocaml>let rec input () =
let s = read_line () in
let s = read_line () in
try
try
Line 4,879: Line 4,879:
done;
done;
print_endline "Congratulations you guessed correctly";
print_endline "Congratulations you guessed correctly";
;;</lang>
;;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: bullsAndCows
<syntaxhighlight lang=Oforth>: bullsAndCows
| numbers guess digits bulls cows |
| numbers guess digits bulls cows |


Line 4,900: Line 4,900:
guess filter(#[numbers include]) size bulls - ->cows
guess filter(#[numbers include]) size bulls - ->cows
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
] ;</lang>
] ;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
Line 4,906: Line 4,906:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang=oz>declare
proc {Main}
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
Solution = {PickNUnique 4 {List.number 1 9 1}}
Line 4,974: Line 4,974:
fun {Id X} X end
fun {Id X} X end
in
in
{Main}</lang>
{Main}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
This simple implementation expects guesses in the form [a,b,c,d].
This simple implementation expects guesses in the form [a,b,c,d].
<lang parigp>bc()={
<syntaxhighlight lang=parigp>bc()={
my(u,v,bulls,cows);
my(u,v,bulls,cows);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
Line 4,988: Line 4,988:
print("You have "bulls" bulls and "cows" cows")
print("You have "bulls" bulls and "cows" cows")
)
)
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program BullCow;
<syntaxhighlight lang=pascal>Program BullCow;


{$mode objFPC}
{$mode objFPC}
Line 5,179: Line 5,179:
end.
end.
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use Data::Random qw(rand_set);
<syntaxhighlight lang=perl>use Data::Random qw(rand_set);
use List::MoreUtils qw(uniq);
use List::MoreUtils qw(uniq);


Line 5,220: Line 5,220:
my $g = shift;
my $g = shift;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\BullsAndCows.exw
-- demo\rosetta\BullsAndCows.exw
Line 5,298: Line 5,298:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<small>(as shown in the res label)</small>
<small>(as shown in the res label)</small>
Line 5,313: Line 5,313:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang=php><?php
$size = 4;
$size = 4;


Line 5,352: Line 5,352:
preg_match("/^[1-9]{{$size}}$/", $g);
preg_match("/^[1-9]{{$size}}$/", $g);
}
}
?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
{{trans|Python}}
{{trans|Python}}
<lang Picat>main =>
<syntaxhighlight lang=Picat>main =>
Digits = to_array("123456789"),
Digits = to_array("123456789"),
Size = 4,
Size = 4,
Line 5,388: Line 5,388:
random_sample(N,I,Chosen0,Chosen)
random_sample(N,I,Chosen0,Chosen)
).
).
</syntaxhighlight>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang lisp>(de ok? (N)
<syntaxhighlight lang=lisp>(de ok? (N)
(let D (mapcar 'format (chop N))
(let D (mapcar 'format (chop N))
(and (num? N)
(and (num? N)
Line 5,411: Line 5,411:
(pack Bulls " bulls, " Cows " cows") ) ) )
(pack Bulls " bulls, " Cows " cows") ) ) )
" Bad guess! (4 unique digits, 1-9)" ) ) )
" Bad guess! (4 unique digits, 1-9)" ) ) )
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
[int]$guesses = $bulls = $cows = 0
[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
[string]$guess = "none"
Line 5,462: Line 5,462:


Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 5,482: Line 5,482:
Produces both a console transcript and a GUI interface to the game.
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.
Creates a new game each time the guess is correct; tracks number of games won.
<lang processing>IntDict score;
<syntaxhighlight lang=processing>IntDict score;
StringList choices;
StringList choices;
StringList guess;
StringList guess;
Line 5,543: Line 5,543:
}
}
return result;
return result;
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{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'''.
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'''.
<lang Prolog>:- use_module(library(lambda)).
<syntaxhighlight lang=Prolog>:- use_module(library(lambda)).
:- use_module(library(clpfd)).
:- use_module(library(clpfd)).


Line 5,603: Line 5,603:
Solution, 0, TT),
Solution, 0, TT),
Cows is TT - Bulls.
Cows is TT - Bulls.
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Define.s secret, guess, c
<syntaxhighlight lang=PureBasic>Define.s secret, guess, c
Define.i bulls, cows, guesses, i
Define.i bulls, cows, guesses, i


Line 5,675: Line 5,675:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>'''
<syntaxhighlight lang=python>'''
Bulls and cows. A game pre-dating, and similar to, Mastermind.
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
'''
Line 5,710: Line 5,710:
elif guess[i] in chosen:
elif guess[i] in chosen:
cows += 1
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)</lang>
print ' %i Bulls\n %i Cows' % (bulls, cows)</syntaxhighlight>
Sample output:
Sample output:
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
Line 5,727: Line 5,727:


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>
<syntaxhighlight lang=QB64>
Const MaxDigit = 4, Min = 1, Max = 9
Const MaxDigit = 4, Min = 1, Max = 9
Dim As String NumberToGuess, NumberToTest, Newdigit, Result
Dim As String NumberToGuess, NumberToTest, Newdigit, Result
Line 5,756: Line 5,756:
End If
End If
Loop
Loop
</syntaxhighlight>
</lang>




=={{header|R}}==
=={{header|R}}==
{{works with|R|2.8.1}}
{{works with|R|2.8.1}}
<lang R>target <- sample(1:9,4)
<syntaxhighlight lang=R>target <- sample(1:9,4)
bulls <- 0
bulls <- 0
cows <- 0
cows <- 0
Line 5,779: Line 5,779:
} else {print("Malformed input!")}
} else {print("Malformed input!")}
}
}
print(paste("You won in",attempts,"attempt(s)!"))</lang>
print(paste("You won in",attempts,"attempt(s)!"))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket


Line 5,841: Line 5,841:
(main-loop state (add1 step))))))))))
(main-loop state (add1 step))))))))))


(main-loop game 0)</lang>
(main-loop game 0)</syntaxhighlight>


Output:
Output:
Line 5,871: Line 5,871:
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}


<lang perl6>my $size = 4;
<syntaxhighlight lang=raku line>my $size = 4;
my @secret = pick $size, '1' .. '9';
my @secret = pick $size, '1' .. '9';


Line 5,891: Line 5,891:
}
}


say 'A winner is you!';</lang>
say 'A winner is you!';</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>
<syntaxhighlight lang=Red>
Red[]
Red[]
a: "0123456789"
a: "0123456789"
Line 5,911: Line 5,911:
]
]
print "You won!"
print "You won!"
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Line 5,926: Line 5,926:
<br>and also change the prompt message.
<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.
<br>The REXX statement that contains the &nbsp; '''translate''' &nbsp; statement can be removed if repeated digits aren't allowed.
<lang rexx>/*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
<syntaxhighlight 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. */
?=; 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. */
if pos(r,?)\==0 then iterate; ?= ? || r /*don't allow a repeated digit/numeral. */
Line 5,952: Line 5,952:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */</lang><br><br>
s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */</syntaxhighlight><br><br>


===Version 2===
===Version 2===
<lang rexx>
<syntaxhighlight lang=rexx>
/*REXX program to play the game of "Bulls & Cows". *******************
/*REXX program to play the game of "Bulls & Cows". *******************
* Changes from Version 1:
* Changes from Version 1:
Line 6,057: Line 6,057:


ser: Say '*** error ***' arg(1); Return
ser: Say '*** error ***' arg(1); Return
</syntaxhighlight>
</lang>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
# Project : Bulls and cows
# Project : Bulls and cows


Line 6,100: Line 6,100:
see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
end
end
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Inspired by Tcl
Inspired by Tcl
{{works with|Ruby|1.8.7+}}
{{works with|Ruby|1.8.7+}}
<lang ruby>def generate_word(len)
<syntaxhighlight lang=ruby>def generate_word(len)
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
end
end
Line 6,145: Line 6,145:
puts "that guess has %d bulls and %d cows" % score(word, guess)
puts "that guess has %d bulls and %d cows" % score(word, guess)
end
end
puts "you guessed correctly in #{count} tries."</lang>
puts "you guessed correctly in #{count} tries."</syntaxhighlight>


Inspired by Python
Inspired by Python
{{works with|Ruby|2.0+}}
{{works with|Ruby|2.0+}}
<lang ruby>size = 4
<syntaxhighlight lang=ruby>size = 4
secret = [*'1' .. '9'].sample(size)
secret = [*'1' .. '9'].sample(size)
guess = nil
guess = nil
Line 6,183: Line 6,183:
puts "Bulls: #{bulls}; Cows: #{cows}"
puts "Bulls: #{bulls}; Cows: #{cows}"
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<lang rust>use std::io;
<syntaxhighlight lang=rust>use std::io;
use rand::{Rng,thread_rng};
use rand::{Rng,thread_rng};


Line 6,268: Line 6,268:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import scala.util.Random
<syntaxhighlight lang=scala>import scala.util.Random


object BullCow {
object BullCow {
Line 6,312: Line 6,312:


def hasDups(input:List[Int])=input.size!=input.distinct.size
def hasDups(input:List[Int])=input.size!=input.distinct.size
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|any R6RS Scheme}}
{{works with|any R6RS Scheme}}


<lang scheme>
<syntaxhighlight lang=scheme>


;generate a random non-repeating list of 4 digits, 1-9 inclusive
;generate a random non-repeating list of 4 digits, 1-9 inclusive
Line 6,384: Line 6,384:


(bull-cow (get-num))
(bull-cow (get-num))
</syntaxhighlight>
</lang>


=== Sample game play ===
=== Sample game play ===
Line 6,425: Line 6,425:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 6,473: Line 6,473:
until guess = chosen;
until guess = chosen;
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 6,493: Line 6,493:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>repeat forever
<syntaxhighlight lang=sensetalk>repeat forever
repeat forever
repeat forever
put random(1111,9999) into num
put random(1111,9999) into num
Line 6,569: Line 6,569:
end if
end if
end repeat
end repeat
end repeat</lang>
end repeat</syntaxhighlight>


=={{header|Shale}}==
=={{header|Shale}}==


<lang Shale>#!/usr/local/bin/shale
<syntaxhighlight lang=Shale>#!/usr/local/bin/shale


maths library
maths library
Line 6,692: Line 6,692:


init()
init()
play()</lang>
play()</syntaxhighlight>


{{out}}
{{out}}
Line 6,743: Line 6,743:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var size = 4
<syntaxhighlight lang=ruby>var size = 4
var num = @(1..9).shuffle.first(size)
var num = @(1..9).shuffle.first(size)


Line 6,778: Line 6,778:


"Bulls: %d; Cows: %d\n".printf(bulls, cows)
"Bulls: %d; Cows: %d\n".printf(bulls, cows)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,793: Line 6,793:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>Object subclass: BullsCows [
<syntaxhighlight lang=smalltalk>Object subclass: BullsCows [
|number|
|number|
BullsCows class >> new: secretNum [ |i|
BullsCows class >> new: secretNum [ |i|
Line 6,850: Line 6,850:
'Do you want to play again? [y/n]' display.
'Do you want to play again? [y/n]' display.
( (stdin nextLine) = 'y' )
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ].</lang>
] whileTrue: [ Character nl displayNl ].</syntaxhighlight>


=={{header|Smart BASIC}}==
=={{header|Smart BASIC}}==
<lang smart BASIC>
<syntaxhighlight lang=smart BASIC>
'by rbytes, January 2017
'by rbytes, January 2017
OPTION BASE 1
OPTION BASE 1
Line 6,941: Line 6,941:
END DEF
END DEF
END
END
</syntaxhighlight>
</lang>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>import Foundation
<syntaxhighlight lang=swift>import Foundation


func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
Line 7,003: Line 7,003:
exit(0)
exit(0)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,021: Line 7,021:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc main {} {
<syntaxhighlight lang=tcl>proc main {} {
fconfigure stdout -buffering none
fconfigure stdout -buffering none
set length 4
set length 4
Line 7,105: Line 7,105:
}
}


main</lang>
main</syntaxhighlight>


=={{header|Transd}}==
=={{header|Transd}}==
{{trans|C++}}
{{trans|C++}}
<lang scheme>
<syntaxhighlight lang=scheme>
#lang transd
#lang transd


Line 7,170: Line 7,170:
)
)
}
}
</syntaxhighlight>
</lang>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang=tuscript>
$$ MODE tuscript
$$ MODE tuscript
SET nr1=RANDOM_NUMBERS (1,9,1)
SET nr1=RANDOM_NUMBERS (1,9,1)
Line 7,212: Line 7,212:
ENDIF
ENDIF
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 7,229: Line 7,229:


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
<lang>Local(2) ' Let's use no globals
<syntaxhighlight lang=text>Local(2) ' Let's use no globals


Proc _Initialize ' Get our secret number
Proc _Initialize ' Get our secret number
Line 7,306: Line 7,306:
Next ' Increment with valid digits
Next ' Increment with valid digits
Next
Next
Return (c@) ' Return number of valid digits</lang>
Return (c@) ' Return number of valid digits</syntaxhighlight>
The addition of strings allows for much simpler code.
The addition of strings allows for much simpler code.
<lang>Do
<syntaxhighlight lang=text>Do
s = Str(1234 + RND(8643))
s = Str(1234 + RND(8643))
Until FUNC(_Check(s))
Until FUNC(_Check(s))
Line 7,351: Line 7,351:
b@ = b@ + 2^(Peek(a@, c@) - Ord ("0"))
b@ = b@ + 2^(Peek(a@, c@) - Ord ("0"))
Next
Next
Return (1)</lang>
Return (1)</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash|3}}
{{works with|bash|3}}


<lang bash>#!/bin/bash
<syntaxhighlight lang=bash>#!/bin/bash


rand() {
rand() {
Line 7,505: Line 7,505:
[ "${guess}" == "${secret}" ] && echo "You win!" && exit
[ "${guess}" == "${secret}" ] && echo "You win!" && exit
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
done</lang>
done</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
Option Explicit


Line 7,583: Line 7,583:
AskToUser = strIn
AskToUser = strIn
End Function
End Function
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
VBS functions return variants. I use t to return a single error value or a pair bulls, cows on result<br />
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
VBS does'nt have a continue so i used the classic do loop inside do loop in the main program
<syntaxhighlight lang=vb>
<lang vb>
randomize timer
randomize timer
fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same")
fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same")
Line 7,632: Line 7,632:
checkinput=array(bu,co)
checkinput=array(bu,co)
end function
end function
</syntaxhighlight>
</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>Buf_Switch(Buf_Free)
<syntaxhighlight lang=vedit>Buf_Switch(Buf_Free)
#90 = Time_Tick // seed for random number generator
#90 = Time_Tick // seed for random number generator
#91 = 10 // random numbers in range 0 to 9
#91 = 10 // random numbers in range 0 to 9
Line 7,681: Line 7,681:
#93 = 0x7fffffff % 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</lang>
Return ((#90 & 0xffff) * #91 / 0x10000)</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==


<lang vbnet>Imports System
<syntaxhighlight lang=vbnet>Imports System
Imports System.Text.RegularExpressions
Imports System.Text.RegularExpressions


Line 7,740: Line 7,740:
Console.WriteLine("The number was guessed in {0} attempts. Congratulations!", attempt)
Console.WriteLine("The number was guessed in {0} attempts. Congratulations!", attempt)
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 7,746: Line 7,746:
{{libheader|Wren-set}}
{{libheader|Wren-set}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-ioutil}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang=ecmascript>import "random" for Random
import "/set" for Set
import "/set" for Set
import "/ioutil" for Input
import "/ioutil" for Input
Line 7,798: Line 7,798:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,828: Line 7,828:
=={{header|zkl}}==
=={{header|zkl}}==
Play one game:
Play one game:
<lang zkl>d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
<syntaxhighlight lang=zkl>d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
abcd:=d.keys.shuffle();
abcd:=d.keys.shuffle();
while(1){
while(1){
Line 7,839: Line 7,839:
"%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println();
"%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println();
}
}
fcn s(n){ (n!=1) and "s" or "" }</lang>
fcn s(n){ (n!=1) and "s" or "" }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>