Bulls and cows: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task|Games}}
[[Category:Puzzles]]
[[Category:Games]]
{{task|Games}}
 
[[wp:Bulls and Cows|Bulls and Cows]]   is an old game played with pencil and paper that was later implemented using computers.
Line 27:
*   [[Mastermind]]
<br><br>
 
=={{header|8080 Assembly}}==
 
This is written to run under CP/M and includes an RNG to generate the secret.
 
<syntaxhighlight lang="8080asm">bdos equ 5
putchar equ 2
rawio equ 6
Line 238 ⟶ 237:
bufdef: db 4,0 ; User input buffer
buf: ds 4</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">DEFINE DIGNUM="4"
 
TYPE Score=[BYTE bulls,cows,err]
Line 336 ⟶ 334:
You win!
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 391 ⟶ 388:
end loop;
end Bulls_And_Cows;</syntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|Python}}
Line 400 ⟶ 396:
 
{{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]}}
<syntaxhighlight lang="algol68">STRING digits = "123456789";
 
[4]CHAR chosen;
Line 462 ⟶ 458:
Next guess [1]:
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
Line 469 ⟶ 464:
Bulls and Cows in the APL session.
 
<syntaxhighlight lang=APL"apl">input ← {⍞←'Guess: ' ⋄ 7↓⍞}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
Line 486 ⟶ 481:
referred to twice. The following definition of <code>moo</code> is exactly equivalent to the above:
 
<syntaxhighlight lang=APL"apl">moo←'You win!'⊣((4∘⊣?9∘⊣)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢)</syntaxhighlight>
 
 
=={{header|AppleScript}}==
 
GUI implementation; the prompt for a guess includes a list of all past guesses and their scores.
 
<syntaxhighlight lang="applescript">on pickNumber()
set theNumber to ""
repeat 4 times
Line 551 ⟶ 544:
end repeat
end run</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0
 
Line 575 ⟶ 567:
]
print color #green "** Well done! You made the right guess!!"</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">length:=4, Code:="" ; settings
 
While StrLen(Code) < length {
Line 629 ⟶ 620:
Return Bulls "," Cows
}</syntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk"># Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
srand()
Line 706 ⟶ 696:
Congratulations, you win!
</pre>
 
=={{header|BASIC}}==
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">DEFINT A-Z
 
DIM secret AS STRING
Line 752 ⟶ 741:
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang=ApplesoftBasic"applesoftbasic">100 D$ = "123456789"
110 FOR I = 1 TO 4
120 P = INT(RND(1) * LEN(D$)) + 1
Line 789 ⟶ 778:
* Other formatting (clear screen, etc.) unique to Commodore BASIC.
 
<syntaxhighlight lang=FreeBasic"freebasic">100 D$="123456789"
110 FOR I=1 TO 4
120 P=INT(RND(1)*LEN(D$))+1
Line 830 ⟶ 819:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">100 PROGRAM "Bulls.bas"
110 RANDOMIZE
120 STRING C$*4
Line 864 ⟶ 853:
==={{header|ZX Spectrum Basic}}===
{{trans|QBasic}}
<syntaxhighlight lang="zxbasic">10 DIM n(10): LET c$=""
20 FOR i=1 TO 4
30 LET d=INT (RND*9+1)
Line 884 ⟶ 873:
190 GO TO 90
</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">:: Bulls and Cows Task from Rosetta Code
:: Batch File Implementation
Line 1,031 ⟶ 1,019:
 
Play again? </pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> secret$ = ""
REPEAT
c$ = CHR$(&30 + RND(9))
Line 1,066 ⟶ 1,053:
UNTIL FALSE
</syntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
static $( randstate = ? $)
Line 1,163 ⟶ 1,149:
You win in 9 tries.</pre>
=={{header|Brat}}==
<syntaxhighlight lang="brat">secret_length = 4
 
secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
Line 1,202 ⟶ 1,188:
}
}</syntaxhighlight>
 
=={{header|C}}==
{{libheader|ncurses}}
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
Line 1,268 ⟶ 1,253:
The following function contains the code to check how many bulls and cows there are.
 
<syntaxhighlight lang="c">bool take_it_or_not()
{
int i;
Line 1,353 ⟶ 1,338:
return EXIT_SUCCESS;
}</syntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
namespace BullsnCows
Line 1,435 ⟶ 1,419:
}
</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <algorithm>
Line 1,515 ⟶ 1,498:
}
}</syntaxhighlight>
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
}
Line 1,587 ⟶ 1,569:
}
}</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(ns bulls-and-cows)
Line 1,629 ⟶ 1,610:
(bulls-and-cows)
</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
Line 1,778 ⟶ 1,758:
Bulls: 4, cows: 0
Congratulations! You won in 5 tries.</pre>
 
=={{header|Coco}}==
 
Line 1,785 ⟶ 1,764:
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:
 
<syntaxhighlight lang="coco">say = print
prompt = (str) ->
putstr str
Line 1,792 ⟶ 1,771:
We can now solve the task using <code>say</code> and <code>prompt</code>:
 
<syntaxhighlight lang="coco">const SIZE = 4
 
secret = _.sample ['1' to '9'], SIZE
Line 1,814 ⟶ 1,793:
 
say 'A winner is you!'</syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun get-number ()
(do ((digits '()))
((>= (length digits) 4) digits)
Line 1,858 ⟶ 1,836:
(format stream "~&Score: ~a cows, ~a bulls."
cows bulls)))))))</syntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang=Ruby"ruby">size = 4
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
Line 1,896 ⟶ 1,873:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.string, std.algorithm,
std.range, std.ascii;
Line 1,942 ⟶ 1,918:
Note: This example was deliberately written in an abstracted style, separating out the algorithms, game logic, and UI.
 
<syntaxhighlight lang="e">def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]
 
Line 2,045 ⟶ 2,021:
{{works with|E-on-Java}} (Java Swing)
 
<syntaxhighlight lang="e">def guiBullsAndCows() {
var lastGuess := ""
def op := <unsafe:javax.swing.makeJOptionPane>
Line 2,060 ⟶ 2,036:
}, entropy)
}</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
h = i + random (9 - i)
Line 2,104 ⟶ 2,079:
.
print "Well done! " & attempts & " attempts needed."</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang=Eiffel"eiffel">
class
BULLS_AND_COWS
Line 2,246 ⟶ 2,220:
Congratulations! You won with 6 guesses.
</pre>
 
=={{header|Elena}}==
ELENA 5.0 :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
 
Line 2,354 ⟶ 2,327:
Congratulations! You have won!
</pre>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<syntaxhighlight lang="elixir">defmodule Bulls_and_cows do
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
Line 2,413 ⟶ 2,385:
You win!
</pre>
 
=={{header|Erlang}}==
Module:
<syntaxhighlight lang="erlang">-module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).
 
Line 2,463 ⟶ 2,434:
 
Script:
<syntaxhighlight lang="erlang">#!/usr/bin/escript
% Play Bulls and Cows
main(_) -> random:seed(now()), bulls_and_cows:play().</syntaxhighlight>
Line 2,478 ⟶ 2,449:
Correct!
</pre>
 
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<syntaxhighlight lang="euphoria">include std\text.e
include std\os.e
include std\sequence.e
Line 2,609 ⟶ 2,579:
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}}==
<syntaxhighlight lang=Factor"factor">USING: accessors assocs combinators fry grouping hashtables kernel
locals math math.parser math.ranges random sequences strings
io ascii ;
Line 2,675 ⟶ 2,767:
 
: main ( -- ) new-number drop narr>nhash main-loop ;</syntaxhighlight>
 
=={{header|Fan}}==
<syntaxhighlight lang=Fan"fan">**
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
Line 2,727 ⟶ 2,818:
}
}</syntaxhighlight>
 
=={{header|FOCAL}}==
<syntaxhighlight lang=FOCAL"focal">01.10 T %1,"BULLS AND COWS"!"----- --- ----"!!
01.20 S T=0;D 3
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
Line 2,794 ⟶ 2,884:
 
YOU WON! GUESSES= 8</pre>
 
=={{header|Forth}}==
{{works with|GNU Forth}}
<syntaxhighlight lang="forth">include random.fs
 
create hidden 4 allot
Line 2,841 ⟶ 2,930:
guess: 1879 4 bulls, 0 cows
You guessed it! ok</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<syntaxhighlight lang="fortran">module bac
implicit none
 
Line 2,928 ⟶ 3,016:
 
end program Bulls_and_Cows</syntaxhighlight>
 
=={{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|Frink}}==
<syntaxhighlight lang="frink">
// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]
Line 3,152 ⟶ 3,115:
Congratulations! Your guess of 6431 was correct! You solved this in 9 guesses.
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 3,222 ⟶ 3,184:
}
}</syntaxhighlight>
 
=={{header|Golo}}==
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
This module is the Bulls and Cows game.
Line 3,324 ⟶ 3,285:
}
</syntaxhighlight>
 
=={{header|Groovy}}==
<syntaxhighlight lang=Groovy"groovy">class BullsAndCows {
static void main(args) {
def inputReader = System.in.newReader()
Line 3,373 ⟶ 3,333:
 
</syntaxhighlight>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.List (partition, intersect, nub)
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
Line 3,425 ⟶ 3,384:
where (i, g') = randomR (0, max) g
(left, picked : right) = splitAt i l</syntaxhighlight>
 
=={{header|Hy}}==
 
<syntaxhighlight lang="lisp">(import random)
 
(def +size+ 4)
Line 3,454 ⟶ 3,412:
(print "A winner is you!")</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
The following works in both Icon and Unicon.
 
<syntaxhighlight lang=Unicon"unicon">procedure main()
digits := "123456789"
every !digits :=: ?digits
Line 3,483 ⟶ 3,440:
return (bulls = *num)
end</syntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j">require 'misc'
plural=: conjunction define
Line 3,512 ⟶ 3,468:
For example:
 
<syntaxhighlight lang="j"> bullcow''
Guess my number: 1234
0 bulls and 1 cow.
Line 3,528 ⟶ 3,484:
4 bulls and 0 cows.
you win</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java5">import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
Line 3,603 ⟶ 3,558:
Guess a 4-digit number with no duplicate digits: 3957
You won after 10 guesses!</pre>
 
=={{header|JavaScript}}==
=== Spidermonkey version ===
<syntaxhighlight lang="javascript">#!/usr/bin/env js
 
function main() {
Line 3,724 ⟶ 3,678:
Bulls: 4, cows: 0
You win! Guesses needed: 8
 
=={{header|Julia}}==
<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
You get one bull for every right number in the right position.\n
Line 3,759 ⟶ 3,712:
end</syntaxhighlight>
The following version checks thoroughly that the input of the player is constituted of four distincts digits.
<syntaxhighlight lang="julia">function bullsandcows ()
bulls = cows = turns = 0
result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
Line 3,792 ⟶ 3,745:
please, enter four distincts digits
Your guess? </pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
import java.util.Random
Line 3,865 ⟶ 3,817:
You've won with 9 valid guesses!
</pre>
 
=={{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"lasso">[
define randomizer() => {
local(n = string)
Line 3,981 ⟶ 3,932:
5493: Bulls: 4, Cows: 0 - YOU WIN!
Restart</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
 
do while len( secret$) <4
Line 4,047 ⟶ 3,997:
end
</syntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<syntaxhighlight lang="logo">to ok? :n
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end
Line 4,069 ⟶ 4,018:
if :bulls = 4 [print [You guessed it!]]
end</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang=Lua"lua">function ShuffleArray(array)
for i=1,#array-1 do
local t = math.random(i, #array)
Line 4,175 ⟶ 4,123:
 
Another version:
<syntaxhighlight lang=Lua"lua">function createNewNumber ()
math.randomseed(os.time())
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Line 4,238 ⟶ 4,186:
end
end</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Game {
Malformed=lambda (a$)->{
Line 4,290 ⟶ 4,237:
Game
</syntaxhighlight>
 
=={{header|Maple}}==
<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;
target := [0, 0, 0, 0]:
Line 4,359 ⟶ 4,305:
...
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
Line 4,378 ⟶ 4,323:
Illegal input.
8261: You got it!</pre>
 
=={{header|MATLAB}}==
<syntaxhighlight lang=MATLAB"matlab">function BullsAndCows
% Plays the game Bulls and Cows as the "game master"
Line 4,471 ⟶ 4,415:
Try again: 4368
You win! Bully for you! Only 8 guesses.</pre>
 
=={{header|MAXScript}}==
<syntaxhighlight lang=MAXScript"maxscript">
numCount = 4 -- number of digits to use
 
Line 4,544 ⟶ 4,487:
)</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
OK
Rules:
Line 4,566 ⟶ 4,509:
Bulls: 0 Cows: 1
</syntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript"miniscript">secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")
Line 4,606 ⟶ 4,548:
Your guess? 8642
You got it! Great job!</pre>
 
=={{header|MUMPS}}==
<syntaxhighlight lang=MUMPS"mumps">BullCow New bull,cow,guess,guessed,ii,number,pos,x
Set number="",x=1234567890
For ii=1:1:4 Do
Line 4,673 ⟶ 4,614:
You guessed 2907. That earns you 4 bulls.
That's a perfect score.</syntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang=Nanoquery"nanoquery">import Nanoquery.Util; random = new(Random)
 
// a function to verify the user's input
Line 4,764 ⟶ 4,704:
 
Congratulations you guess correctly in 11 attempts</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import random, strutils, strformat, sequtils
randomize()
 
Line 4,828 ⟶ 4,767:
 
Congratulations! You guessed correctly in 4 attempts.</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let rec input () =
let s = read_line () in
try
Line 4,880 ⟶ 4,818:
print_endline "Congratulations you guessed correctly";
;;</syntaxhighlight>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang=Oforth"oforth">: bullsAndCows
| numbers guess digits bulls cows |
 
Line 4,901 ⟶ 4,838:
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
] ;</syntaxhighlight>
 
=={{header|ooRexx}}==
The solution at [[#Version_2|Rexx Version 2]] is a valid ooRexx program.
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
Line 4,975 ⟶ 4,910:
in
{Main}</syntaxhighlight>
 
=={{header|PARI/GP}}==
This simple implementation expects guesses in the form [a,b,c,d].
<syntaxhighlight lang="parigp">bc()={
my(u,v,bulls,cows);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
Line 4,989 ⟶ 4,923:
)
};</syntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">Program BullCow;
 
{$mode objFPC}
Line 5,180 ⟶ 5,113:
end.
</syntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use Data::Random qw(rand_set);
use List::MoreUtils qw(uniq);
 
Line 5,221 ⟶ 5,153:
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
}</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\BullsAndCows.exw
Line 5,311 ⟶ 5,242:
Well done!
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
$size = 4;
 
Line 5,353 ⟶ 5,283:
}
?></syntaxhighlight>
 
=={{header|Picat}}==
{{trans|Python}}
<syntaxhighlight lang=Picat"picat">main =>
Digits = to_array("123456789"),
Size = 4,
Line 5,389 ⟶ 5,318:
).
</syntaxhighlight>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="lisp">(de ok? (N)
(let D (mapcar 'format (chop N))
(and (num? N)
Line 5,412 ⟶ 5,340:
" Bad guess! (4 unique digits, 1-9)" ) ) )
</syntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">
[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
Line 5,478 ⟶ 5,405:
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.
<syntaxhighlight lang="processing">IntDict score;
StringList choices;
StringList guess;
Line 5,544 ⟶ 5,470:
return result;
}</syntaxhighlight>
 
=={{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'''.
<syntaxhighlight lang=Prolog"prolog">:- use_module(library(lambda)).
:- use_module(library(clpfd)).
 
Line 5,604 ⟶ 5,529:
Cows is TT - Bulls.
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Define.s secret, guess, c
Define.i bulls, cows, guesses, i
 
Line 5,676 ⟶ 5,600:
CloseConsole()
EndIf</syntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">'''
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
Line 5,725 ⟶ 5,648:
 
Congratulations you guessed correctly in 2 attempts</pre>
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
Const MaxDigit = 4, Min = 1, Max = 9
Dim As String NumberToGuess, NumberToTest, Newdigit, Result
Line 5,757 ⟶ 5,679:
Loop
</syntaxhighlight>
 
 
=={{header|R}}==
{{works with|R|2.8.1}}
<syntaxhighlight lang=R"r">target <- sample(1:9,4)
bulls <- 0
cows <- 0
Line 5,780 ⟶ 5,700:
}
print(paste("You won in",attempts,"attempt(s)!"))</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 5,864 ⟶ 5,783:
You won after 8 guesses.
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 5,871 ⟶ 5,789:
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" line>my $size = 4;
my @secret = pick $size, '1' .. '9';
 
Line 5,892 ⟶ 5,810:
 
say 'A winner is you!';</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">
Red[]
a: "0123456789"
Line 5,912 ⟶ 5,829:
print "You won!"
</syntaxhighlight>
 
=={{header|REXX}}==
This game is also known as:
Line 5,926 ⟶ 5,842:
<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.
<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. */
if pos(r,?)\==0 then iterate; ?= ? || r /*don't allow a repeated digit/numeral. */
Line 5,955 ⟶ 5,871:
 
===Version 2===
<syntaxhighlight lang="rexx">
/*REXX program to play the game of "Bulls & Cows". *******************
* Changes from Version 1:
Line 6,058 ⟶ 5,974:
ser: Say '*** error ***' arg(1); Return
</syntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Bulls and cows
 
Line 6,101 ⟶ 6,016:
end
</syntaxhighlight>
 
=={{header|Ruby}}==
Inspired by Tcl
{{works with|Ruby|1.8.7+}}
<syntaxhighlight lang="ruby">def generate_word(len)
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
end
Line 6,149 ⟶ 6,063:
Inspired by Python
{{works with|Ruby|2.0+}}
<syntaxhighlight lang="ruby">size = 4
secret = [*'1' .. '9'].sample(size)
guess = nil
Line 6,184 ⟶ 6,098:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</syntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang="rust">use std::io;
use rand::{Rng,thread_rng};
 
Line 6,269 ⟶ 6,182:
}
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">import scala.util.Random
 
object BullCow {
Line 6,313 ⟶ 6,225:
def hasDups(input:List[Int])=input.size!=input.distinct.size
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{works with|any R6RS Scheme}}
 
<syntaxhighlight lang="scheme">
 
;generate a random non-repeating list of 4 digits, 1-9 inclusive
Line 6,411 ⟶ 6,322:
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,423 ⟶ 6,333:
<br>
Since Scratch is an educational language, I've included comments in the code to explain what the program is doing.<br>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 6,491 ⟶ 6,400:
Congratulations you guessed correctly in 4 attempts
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">repeat forever
repeat forever
put random(1111,9999) into num
Line 6,570 ⟶ 6,478:
end repeat
end repeat</syntaxhighlight>
 
=={{header|Shale}}==
 
<syntaxhighlight lang=Shale"shale">#!/usr/local/bin/shale
 
maths library
Line 6,741 ⟶ 6,648:
New game
></pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var size = 4
var num = @(1..9).shuffle.first(size)
 
Line 6,790 ⟶ 6,696:
You did it in 4 attempts!
</pre>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<syntaxhighlight lang="smalltalk">Object subclass: BullsCows [
|number|
BullsCows class >> new: secretNum [ |i|
Line 6,851 ⟶ 6,756:
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ].</syntaxhighlight>
 
=={{header|Smart BASIC}}==
<syntaxhighlight lang="smart BASICbasic">
'by rbytes, January 2017
OPTION BASE 1
Line 6,942 ⟶ 6,846:
END
</syntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
Line 7,019 ⟶ 6,922:
Your score: 0 bulls and 1 cows
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc main {} {
fconfigure stdout -buffering none
set length 4
Line 7,106 ⟶ 7,008:
 
main</syntaxhighlight>
 
=={{header|Transd}}==
{{trans|C++}}
<syntaxhighlight lang="scheme">
#lang transd
 
Line 7,171 ⟶ 7,072:
}
</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE tuscript
SET nr1=RANDOM_NUMBERS (1,9,1)
Line 7,227 ⟶ 7,127:
BINGO
</pre>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Local(2) ' Let's use no globals
 
Proc _Initialize ' Get our secret number
Line 7,308 ⟶ 7,207:
Return (c@) ' Return number of valid digits</syntaxhighlight>
The addition of strings allows for much simpler code.
<syntaxhighlight lang="text">Do
s = Str(1234 + RND(8643))
Until FUNC(_Check(s))
Line 7,352 ⟶ 7,251:
Next
Return (1)</syntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|bash|3}}
 
<syntaxhighlight lang="bash">#!/bin/bash
 
rand() {
Line 7,506 ⟶ 7,404:
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
done</syntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Line 7,584 ⟶ 7,481:
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")
Line 7,633 ⟶ 7,529:
end function
</syntaxhighlight>
 
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">Buf_Switch(Buf_Free)
#90 = Time_Tick // seed for random number generator
#91 = 10 // random numbers in range 0 to 9
Line 7,682 ⟶ 7,577:
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<syntaxhighlight lang="vbnet">Imports System
Imports System.Text.RegularExpressions
 
Line 7,741 ⟶ 7,635:
End Sub
End Module</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-set}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/set" for Set
import "/ioutil" for Input
Line 7,825 ⟶ 7,718:
You've won with 9 valid guesses!
</pre>
 
=={{header|zkl}}==
Play one game:
<syntaxhighlight lang="zkl">d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
abcd:=d.keys.shuffle();
while(1){
10,333

edits