Bulls and cows: Difference between revisions
→{{header|Kotlin}}
(37 intermediate revisions by 21 users not shown) | |||
Line 1:
[[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.
<
putchar equ 2
rawio equ 6
Line 237 ⟶ 236:
secret: ds 4 ; Holds the secret code
bufdef: db 4,0 ; User input buffer
buf: ds 4</
=={{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!}}==
<
TYPE Score=[BYTE bulls,cows,err]
Line 317 ⟶ 400:
PrintE(", try again:")
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bulls_and_cows.png Screenshot from Atari 8-bit computer]
Line 338 ⟶ 421:
=={{header|Ada}}==
<
with Ada.Numerics.Discrete_Random;
Line 390 ⟶ 473:
end;
end loop;
end Bulls_And_Cows;</
=={{header|ALGOL 68}}==
{{trans|Python}}
Line 400 ⟶ 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]}}
<
[4]CHAR chosen;
Line 454 ⟶ 536:
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))</
Output:
<pre>
Line 462 ⟶ 544:
Next guess [1]:
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
Line 469 ⟶ 550:
Bulls and Cows in the APL session.
<
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
Line 479 ⟶ 560:
random ← 4∘⊣?9∘⊣
moo ← 'You win!'⊣(random game⊢)
</syntaxhighlight>
Line 486 ⟶ 567:
referred to twice. The following definition of <code>moo</code> is exactly equivalent to the above:
<
=={{header|AppleScript}}==
GUI implementation; the prompt for a guess includes a list of all past guesses and their scores.
<
set theNumber to ""
repeat 4 times
Line 550 ⟶ 629:
end if
end repeat
end run</
=={{header|Arturo}}==
<
bulls: 0
Line 574 ⟶ 652:
]
]
print color #green "** Well done! You made the right guess!!"</
=={{header|AutoHotkey}}==
<
While StrLen(Code) < length {
Line 628 ⟶ 705:
Cows++
Return Bulls "," Cows
}</
=={{header|AWK}}==
<
BEGIN {
srand()
Line 684 ⟶ 760:
}
return bulls == 4
}</
{{out}}
<pre>
Line 706 ⟶ 782:
Congratulations, you win!
</pre>
=={{header|BASIC}}==
{{works with|QBasic}}
<
DIM secret AS STRING
Line 749 ⟶ 824:
END IF
looper:
LOOP</
==={{header|Applesoft BASIC}}===
<
110 FOR I = 1 TO 4
120 P = INT(RND(1) * LEN(D$)) + 1
Line 779 ⟶ 854:
380 PRINT B " BULLS, " C " COWS"
390 Q = G$ = N$
400 NEXT Q</
==={{header|Commodore BASIC}}===
Line 789 ⟶ 864:
* Other formatting (clear screen, etc.) unique to Commodore BASIC.
<
110 FOR I=1 TO 4
120 P=INT(RND(1)*LEN(D$))+1
Line 827 ⟶ 902:
730 IF NOT M THEN NEXT J,I
740 RETURN
</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 RANDOMIZE
120 STRING C$*4
Line 860 ⟶ 935:
380 IF POS(S$(:I-1),S$(I)) OR POS(S$(I+1:),S$(I)) THEN LET CHECK$=""
390 NEXT
400 END DEF</
==={{header|ZX Spectrum Basic}}===
{{trans|QBasic}}
<
20 FOR i=1 TO 4
30 LET d=INT (RND*9+1)
Line 883 ⟶ 958:
180 IF c$=g$ THEN PRINT "You won after ";guesses;" guesses!": GO TO 10
190 GO TO 90
</syntaxhighlight>
=={{header|Batch File}}==
<
:: Batch File Implementation
Line 986 ⟶ 1,060:
set /p "opt=Play again? "
if /i "!opt!" equ "y" goto begin
exit /b 0</
{{Out}}
<pre>
Line 1,031 ⟶ 1,105:
Play again? </pre>
=={{header|BBC BASIC}}==
<
REPEAT
c$ = CHR$(&30 + RND(9))
Line 1,065 ⟶ 1,138:
UNTIL FALSE
</syntaxhighlight>
=={{header|BCPL}}==
<
static $( randstate = ? $)
Line 1,137 ⟶ 1,209:
gensecret(secret)
play(secret)
$)</
{{out}}
<pre>Bulls and cows
Line 1,163 ⟶ 1,235:
You win in 9 tries.</pre>
=={{header|Brat}}==
<
secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
Line 1,201 ⟶ 1,273:
guesses = guesses + 1
}
}</
=={{header|C}}==
{{libheader|ncurses}}
<
#include <stdarg.h>
#include <stdlib.h>
Line 1,264 ⟶ 1,335:
}
}
}</
The following function contains the code to check how many bulls and cows there are.
<
{
int i;
Line 1,352 ⟶ 1,423:
nocbreak(); echo(); endwin();
return EXIT_SUCCESS;
}</
=={{header|C sharp|C#}}==
<
namespace BullsnCows
Line 1,434 ⟶ 1,504:
}
}
</syntaxhighlight>
=={{header|C++}}==
<
#include <string>
#include <algorithm>
Line 1,514 ⟶ 1,583:
std::cout << "Another game? ";
}
}</
=={{header|Ceylon}}==
<
DefaultRandom
}
Line 1,586 ⟶ 1,654:
}
}
}</
=={{header|Clojure}}==
<
(ns bulls-and-cows)
Line 1,628 ⟶ 1,695:
(bulls-and-cows)
</syntaxhighlight>
=={{header|CLU}}==
<
% to use the random number generator.
%
Line 1,762 ⟶ 1,828:
stream$putl(po, "Bulls and cows\n----- --- ----\n")
play_game(make_secret())
end start_up</
{{out}}
<pre>Bulls and cows
Line 1,778 ⟶ 1,844:
Bulls: 4, cows: 0
Congratulations! You won in 5 tries.</pre>
=={{header|Coco}}==
Line 1,785 ⟶ 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:
<
prompt = (str) ->
putstr str
readline! ? quit!</
We can now solve the task using <code>say</code> and <code>prompt</code>:
<
secret = _.sample ['1' to '9'], SIZE
Line 1,813 ⟶ 1,878:
say "#bulls bull#{[if bulls !== 1 then 's']}, #cows cow#{[if cows !== 1 then 's']}."
say 'A winner is you!'</
=={{header|Common Lisp}}==
<
(do ((digits '()))
((>= (length digits) 4) digits)
Line 1,857 ⟶ 1,921:
(format stream "~&Correct, you win!")
(format stream "~&Score: ~a cows, ~a bulls."
cows bulls)))))))</
=={{header|Crystal}}==
{{trans|Ruby}}
<
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
Line 1,895 ⟶ 1,958:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</
=={{header|D}}==
<
import std.stdio, std.random, std.string, std.algorithm,
std.range, std.ascii;
Line 1,915 ⟶ 1,977:
" Bad guess! (4 unique digits, 1-9)".writeln;
}
}</
{{out}}
<pre>Next guess: 6548
Line 1,938 ⟶ 2,000:
=={{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}}==
Note: This example was deliberately written in an abstracted style, separating out the algorithms, game logic, and UI.
<
def Number := Tuple[Digit,Digit,Digit,Digit]
Line 2,023 ⟶ 2,211:
return gameTurn()
}</
===REPL user interface===
Line 2,045 ⟶ 2,233:
{{works with|E-on-Java}} (Java Swing)
<
var lastGuess := ""
def op := <unsafe:javax.swing.makeJOptionPane>
Line 2,059 ⟶ 2,247:
op.showMessageDialog(null, msg)
}, entropy)
}</
=={{header|EasyLang}}==
<syntaxhighlight>
dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for
h = i - 1 + randint (10 - i)
swap dig[i] dig[h]
.
# print dig[]
Line 2,071 ⟶ 2,260:
attempts = 0
repeat
repeat
ok = 0
s$[] = strchars input
if len s$[] = 4
ok = 1
for i
g[i] = number s$[i]
if g[i] = 0
ok = 0
.
.
.
.
print g[]
attempts += 1
for j = 1 to 4
.
.
print "bulls:" & bulls & " cows:" & cows
.
print "Well done! " & attempts & " attempts needed."</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
BULLS_AND_COWS
Line 2,219 ⟶ 2,408:
end
</syntaxhighlight>
{{out}}
<pre>
Line 2,246 ⟶ 2,435:
Congratulations! You won with 6 guesses.
</pre>
=={{header|Elena}}==
ELENA
<
import extensions;
class GameMaster
{
field _numbers;
field _attempt;
}
catch(Exception
}
};
}
public program()
{
var process := $lazy gameMaster.proceed(gameMaster.ask());
}</
{{out}}
<pre>
Line 2,357 ⟶ 2,547:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
Line 2,398 ⟶ 2,588:
end
Bulls_and_cows.play</
{{out}}
Line 2,413 ⟶ 2,603:
You win!
</pre>
=={{header|Erlang}}==
Module:
<
-export([generate_secret/0, score_guess/2, play/0]).
Line 2,460 ⟶ 2,649:
read_guess() ->
lists:map(fun(D)->D-48 end,
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).</
Script:
<
% Play Bulls and Cows
main(_) -> random:seed(now()), bulls_and_cows:play().</
Sample play:<pre>Enter your 4-digit guess: 8376
Line 2,478 ⟶ 2,667:
Correct!
</pre>
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<
include std\os.e
include std\sequence.e
Line 2,586 ⟶ 2,774:
</syntaxhighlight>
Output :
<pre>
Line 2,609 ⟶ 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}}==
<
locals math math.parser math.ranges random sequences strings
io ascii ;
Line 2,674 ⟶ 2,984:
[ main-loop ] [ drop win ] if ;
: main ( -- ) new-number drop narr>nhash main-loop ;</
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
Line 2,726 ⟶ 3,035:
}
}
}</
=={{header|FOCAL}}==
<
01.20 S T=0;D 3
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
Line 2,762 ⟶ 3,070:
05.70 I (-FABS(S(X)-G(Y)))5.5,5.9
05.80 S B=B+1
05.90 S C=C+1</
{{out}}
Line 2,794 ⟶ 3,102:
YOU WON! GUESSES= 8</pre>
=={{header|Forth}}==
{{works with|GNU Forth}}
<
create hidden 4 allot
Line 2,833 ⟶ 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 ;</
{{out}}
<pre>init ok
Line 2,841 ⟶ 3,148:
guess: 1879 4 bulls, 0 cows
You guessed it! ok</pre>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 2,927 ⟶ 3,233:
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
end program Bulls_and_Cows</
=={{header|Frink}}==
<
// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]
Line 3,138 ⟶ 3,319:
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]
</syntaxhighlight>
{{Out}}
<pre>
Line 3,152 ⟶ 3,333:
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}}==
<
import (
Line 3,221 ⟶ 3,516:
}
}
}</
=={{header|Golo}}==
<
----
This module is the Bulls and Cows game.
Line 3,323 ⟶ 3,617:
}
}
</syntaxhighlight>
=={{header|Groovy}}==
<
static void main(args) {
def inputReader = System.in.newReader()
Line 3,372 ⟶ 3,665:
}
</syntaxhighlight>
=={{header|Haskell}}==
<
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
Line 3,424 ⟶ 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</
=={{header|Hy}}==
<
(def +size+ 4)
Line 3,453 ⟶ 3,744:
cows (if (= cows 1) "" "s"))))
(print "A winner is you!")</
=={{header|Icon}} and {{header|Unicon}}==
The following works in both Icon and Unicon.
<
digits := "123456789"
every !digits :=: ?digits
Line 3,482 ⟶ 3,772:
write("\t",bulls," bulls and ",cows," cows")
return (bulls = *num)
end</
=={{header|J}}==
<
plural=: conjunction define
Line 3,508 ⟶ 3,797:
end.
smoutput 'you win'
)</
For example:
<
Guess my number: 1234
0 bulls and 1 cow.
Line 3,527 ⟶ 3,816:
Guess my number: 5178
4 bulls and 0 cows.
you win</
=={{header|Java}}==
<
import java.util.Random;
import java.util.Scanner;
Line 3,581 ⟶ 3,869:
return false;
}
}</
Output:
<pre>Guess a 4-digit number with no duplicate digits: 5834
Line 3,603 ⟶ 3,891:
Guess a 4-digit number with no duplicate digits: 3957
You won after 10 guesses!</pre>
=={{header|JavaScript}}==
=== Spidermonkey version ===
<
function main() {
Line 3,694 ⟶ 3,981:
main();
</syntaxhighlight>
Example game (cheating!):
Line 3,724 ⟶ 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}}==
<
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 3,757 ⟶ 4,139:
end
end
end</
The following version checks thoroughly that the input of the player is constituted of four distincts digits.
<
bulls = cows = turns = 0
result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
Line 3,775 ⟶ 4,157:
end
println("You win! You succeeded in $turns guesses.")
end</
{{Out}}
<pre>julia> bullsandcows()
Line 3,794 ⟶ 4,176:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
const val MAX_GUESSES = 20 // say
fun main(
val num = ('1'..'9').shuffled().take(4).joinToString("")
println("All guesses should have exactly 4 distinct digits excluding zero.")
Line 3,813 ⟶ 4,188:
while (true) {
print("Enter your guess : ")
val guess =
if (guess == num) {
println("You've won with ${++guesses} valid guesses!")
}
val n = guess.toIntOrNull()
Line 3,842 ⟶ 4,217:
}
}
}</
Sample input/output:
{{out}}
Line 3,868 ⟶ 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">[
define randomizer() => {
local(n = string)
Line 3,938 ⟶ 4,313:
'<a href="?restart">Restart</a>'
^}]
</syntaxhighlight>
{{out}}
Line 3,981 ⟶ 4,356:
5493: Bulls: 4, Cows: 0 - YOU WIN!
Restart</pre>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
do while len( secret$) <4
Line 4,046 ⟶ 4,420:
close #w
end
</syntaxhighlight>
=={{header|Logo}}==
{{works with|UCB Logo}}
<
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end
Line 4,068 ⟶ 4,441:
(print :bulls "bulls, :cows "cows)
if :bulls = 4 [print [You guessed it!]]
end</
=={{header|Lua}}==
<
for i=1,#array-1 do
local t = math.random(i, #array)
Line 4,171 ⟶ 4,543:
print("\nGoodbye!")
end
until quit</
Another version:
<
math.randomseed(os.time())
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Line 4,237 ⟶ 4,609:
end
end
end</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Game {
Malformed=lambda (a$)->{
Line 4,289 ⟶ 4,660:
}
Game
</syntaxhighlight>
=={{header|Maple}}==
<
local target, win, numGuesses, guess, bulls, cows, i, err;
target := [0, 0, 0, 0]:
Line 4,346 ⟶ 4,716:
end if;
return NULL;
end proc:</
{{out}}
<pre>
Line 4,359 ⟶ 4,729:
...
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
Line 4,372 ⟶ 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."]]]]]]]</
Output:
<pre>{8, 2, 6, 1}
Line 4,378 ⟶ 4,747:
Illegal input.
8261: You got it!</pre>
=={{header|MATLAB}}==
<
% Plays the game Bulls and Cows as the "game master"
Line 4,441 ⟶ 4,809:
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end</
{{out}}
<pre>Welcome to Bulls and Cows!
Line 4,471 ⟶ 4,839:
Try again: 4368
You win! Bully for you! Only 8 guesses.</pre>
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
numCount = 4 -- number of digits to use
Line 4,542 ⟶ 4,909:
format "\nBulls: % Cows: %\n" bulls cows
)
)</
{{out}}
<syntaxhighlight lang="text">
OK
Rules:
Line 4,565 ⟶ 4,932:
Enter your number: 1357
Bulls: 0 Cows: 1
</syntaxhighlight>
=={{header|MiniScript}}==
<
secret.shuffle
secret = secret[:4].join("")
Line 4,593 ⟶ 4,959:
print "You score " + bulls + " bull" + "s"*(bulls!=1) +
" and " + cows + " cow" + "s"*(cows!=1) + "."
end while</
{{out}}
<pre>Your guess? 2385
Line 4,606 ⟶ 4,972:
Your guess? 8642
You got it! Great job!</pre>
=={{header|MUMPS}}==
<
Set number="",x=1234567890
For ii=1:1:4 Do
Line 4,672 ⟶ 5,037:
Your guess: 2907
You guessed 2907. That earns you 4 bulls.
That's a perfect score.</
=={{header|Nanoquery}}==
{{trans|Python}}
<
// a function to verify the user's input
Line 4,741 ⟶ 5,105:
end
println "\nCongratulations you guess correctly in " + guesses + " attempts"</
{{out}}
Line 4,764 ⟶ 5,128:
Congratulations you guess correctly in 11 attempts</pre>
=={{header|Nim}}==
{{trans|Python}}
<
randomize()
Line 4,806 ⟶ 5,169:
if guess[i] == chosen[i]: inc bulls
elif guess[i] in chosen: inc cows
echo &" {bulls} Bull{plural(bulls)}\n {cows} Cow{plural(cows)}"</
{{out}}
Line 4,828 ⟶ 5,191:
Congratulations! You guessed correctly in 4 attempts.</pre>
=={{header|OCaml}}==
<
let s = read_line () in
try
Line 4,879 ⟶ 5,241:
done;
print_endline "Congratulations you guessed correctly";
;;</
=={{header|Oforth}}==
<
| numbers guess digits bulls cows |
Line 4,900 ⟶ 5,261:
guess filter(#[numbers include]) size bulls - ->cows
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
] ;</
=={{header|ooRexx}}==
The solution at [[#Version_2|Rexx Version 2]] is a valid ooRexx program.
=={{header|Oz}}==
<
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
Line 4,974 ⟶ 5,333:
fun {Id X} X end
in
{Main}</
=={{header|PARI/GP}}==
This simple implementation expects guesses in the form [a,b,c,d].
<
my(u,v,bulls,cows);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
Line 4,988 ⟶ 5,346:
print("You have "bulls" bulls and "cows" cows")
)
};</
=={{header|Pascal}}==
<
{$mode objFPC}
Line 5,179 ⟶ 5,536:
end.
</syntaxhighlight>
=={{header|Perl}}==
<
use List::MoreUtils qw(uniq);
Line 5,220 ⟶ 5,576:
my $g = shift;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
}</
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\BullsAndCows.exw
Line 5,298 ⟶ 5,653:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</
{{out}}
<small>(as shown in the res label)</small>
Line 5,311 ⟶ 5,666:
Well done!
</pre>
=={{header|PHP}}==
<
$size = 4;
Line 5,352 ⟶ 5,706:
preg_match("/^[1-9]{{$size}}$/", $g);
}
?></
=={{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}}==
<
(let D (mapcar 'format (chop N))
(and (num? N)
Line 5,375 ⟶ 5,763:
(pack Bulls " bulls, " Cows " cows") ) ) )
" Bad guess! (4 unique digits, 1-9)" ) ) )
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
Line 5,426 ⟶ 5,813:
Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
</syntaxhighlight>
{{Out}}
<pre>
Line 5,442 ⟶ 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.
<
StringList choices;
StringList guess;
Line 5,507 ⟶ 5,893:
}
return result;
}</
=={{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'''.
<
:- use_module(library(clpfd)).
Line 5,567 ⟶ 5,952:
Solution, 0, TT),
Cows is TT - Bulls.
</syntaxhighlight>
=={{header|PureBasic}}==
<
Define.i bulls, cows, guesses, i
Line 5,639 ⟶ 6,023:
Input()
CloseConsole()
EndIf</
=={{header|Python}}==
<
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
Line 5,674 ⟶ 6,057:
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)</
Sample output:
<pre>I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.
Line 5,689 ⟶ 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}}
<
bulls <- 0
cows <- 0
Line 5,710 ⟶ 6,214:
} else {print("Malformed input!")}
}
print(paste("You won in",attempts,"attempt(s)!"))</
=={{header|Racket}}==
<
#lang racket
Line 5,772 ⟶ 6,275:
(main-loop state (add1 step))))))))))
(main-loop game 0)</
Output:
Line 5,795 ⟶ 6,298:
You won after 8 guesses.
</pre>
=={{header|Raku}}==
(formerly Perl 6)
Line 5,802 ⟶ 6,304:
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
my @secret = pick $size, '1' .. '9';
Line 5,822 ⟶ 6,324:
}
say 'A winner is you!';</
=={{header|Red}}==
<syntaxhighlight lang="red">
Red[]
a: "0123456789"
Line 5,842 ⟶ 6,343:
]
print "You won!"
</syntaxhighlight>
=={{header|REXX}}==
This game is also known as:
Line 5,851 ⟶ 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 5,857 ⟶ 6,358:
<br>and also change the prompt message.
<br>The REXX statement that contains the '''translate''' statement can be removed if repeated digits aren't allowed.
<
?=; 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. */
Line 5,883 ⟶ 6,384:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */</
===Version 2===
<
/*REXX program to play the game of "Bulls & Cows". *******************
* Changes from Version 1:
Line 5,988 ⟶ 6,489:
ser: Say '*** error ***' arg(1); Return
</syntaxhighlight>
=={{header|Ring}}==
<
# Project : Bulls and cows
Line 6,031 ⟶ 6,532:
see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
end
</syntaxhighlight>
=={{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+}}
<
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
end
Line 6,076 ⟶ 6,606:
puts "that guess has %d bulls and %d cows" % score(word, guess)
end
puts "you guessed correctly in #{count} tries."</
Inspired by Python
{{works with|Ruby|2.0+}}
<
secret = [*'1' .. '9'].sample(size)
guess = nil
Line 6,114 ⟶ 6,644:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</
=={{header|Rust}}==
{{libheader|rand}}
<
use rand::{Rng,thread_rng};
Line 6,199 ⟶ 6,729:
}
}
}</
=={{header|Scala}}==
<
object BullCow {
Line 6,243 ⟶ 6,772:
def hasDups(input:List[Int])=input.size!=input.distinct.size
}</
=={{header|Scheme}}==
{{works with|any R6RS Scheme}}
<
;generate a random non-repeating list of 4 digits, 1-9 inclusive
Line 6,315 ⟶ 6,843:
(bull-cow (get-num))
</syntaxhighlight>
=== Sample game play ===
Line 6,342 ⟶ 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>
Line 6,354 ⟶ 6,881:
<br>
Since Scratch is an educational language, I've included comments in the code to explain what the program is doing.<br>
=={{header|Seed7}}==
<
const proc: main is func
Line 6,404 ⟶ 6,930:
until guess = chosen;
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
end func;</
{{out}}
Line 6,422 ⟶ 6,948:
Congratulations you guessed correctly in 4 attempts
</pre>
=={{header|SenseTalk}}==
<
repeat forever
put random(1111,9999) into num
Line 6,500 ⟶ 7,025:
end if
end repeat
end repeat</
=={{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}}==
<
maths library
Line 6,623 ⟶ 7,235:
init()
play()</
{{out}}
Line 6,674 ⟶ 7,286:
=={{header|Sidef}}==
<
var num = @(1..9).shuffle.first(size)
Line 6,709 ⟶ 7,321:
"Bulls: %d; Cows: %d\n".printf(bulls, cows)
}</
{{out}}
<pre>
Line 6,721 ⟶ 7,333:
You did it in 4 attempts!
</pre>
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
|number|
BullsCows class >> new: secretNum [ |i|
Line 6,781 ⟶ 7,392:
'Do you want to play again? [y/n]' display.
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ].</
=={{header|Smart BASIC}}==
<
'by rbytes, January 2017
OPTION BASE 1
Line 6,872 ⟶ 7,482:
END DEF
END
</syntaxhighlight>
=={{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>
<
func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
Line 6,934 ⟶ 7,605:
exit(0)
}
}</
{{out}}
Line 6,952 ⟶ 7,623:
=={{header|Tcl}}==
<
fconfigure stdout -buffering none
set length 4
Line 7,036 ⟶ 7,707:
}
main</
=={{header|Transd}}==
{{trans|C++}}
<
MainModule: {
Line 7,050 ⟶ 7,719:
),
play: (λ locals:
syms "0123456789"
len 4
Line 7,070 ⟶ 7,739:
(with bulls 0 cows 0 pl 0
(for i in Range(len) do
(= pl (
(if (eq pl i) (+= bulls 1)
elsif (neq pl -1) (+= cows 1))
Line 7,084 ⟶ 7,753:
),
_start: (λ locals: s String()
(lout "Welcome to \"Bulls and cows\"!")
(while true
(while true
(textout "Do you want to play? (yes|no) : ")
(
(if (not (size s))
(lout "Didn't receive an answer. Exiting.") (exit)
Line 7,098 ⟶ 7,767:
(play)
(lout "Another game?")
)
)
}</syntaxhighlight>
=={{header|TUSCRIPT}}==
<
$$ MODE tuscript
SET nr1=RANDOM_NUMBERS (1,9,1)
Line 7,143 ⟶ 7,811:
ENDIF
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 7,158 ⟶ 7,826:
BINGO
</pre>
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Local(2) ' Let's use no globals
Proc _Initialize ' Get our secret number
Line 7,237 ⟶ 7,904:
Next ' Increment with valid digits
Next
Return (c@) ' Return number of valid digits</
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}}
<
rand() {
Line 7,391 ⟶ 8,102:
[ "${guess}" == "${secret}" ] && echo "You win!" && exit
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
done</
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 7,469 ⟶ 8,179:
AskToUser = strIn
End Function
</syntaxhighlight>
=={{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
bu=c(0)
wscript.stdout.write "bulls: " & c(0) & " | cows: " & c(1)
Line 7,502 ⟶ 8,211:
function checkinput(s)
dim c(10)
bu=0:co=0
if len(s)<>4 then checkinput=
for i=1 to 4
b=mid(s,i,1)
if instr("0123456789",b)=0 then checkinput=
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
Line 7,515 ⟶ 8,227:
checkinput=array(bu,co)
end function
</syntaxhighlight>
=={{header|Vedit macro language}}==
<
#90 = Time_Tick // seed for random number generator
#91 = 10 // random numbers in range 0 to 9
Line 7,564 ⟶ 8,275:
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</
=={{header|Visual Basic .NET}}==
<
Imports System.Text.RegularExpressions
Line 7,623 ⟶ 8,333:
Console.WriteLine("The number was guessed in {0} attempts. Congratulations!", attempt)
End Sub
End Module</
=={{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}}==
Line 7,629 ⟶ 8,496:
{{libheader|Wren-set}}
{{libheader|Wren-ioutil}}
<
import "./set" for Set
import "./ioutil" for Input
var MAX_GUESSES = 20 // say
Line 7,654 ⟶ 8,521:
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")
Line 7,681 ⟶ 8,550:
}
}
}</
{{out}}
Line 7,707 ⟶ 8,576:
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:
<
abcd:=d.keys.shuffle();
while(1){
Line 7,722 ⟶ 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 "" }</
{{out}}
<pre>
|