Bulls and cows: Difference between revisions

(1-based index)
 
(23 intermediate revisions by 14 users not shown)
Line 237:
bufdef: db 4,0 ; User input buffer
buf: ds 4</syntaxhighlight>
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO RETURN random.digit:
RETURN choice "123456789"
 
HOW TO MAKE SECRET secret:
PUT "" IN secret
FOR i IN {1..4}:
PUT random.digit IN digit
WHILE SOME j IN {1..i-1} HAS secret item j = digit:
PUT random.digit IN digit
PUT secret^digit IN secret
 
HOW TO RETURN guess count.bulls secret:
PUT 0 IN bulls
FOR i IN {1..4}:
IF secret item i = guess item i: PUT bulls+1 IN bulls
RETURN bulls
 
HOW TO RETURN guess count.cows secret:
PUT -(guess count.bulls secret) IN cows
FOR c IN guess:
IF c in secret: PUT cows+1 IN cows
RETURN cows
 
HOW TO REPORT has.duplicates guess:
FOR i IN {1..3}:
FOR j IN {i+1..4}:
IF guess item i = guess item j: SUCCEED
FAIL
 
HOW TO REPORT is.valid guess:
IF SOME digit IN guess HAS digit not.in "123456789":
WRITE "Invalid digit: ", digit/
FAIL
IF #guess <> 4:
WRITE "Guess must contain 4 digits."/
FAIL
IF has.duplicates guess:
WRITE "No duplicates allowed"/
FAIL
SUCCEED
 
HOW TO READ GUESS guess:
WHILE 1=1:
WRITE "Guess? "
READ guess RAW
IF is.valid guess: QUIT
 
HOW TO PLAY BULLS AND COWS:
PUT 0, 0, 0 IN tries, bulls, cows
MAKE SECRET secret
WRITE "Bulls and cows"/
WRITE "--------------"/
WRITE /
WHILE bulls<>4:
READ GUESS guess
PUT guess count.bulls secret IN bulls
PUT guess count.cows secret IN cows
WRITE "Bulls:",bulls,"- Cows:",cows/
PUT tries+1 IN tries
WRITE "You win! Tries:", tries
 
PLAY BULLS AND COWS</syntaxhighlight>
{{out}}
<pre>Bulls and cows
--------------
 
Guess? 1234
Bulls: 0 - Cows: 1
Guess? 5678
Bulls: 0 - Cows: 2
Guess? 1679
Bulls: 0 - Cows: 2
Guess? 1689
Bulls: 0 - Cows: 2
Guess? 1659
Bulls: 1 - Cows: 2
Guess? 2659
Bulls: 1 - Cows: 2
Guess? 3659
Bulls: 1 - Cows: 3
Guess? 9356
Bulls: 4 - Cows: 0
You win! Tries: 8</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE DIGNUM="4"
Line 334 ⟶ 419:
You win!
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
Line 1,914 ⟶ 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}}==
 
Line 2,036 ⟶ 2,248:
}, entropy)
}</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i = 1 to 4
h = i - 1 + randomrandint (10 - i)
swap dig[i] dig[h]
.
# print dig[]
Line 2,047 ⟶ 2,260:
attempts = 0
repeat
repeat
ok = 0
s$[] = strchars input
if len s$[] = 4
ok = 1
for i = 1 to 4
g[i] = number s$[i]
if g[i] = 0
ok = 0
.
.
.
. until ok = 1
.
until ok = 1
print g[]
.
attempts += 1
print g[]
attempts +bulls = 10
bulls cows = 0
cows for i = 01 to 4
for i = 1 toif 4g[i] = dig[i]
if g[i] bulls += dig[i]1
bulls += 1else
for j = 1 to 4
else
for j = 1 to 4 if dig[j] = g[i]
if dig[j] cows += g[i]1
cows += 1.
.
.
.
print "bulls:" & bulls & " cows:" & cows
.
print "bulls:" &until bulls & " cows:" &= cows4
until bulls = 4
.
print "Well done! " & attempts & " attempts needed."</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Eiffel}}==
Line 2,224 ⟶ 2,436:
</pre>
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
Line 2,230 ⟶ 2,442:
class GameMaster
{
field _numbers;
object theNumbers;
field _attempt;
object theAttempt;
 
constructor()
{
// generate secret number
var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9);
 
theNumbers_numbers := randomNumbers.Subarray(0, 4);
theAttempt_attempt := new Integer(1);
}
 
ask()
{
var row := console.print("Your Guess #",theAttempt_attempt," ?").readLine();
^ row.toArray()
}
 
proceed(guess)
{
int cows := 0;
int bulls := 0;
 
if (guess.Length != 4)
{
bulls := -1
}
else
{
try
{
for (int i := 0,; i < 4,; i+=1) {
var ch := guess[i];
var number := ch.toString().toInt();
// check range
ifnot (number > 0 && number < 10)
{ InvalidArgumentException.raise() };
// check duplicates
var duplicate := guess.seekEach::(x => (x == ch)&&(x.equalReference(ch).Inverted));
if (nil != duplicate)
{
InvalidArgumentException.raise()
};
if (number == theNumbers_numbers[i])
{
bulls += 1
}
else
{
if (theNumbers_numbers.ifExists(number))
{ cows += 1 }
}
}
}
catch(Exception e)}
catch(Exception {e)
bulls := -1{
}bulls := -1
};
};
 
bulls =>
-1 { console.printLine:("Not a valid guess."); ^ true }
4 { console.printLine:("Congratulations! You have won!"); ^ false }
:! {
theAttempt_attempt.append(1);
console.printLine("Your Score is ",bulls," bulls and ",cows," cows");
^ true
}
}
}
 
public program()
{
var gameMaster := new GameMaster();
 
var (process := $lazy: gameMaster.proceed(gameMaster.ask())).doWhile();
 
process.doWhile();
console.readChar()
}</syntaxhighlight>
{{out}}
Line 2,330 ⟶ 2,544:
Congratulations! You have won!
</pre>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
Line 3,118 ⟶ 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}}==
<syntaxhighlight lang="go">package main
Line 3,681 ⟶ 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}}==
<syntaxhighlight lang="julia">function cowsbulls()
Line 3,748 ⟶ 4,174:
please, enter four distincts digits
Your guess? </pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scalakotlin">// version 1.1.2
 
import java.util.Random
 
const val MAX_GUESSES = 20 // say
 
fun main(args: Array<String>) {
val num = ('1'..'9').shuffled().take(4).joinToString("")
val r = Random()
var num: String
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
do {
num = (1234 + r.nextInt(8643)).toString()
} while ('0' in num || num.toSet().size < 4)
 
println("All guesses should have exactly 4 distinct digits excluding zero.")
Line 3,768 ⟶ 4,188:
while (true) {
print("Enter your guess : ")
val guess = readLinereadln().trim()!!
if (guess == num) {
println("You've won with ${++guesses} valid guesses!")
returnbreak
}
val n = guess.toIntOrNull()
Line 3,820 ⟶ 4,240:
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.
Line 5,682 ⟶ 6,103:
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}}
Line 5,839 ⟶ 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,977 ⟶ 6,490:
ser: Say '*** error ***' arg(1); Return
</syntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
Line 6,019 ⟶ 6,533:
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
Line 6,101 ⟶ 6,645:
puts "Bulls: #{bulls}; Cows: #{cows}"
end</syntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
Line 6,481 ⟶ 7,026:
end repeat
end repeat</syntaxhighlight>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program bulls_and_cows;
setrandom(0);
 
print("Bulls and cows");
print("--------------");
print;
 
secret := make_secret();
 
loop do
guess := read_guess();
tries +:= 1;
bulls := count_bulls(guess, secret);
cows := count_cows(guess, secret);
print(bulls, "bulls,", cows, "cows.");
if bulls = 4 then
print("You win! Tries:", tries);
exit;
end if;
end loop;
 
proc make_secret();
digits := [];
loop for i in [1..4] do
loop until not digit in digits do
digit := 1 + random(8);
end loop;
digits with:= digit;
end loop;
return digits;
end proc;
 
proc read_guess();
loop do
putchar("Guess? ");
flush(stdout);
guess := getline(stdin);
if exists d in guess | not d in "123456789" then
print("invalid input:", d);
elseif #guess /= #{d : d in guess} then
print("no duplicates allowed");
elseif #guess /= 4 then
print("need 4 digits");
else
exit;
end if;
end loop;
return [val d : d in guess];
end proc;
 
proc count_bulls(guess, secret);
return #[i : i in [1..4] | guess(i) = secret(i)];
end proc;
 
proc count_cows(guess, secret);
return #[d : d in guess | d in secret] - count_bulls(guess, secret);
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Bulls and cows
--------------
 
Guess? 1234
0 bulls, 1 cows.
Guess? 5678
2 bulls, 1 cows.
Guess? 5978
2 bulls, 0 cows.
Guess? 5968
1 bulls, 1 cows.
Guess? 5976
1 bulls, 1 cows.
Guess? 6978
3 bulls, 0 cows.
Guess? 6971
2 bulls, 0 cows.
Guess? 6918
2 bulls, 0 cows.
Guess? 1978
2 bulls, 0 cows.
Guess? 6178
3 bulls, 0 cows.
Guess? 6278
3 bulls, 0 cows.
Guess? 6378
4 bulls, 0 cows.
You win! Tries: 12</pre>
=={{header|Shale}}==
 
Line 6,651 ⟶ 7,284:
New game
></pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var size = 4
Line 6,850 ⟶ 7,484:
</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>
 
<syntaxhighlight lang="swift">import Foundation
Line 6,925 ⟶ 7,621:
Your score: 0 bulls and 1 cows
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc main {} {
Line 7,013 ⟶ 7,710:
=={{header|Transd}}==
{{trans|C++}}
<syntaxhighlight lang="scheme">#lang transd
#lang transd
 
MainModule: {
Line 7,023 ⟶ 7,719:
),
 
play: (λ locals:
syms "0123456789"
len 4
Line 7,043 ⟶ 7,739:
(with bulls 0 cows 0 pl 0
(for i in Range(len) do
(= pl (findindex-of thenum (subn guess i)))
(if (eq pl i) (+= bulls 1)
elsif (neq pl -1) (+= cows 1))
Line 7,057 ⟶ 7,753:
),
 
_start: (λ locals: s String()
(lout "Welcome to \"Bulls and cows\"!")
(while true
(while true
(textout "Do you want to play? (yes|no) : ")
(textingetline s 3)
(if (not (size s))
(lout "Didn't receive an answer. Exiting.") (exit)
Line 7,071 ⟶ 7,767:
(play)
(lout "Another game?")
)
)
}</syntaxhighlight>
}
 
</syntaxhighlight>
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
Line 7,718 ⟶ 8,414:
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,723 ⟶ 8,496:
{{libheader|Wren-set}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="ecmascriptwren">import "random" for Random
import "./set" for Set
import "./ioutil" for Input
 
var MAX_GUESSES = 20 // say
Line 7,748 ⟶ 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,802 ⟶ 8,577:
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:
44

edits