Bulls and cows/Player: Difference between revisions

m
Fix variable name typo
(Added R.)
m (Fix variable name typo)
 
(28 intermediate revisions by 12 users not shown)
Line 13:
*   [[Guess the number/With Feedback (Player)]]
<br><br>
 
=={{header|Ada}}==
{{works with|Ada 2005}}
 
bulls_player.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
Line 147 ⟶ 146:
Testant : constant Sequence := V.Element (Position);
Bull_Score : Natural := 0;
Cows_ScoreCow_Score : Natural := 0;
begin
for I in Testant'Range loop
Line 227 ⟶ 226:
-- solve the puzzle
Solve;
end Bulls_Player;</langsyntaxhighlight>
 
output:
Line 253 ⟶ 252:
Cows:2
The sequence you thought has to be: 8 3 9 5</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">
# This breaks a unique code of `n' pegs and `m' colours you think of. #
 
INT pegs = 4, colours = 6;
 
MODE LIST = FLEX [1 : 0] COMBINATION,
COMBINATION = [pegs] COLOUR,
COLOUR = INT;
 
OP +:= = (REF LIST u, COMBINATION v) REF LIST:
# Add one combination to a list. #
([UPB u + 1] COMBINATION w; w[ : UPB u] := u; w[UPB w] := v; u := w);
 
PROC gen = (REF COMBINATION part, INT peg) VOID:
# Generate all unique [colours!/(colours-pegs)!] combinations. #
IF peg > pegs
THEN all combs +:= part
ELSE FOR i TO colours
DO IF BOOL unique := TRUE;
FOR j TO peg - 1 WHILE unique
DO unique := part[j] ~= i
OD;
unique
THEN part[peg] := i;
gen (part, peg + 1)
FI
OD
FI;
 
LIST all combs;
gen (LOC COMBINATION, 1);
 
PROC break code = (LIST sieved) VOID:
# Present a trial and sieve the list with the entered score. #
CASE UPB sieved + 1
IN # No elements. # printf ($l"Inconsistent scores"l$),
# One element. # printf (($l"Solution is "4(xd)l$, sieved[1]))
OUT printf (($l4(dx)$, sieved[1]));
# Read the score as a sequence of "c" and "b". #
INT col ok := 0, pos ok := 0, STRING z := "";
WHILE z = ""
DO read ((z, new line))
OD;
FOR i TO UPB z
DO (z[i] = "c" | col ok |: z[i] = "b" | pos ok) +:= 1
OD;
(pos ok = pegs | stop);
# Survivors are combinations with score as entered. #
LIST survivors;
FOR i FROM 2 TO UPB sieved
DO INT col ok i := 0, pos ok i := 0;
FOR u TO pegs
DO FOR v TO pegs
DO IF sieved[1][u] = sieved[i][v]
THEN (u = v | pos ok i | col ok i) +:= 1
FI
OD
OD;
(col ok = col ok i AND pos ok = pos ok i | survivors +:= sieved[i])
OD;
# Solution must be among the survivors. #
break code (survivors)
ESAC;
 
break code (all combs)
</syntaxhighlight>
{{out}}
<pre>
1 2 3 4 cc
2 1 5 6 cc
3 4 6 5 cccc
5 6 4 3 ccbb
Solution is 6 5 4 3
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="ahk">length:=4, i:=0, S:=P(9,length)
 
Gui, Add, Text, w83 vInfo, Think of a %length%-digit number with no duplicate digits.
Line 361 ⟶ 436:
. P(n,k-1,opt,delim,str . A_LoopField . delim)
Return s
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> secret$ = ""
REPEAT
c$ = CHR$(&30 + RND(9))
Line 422 ⟶ 496:
NEXT i%
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 526 ⟶ 599:
 
return 0;
}</langsyntaxhighlight>sample output for 4 digits:<syntaxhighlight lang="text">--------+--------------------
Secret | 5437
--------+--------------------
Line 541 ⟶ 614:
Score | 4 bull, 0 cow
--------+--------------------
</langsyntaxhighlight>sample output for 9 digits<syntaxhighlight lang="text">--------+--------------------
Secret | 758214936
--------+--------------------
Line 576 ⟶ 649:
Guess 11| 758214936 (from: 1)
Score | 9 bull, 0 cow
--------+--------------------</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C#|3.0}}
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 662 ⟶ 734:
}
}
</syntaxhighlight>
</lang>
Example output:-
<pre>
Line 674 ⟶ 746:
Hooray! The answer is 5936!
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <sstream>
Line 796 ⟶ 867:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
Output:
<pre>
Line 816 ⟶ 887:
It is: 6281
</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun random-number ()
(do* ((lst '(1 2 3 4 5 6 7 8 9) (remove d lst))
Line 862 ⟶ 932:
(setq b (bulls number guess))
(setq c (- (bulls+cows number guess) b)))))
</syntaxhighlight>
</lang>
Output:
<pre>
Line 876 ⟶ 946:
NIL
</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight Rubylang="ruby">size = 4
scores = [] of Tuple(Int32, Int32)
guesses = [] of Array(Char)
Line 907 ⟶ 976:
break
end
end</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.algorithm, std.range, std.ascii;
 
Line 929 ⟶ 997:
return "Nothing fits the scores you gave.".writeln;
writeln("Solution found: ", choices[0]);
}</langsyntaxhighlight>
{{out|Example output}}
<pre>My guess is 9345. How many bulls and cows? 02
Line 937 ⟶ 1,005:
My guess is 7931. How many bulls and cows? 40
Solution found: 7931</pre>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">defmodule Bulls_and_cows do
def player(size \\ 4) do
possibility = permute(size) |> Enum.shuffle
Line 984 ⟶ 1,051:
end
 
Bulls_and_cows.player</langsyntaxhighlight>
 
{{out}}
Line 998 ⟶ 1,065:
Solved!
</pre>
 
=={{header|Euphoria}}==
{{trans|C}}
{{works with|Euphoria|4.*}}
<langsyntaxhighlight lang="euphoria">include std/sequence.e
 
constant line = "--------+--------------------\n"
Line 1,085 ⟶ 1,151:
sequence secret = get_digits(n)
printf(1,"%sSecret | %s\n%s", {line, secret, line})
game(secret)</langsyntaxhighlight>
 
Output:
Line 1,106 ⟶ 1,172:
Score | 4 bull, 0 cow
--------+--------------------</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays combinators.short-circuit formatting fry io kernel
math math.combinatorics math.functions math.order math.parser
math.ranges random regexp sequences sets splitting ;
Line 1,134 ⟶ 1,199:
] [ drop "Scoring inconsistency." print ] if* ;
 
possibilities game</langsyntaxhighlight>
{{out}}
<pre>
Line 1,149 ⟶ 1,214:
Success!
</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module Player
implicit none
 
Line 1,260 ⟶ 1,324:
end if
end do
end program</langsyntaxhighlight>
Output
<pre>
Line 1,282 ⟶ 1,346:
 
Solved!</pre>
=={{header|FutureBasic}}==
This player function uses FB's new global MDA (MultiDimensionalArray) to hold the list of possible 4-digit numbers.
<syntaxhighlight lang="future basic">
cgRect wndrect
str15 guess
short count, x, y = 60, stock, state = 1
 
begin enum 3
_bullLabel
_cowLabel
_horzLine
_vertLine
_newGameBtn
_help
_alert = 101
end enum
 
void local fn showGuess
print %(20, y)chr$(guess[2]);
print %(59, y)chr$(guess[3]);
print %(98, y)chr$(guess[4]);
print %(137,y)chr$(guess[5]);
x = 210
end fn
 
void local fn growWindow
CGRect r = fn WindowContentRect( 1 )
r.size.height += 32
r.origin.y -= 32
window 1,,r
end fn
 
void local fn init //Create array of possible 4-digit numbers
uint8 d1,d2,d3,d4
for d1 = 1 to 9
for d2 = 1 to 9
if d2 == d1 then continue
for d3 = 1 to 9
if d3 == d2 || d3 == d1 then continue
for d4 = 1 to 9
if d4 == d1 || d4 == d2 || d4 == d3 then continue
mda_add(0) = @(d1*1000 + d2*100 + d3*10 + d4)
next
next
next
next
end fn
 
void local fn NewGame
window 1,, wndrect
cls
count = mda_count(0)
guess = str$( mda_integer( rnd(count) - 1 ) )
state = 1 : stock = 0 : y = 60
fn growWindow
text @"menlo bold",24,fn ColorControlText
fn showGuess
end fn
 
local fn play( n as byte )
short i, r, s = 0
uint8 bnc
print %(x,y) n;
if state
if n < 4 then stock = 10*n : state-- : x = 270 : exit fn
s = -1
else
stock += n
str15 s2
for i = 0 to count - 1
bnc = 0
s2 = str$( mda_integer(i) )
for r = 2 to 5
n = instr$(1, s2, chr$(guess[r]) )
if n == r then bnc += 10 else if n then bnc++
next
if bnc == stock then mda_swap(s),(i) : s ++
next
end if
select s
case 0 : stop "There is a problem with one of your counts. ¬
Choose CONTINUE to start again."
fn newGame : exit fn
case 1, -1 : y = 20 : text,,fn colorRed
if s == 1 then guess = str$( mda_integer(0) )
case else count = s
guess = str$( mda_integer(rnd(s)-1) )
y += 32 : state ++
end select
fn showGuess
fn growWindow
end fn
 
void local fn BuildWindows
subclass window 1, @"Bulls and cows solver", (0,0,311,114), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
wndrect = fn WindowContentRect( 1 )
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", (15,15,100,32)
ViewSetAutoresizingMask( _newGameBtn, NSViewMaxYMargin )
CGRect r = fn WindowContentRect( 1 )
r.size.width += 120
r.size.height -= 20
r.origin.x -= 60
r.origin.y += 145
window 2, @"How to play",r
text,16
textlabel _help ,@"Choose a number with 4 unique digits, 1-9. ¬
I'll try to guess it.¬
\nAfter each guess, type the number (0-4) of Bulls, then of Cows.¬
\n A Bull (🐂) is a correct digit in the right position.¬
\n A Cow (🐄) is a correct digit in the wrong position.",(20,20,420,70),2
end fn
 
void local fn DoDialog( evt as long, tag as long )
select ( evt )
case _windowKeyDown //: stop
CFStringRef ch = fn EventCharacters
if instr( 0, @"01234", ch ) < 5
DialogEventSetBool(YES) : fn play( intval( ch ) )
end if
//if fn StringIsEqual( ch, @"?" ) then window 2
case _btnClick : fn NewGame : window -2
case _windowWillClose : if tag == 1 then end //else window -2 : DialogEventSetBool(YES)
end select
end fn
 
on dialog fn DoDialog
fn buildWindows
fn init
fn newGame
 
HandleEvents
</syntaxhighlight>
{{out}}
[[File:Bull and Cows Solver in FB.png]]
 
=={{header|Go}}==
Notes: Strategy per the suggestion in the problem description. Check algorithm lifted from Bulls and cows program. Code here uses Go's built in map type as the container for the list of still-possible numbers; only the map key is used, the value is assigned a dummy of 0.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,380 ⟶ 1,585:
}
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Monad
import System.Random (randomRIO)
Line 1,415 ⟶ 1,620:
do putStrLn "Wrong input. Try again"
takeInput
else return ui</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="haskell">*Main> player
My guess is 4923
How many bulls and cows?
Line 1,430 ⟶ 1,635:
How many bulls and cows?
4 0
The answer is 4932</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'general/misc/prompt'
 
poss=:1+~.4{."1 (i.!9)A.i.9
fmt=: ' ' -.~ ":
 
play=:3 :0{{
while.1<#poss=.poss do.
smoutputecho 'guessing ',fmt guess=.({~ ?@#)poss
bc=.+/\ _".prompt 'how many bull and cows? '
poss=.poss #~({.bc)=guess+/@:="1 poss
poss=.poss #~({:+/bc)=guess+/@e."1 poss
end.
if.#poss do.
Line 1,451 ⟶ 1,654:
'no valid possibilities'
end.
}}</syntaxhighlight>
)</lang>
 
For example:
<langsyntaxhighlight lang="j"> play''
guessing 7461
how many bull and cows? 0 1
Line 1,463 ⟶ 1,666:
guessing 1359
how many bull and cows? 3 0
the answer is 1358</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
public class BullsAndCowsPlayerGame {
 
Line 1,547 ⟶ 1,749:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="java">
<lang Java>
public abstract class AbstractGuessNumber {
 
Line 1,588 ⟶ 1,790:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="java">
<lang Java>
public class GameNumber extends AbstractGuessNumber {
 
Line 1,659 ⟶ 1,861:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="java">
<lang Java>
public class AutoGuessNumber extends AbstractGuessNumber {
 
Line 1,691 ⟶ 1,893:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="java">
<lang Java>
public class GuessResult {
 
Line 1,742 ⟶ 1,944:
}
}
</syntaxhighlight>
</lang>
Sample game:
{{out}}
Line 1,777 ⟶ 1,979:
The answer is [0, 5, 3, 6]
</pre>
 
=={{header|Julia}}==
{{works with|Julia version 0.6.0}}
<syntaxhighlight lang="julia">
<lang Julia>
countbulls(a, b) = sum([a[i] == b[i] for i in 1:length(a)])
countcows(a, b) = sum([a[i] == b[j] for i in 1:length(a), j in 1:length(b) if i != j])
Line 1,809 ⟶ 2,010:
answ = doguess()
println("The winning pick: $(answ[1])$(answ[2])$(answ[3])$(answ[4])")
</syntaxhighlight>
</lang>
Example game:
<syntaxhighlight lang="julia">
<lang Julia>
My guess: 9517. How many bulls and cows?
0 1
Line 1,827 ⟶ 2,028:
4 0
The winning pick: 3124
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.util.Random
Line 1,881 ⟶ 2,081:
println("Something went wrong as no choices left! Aborting program")
}
}</langsyntaxhighlight>
Sample game:
{{out}}
Line 1,896 ⟶ 2,096:
You've just found the answer!
</pre>
 
=={{header|Liberty BASIC}}==
As supplied rhe code shows the remaining pool of numbers after each guess is scored.
<syntaxhighlight lang="lb">
<lang lb>
guesses =0
 
Line 1,999 ⟶ 2,198:
if instr( i$, "0") then check =1
end function
</syntaxhighlight>
</lang>
=={{header|Lua}}==
{{Trans|Phix}}
<syntaxhighlight lang="lua">local line = "---------+----------------------------------+-------+-------+"
local digits = {1,2,3,4,5,6,7,8,9}
 
function and_bits (a, b)
=={{header|Mathematica}}==
-- print (a, b)
<lang Mathematica>
return a & b -- Lua 5.3
bullCow={Count[#1-#2,0],Length[#1\[Intersection]#2]-Count[#1-#2,0]}&;
end
 
function or_bits (a, b)
return a | b -- Lua 5.3
end
 
 
function get_digits (n)
local tDigits = {}
for i = 1, #digits do tDigits[i] = digits[i] end
local ret = {}
math.randomseed(os.time())
for i = 1, n do
local d = table.remove (tDigits, math.random(#tDigits))
table.insert (ret, d)
end
return ret
end
 
function mask (x)
return 3*x-1 -- any function
end
 
function score (guess, goal)
local bits, bulls, cows = 0, 0, 0
for i = 1, #guess do
if (guess[i] == goal[i]) then
bulls = bulls + 1
else
bits = bits + mask (goal[i])
end
end
for i = 1, #guess do
if not (guess[i] == goal[i]) then
local nCow = (and_bits (bits, mask(guess[i])) == 0) and 0 or 1
cows = cows + nCow
end
end
return bulls, cows
end
 
function iCopy (list)
local nList = {}
for i = 1, #list do nList[i] = list[i] end
return nList
end
 
function pick (list, n, got, marker, buf)
-- print ('pick', #list, n)
local bits = 1
if got >= n then
table.insert (list, buf)
else
local bits = 1
for i = 1, #digits do
if and_bits(marker,bits) == 0 then
buf[got+1] = i
pick (list, n, got+1, or_bits (marker, bits), iCopy(buf))
end
bits = bits * 2
end
end
end
 
function filter_list (list, guess, bulls, cows)
local index = 1
for i = 1, #list do
-- print ('filter_list i: ' .. i)
local scoreBulls, scoreCows = score (guess, list[i])
if bulls == scoreBulls and cows == scoreCows then
list[index] = list[i]
index = index + 1
end
end
for i = #list, index+1, -1 do
table.remove (list, i)
end
end
 
function game (goal)
local n = #goal
local attempt = 1
local guess = {} -- n-length guess numbers array
for i = 1, n do table.insert (guess, 0) end -- empty buffer
local list = {}
pick (list, n, 0, 0, guess)
local bulls, cows = 0, 0
while true do
guess = list[1]
bulls, cows = score (guess, goal)
print (' Guess ' .. attempt .. ' | ' ..table.concat(guess), '('..#list..' variants) ', bulls, cows)
if bulls == n then return end
filter_list (list, guess, bulls, cows)
attempt = attempt + 1
end
end
 
local n = 4
local secret = get_digits (n)
print (line..'\nSecret '.. #secret.. ' | '..table.concat(secret) .. ' | Bulls | Cows |' .. '\n' .. line)
 
game (secret)</syntaxhighlight>
 
{{out}}
N=4:
<pre>---------+----------------------------------+-------+-------+
Secret 4 | 9562 | Bulls | Cows |
---------+----------------------------------+-------+-------+
Guess 1 | 1234 (3024 variants) 0 4
Guess 2 | 2159 (469 variants) 0 4
Guess 3 | 3428 (281 variants) 0 4
Guess 4 | 4382 (153 variants) 1 3
Guess 5 | 5367 (31 variants) 1 3
Guess 6 | 6371 (11 variants) 0 4
Guess 7 | 9562 (2 variants) 4 0</pre>
 
N=6:
<pre>---------+----------------------------------+-------+-------+
Secret 6 | 397124 | Bulls | Cows |
---------+----------------------------------+-------+-------+
Guess 1 | 123456 (60480 variants) 0 3
Guess 2 | 214368 (8382 variants) 0 2
Guess 3 | 341279 (705 variants) 1 0
Guess 4 | 352187 (74 variants) 2 4
Guess 5 | 362591 (21 variants) 1 0
Guess 6 | 376145 (9 variants) 2 4
Guess 7 | 397124 (2 variants) 6 0</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">bullCow={Count[#1-#2,0],Length[#1\[Intersection]#2]-Count[#1-#2,0]}&;
Module[{r,input,candidates=Permutations[Range[9],{4}]},
While[True,
Line 2,016 ⟶ 2,351:
Print[ToString@Length@candidates<>" candidates remaining."];
Print["Can try "<>StringJoin[ToString/@First@candidates]<>"."];
]]]]</syntaxhighlight>
</lang>
Output:
<pre>120 candidates remaining.
<pre>
120 candidates remaining.
Can try 1256.
36 candidates remaining.
Line 2,026 ⟶ 2,359:
5 candidates remaining.
Can try 1584.
Must be: 1639</pre>
</pre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function BullsAndCowsPlayer
% Plays the game Bulls and Cows as the player
Line 2,087 ⟶ 2,418:
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end</langsyntaxhighlight>
{{out}}
Secret number: 5612
Line 2,138 ⟶ 2,469:
How many cows? 0
That's bull! You messed up your scoring.</pre>
 
=={{header|Nim}}==
If there is an impossibility, the program asks the user for the number to guess and indicates where are the errors in scoring.
<langsyntaxhighlight Nimlang="nim">import parseutils
import random
import sequtils
Line 2,273 ⟶ 2,603:
history.findError()
break
choices.shallowCopy = move(remaining)</langsyntaxhighlight>
 
{{out}}
Line 2,316 ⟶ 2,646:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
{{works with|Perl 5.10.0 and above}}
 
<lang perl>#!/usr/bin/perl
use warnings;
use strict;
Line 2,333 ⟶ 2,661:
# $+{BULLS} and $+{COWS}.
 
sub read_score :prototype($) {
(my $guess) = @_;
 
Line 2,347 ⟶ 2,675:
}
 
sub score_correct :prototype($$$$) {
my ($a, $b, $bulls, $cows) = @_;
 
Line 2,371 ⟶ 2,699:
"Your secret number is @candidates":
"I think you made a mistake with your scoring");
</syntaxhighlight>
</lang>
 
Sample game:
<langsyntaxhighlight lang="perl">msl@64Lucid:~/perl$ ./bulls-and-cows
My guess: 1869 (from 3024 possibilities)
1 0
Line 2,384 ⟶ 2,712:
0 3
Your secret number is 1357
msl@64Lucid:~/perl$</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant line = " +---------+-----------------------------+-------+------+\n"
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant digits = "123456789"
<span style="color: #008080;">constant</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">" +---------+-----------------------------+-------+------+\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">digits</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"123456789"</span>
function mask(integer ch)
return power(2,ch-'1')
<span style="color: #008080;">function</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function score(sequence guess, sequence goal)
integer bits = 0, bulls = 0, cows = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">score</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">goal</span><span style="color: #0000FF;">)</span>
for i=1 to length(guess) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bulls</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if guess[i]=goal[i] then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
bulls += 1
<span style="color: #008080;">if</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">goal</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">bulls</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
bits += mask(goal[i])
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">bits</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #000000;">goal</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for i=1 to length(guess) do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
cows += (and_bits(bits,mask(guess[i]))!=0)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">cows</span> <span style="color: #0000FF;">+=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mask</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
return {bulls, cows}
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">}</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence list = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
procedure pick(integer n, integer got, integer marker, sequence buf)
integer bits = 1
<span style="color: #008080;">procedure</span> <span style="color: #000000;">pick</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">got</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">marker</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">buf</span><span style="color: #0000FF;">)</span>
if got>=n then
<span style="color: #008080;">if</span> <span style="color: #000000;">got</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span>
list = append(list,buf)
<span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">,</span><span style="color: #000000;">buf</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">else</span>
for i=0 to length(digits)-1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if not and_bits(marker,bits) then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
buf[got+1] = i+'1'
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">marker</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
pick(n, got+1, or_bits(marker,bits), buf)
<span style="color: #000000;">buf</span><span style="color: #0000FF;">[</span><span style="color: #000000;">got</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'1'</span>
end if
<span style="color: #000000;">pick</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">got</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">marker</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">),</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buf</span><span style="color: #0000FF;">))</span>
bits *= 2
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #000000;">bits</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure filter_list(sequence guess, integer bulls, integer cows)
integer l = length(list), idx = 0
<span style="color: #008080;">procedure</span> <span style="color: #000000;">filter_list</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">)</span>
sequence bc = {bulls,cows}
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to l do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">bc</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cows</span><span style="color: #0000FF;">}</span>
if score(guess,list[i])=bc then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
idx += 1
<span style="color: #008080;">if</span> <span style="color: #000000;">score</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])=</span><span style="color: #000000;">bc</span> <span style="color: #008080;">then</span>
list[idx] = list[i]
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
list = list[1..idx]
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure game(sequence tgt)
integer n = length(tgt), attempt = 1, bulls = 0, cows
<span style="color: #008080;">procedure</span> <span style="color: #000000;">game</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">tgt</span><span style="color: #0000FF;">)</span>
sequence guess
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tgt</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">attempt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
pick(n,0,0,repeat(0,n))
<span style="color: #000000;">pick</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'\0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span>
while bulls<n do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
guess = list[rand(length(list))]
<span style="color: #004080;">string</span> <span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">))]</span>
{bulls, cows} = score(guess,tgt)
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">score</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tgt</span><span style="color: #0000FF;">)</span>
printf(1," | Guess %-2d| %9s %-14s | %d | %d |\n",
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" | Guess %-2d| %9s %-14s | %d | %d |\n"</span><span style="color: #0000FF;">,</span>
{attempt, guess, sprintf("(from %d)",length(list)), bulls, cows})
<span style="color: #0000FF;">{</span><span style="color: #000000;">attempt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"(from %d)"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">)),</span> <span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">})</span>
filter_list(guess, bulls, cows)
<span style="color: #008080;">if</span> <span style="color: #000000;">bulls</span><span style="color: #0000FF;">=</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
attempt += 1
<span style="color: #000000;">filter_list</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bulls</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cows</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #000000;">attempt</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
puts(1,line)
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end procedure
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
constant N = 4
sequence secret = shuffle(digits)[1..N]
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
printf(1,"%s | Secret | %9s | BULLS | COWS |\n%s", {line, secret, line})
<span style="color: #004080;">string</span> <span style="color: #000000;">secret</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">N</span><span style="color: #0000FF;">]</span>
game(secret)</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s | Secret | %9s | BULLS | COWS |\n%s"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">line</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">secret</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">line</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">game</span><span style="color: #0000FF;">(</span><span style="color: #000000;">secret</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
N=4:
Line 2,514 ⟶ 2,845:
+---------+-----------------------------+-------+------+
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de bullsAndCows ()
Line 2,534 ⟶ 2,864:
Choices ) )
(NIL Choices "No matching solution")
(NIL (cdr Choices) (pack "The answer is " (car Choices))) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (bullsAndCows)
Line 2,548 ⟶ 2,878:
How many bulls and cows? 0 2
-> "The answer is 2468"</pre>
 
=={{header|Prolog}}==
Works with SWI-Prolog. Use of library clfd written by '''Markus Triska'''.<br>
There is no algorithm. We explain to Prolog the constraints on the numbers according to the previous guesses and we let Prolog decides of the next guess.<br>
The IA :
<langsyntaxhighlight Prologlang="prolog">:- module('ia.pl', [tirage/1]).
:- use_module(library(clpfd)).
 
Line 2,685 ⟶ 3,014:
H #\= H1,
compte_bien_placees(T, T1, MPC, MPF).
</syntaxhighlight>
</lang>
The code to play :
<langsyntaxhighlight Prologlang="prolog">bulls_and_cows :-
retractall('ia.pl':guess(_,_)),
retractall(coups(_)),
Line 2,708 ⟶ 3,037:
add_1(X, Y) :-
Y is X + 1.
</syntaxhighlight>
</lang>
A game :
<pre> ?- bulls_and_cows.
Line 2,733 ⟶ 3,062:
true .
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#answerSize = 4
Structure history
answer.s
Line 2,840 ⟶ 3,168:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Playing Bulls & Cows with 4 unique digits.
Line 2,854 ⟶ 3,182:
 
Press ENTER to exit</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import permutations
from random import shuffle
 
Line 2,910 ⟶ 3,237:
'\n '.join("%s -> %s" % (''.join(an),sc)
for an,sc in izip(answers, scores)))
break</langsyntaxhighlight>
 
'''Sample output'''
Line 2,934 ⟶ 3,261:
=={{header|R}}==
As we are picking our guesses randomly from the remaining valid guesses, it is likely that this solution is neither optimal, efficient, or particularly smart. However, it is much shorter than some of the other solutions, is reasonably idiomatic R, and does not break in any way that I know of. I am aware that there exists an optimal method of playing this game, but I neither know the algorithm nor was required by the task to implement it. For comparison, it would be interesting to see the optimal method submitted here as an alternative solution.
<langsyntaxhighlight rlang="rsplus">bullsAndCowsPlayer <- function()
{
guesses <- 1234:9876
#The next line is terrible code, but it's the most R way to convert a set of 4-digit numbers to their 4 digits.
guessDigits <- t(sapply(strsplit(as.character(guesses), ""), as.integer))
validGuesses <- guessDigits[apply(guessDigits, 1, function(x) length(unique(x)) == 4 && all(x != 0)), ]
repeat
{
remainingCasesCount <-length nrow(validGuesses[,1])
cat("Possibilities remaining:", remainingCasesCount)#Not required, but excellent when debugging.
guess <- validGuesses[sample(remainingCasesCount, 1), ]
guessAsOneNumber <- as.integer(paste(guess, collapse = ""))
bulls <- as.integer(readline(paste0("My guess is ", guessAsOneNumber, ". Bull score? [0-4] ")))
if(bulls == 4){ return(paste0("Your number is ", guessAsOneNumber, ". I win!"))}
cows <- as.integer(readline("Cow score? [0-4] "))
pseudoBulls<-function(x){sum(x==guess)}
#If our guess scores y bulls, then only numbers containing exactly y digits with the same value and position (y "pseudoBulls") as in our guess can be correct.
#Accounting for the positions of cows not being fixed, the same argument also applies for them.
#The nextfollowing linelines makesmake us only keep the numbers that have the right pseudoBulls and "pseudoCows" scores, albeit without the need for a pseudoCows function.
#We also use pseudoBulls != 4 to remove our most recent guess, because we know that it cannot be correct.
#Finally, the drop=FALSE flag is needed to stop R converting validGuesses to a vector when there is only one guess left.
pseudoBulls <- function(x) sum(x == guess)
validGuesses<-validGuesses[apply(validGuesses,1,function(x) pseudoBulls(x)==bulls&&sum(x %in% guess)-pseudoBulls(x)==cows&&pseudoBulls(x)!=4),,drop=FALSE]
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4
if(length(validGuesses)==0){return("Error: Scoring problem?")}
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE]
if(nrow(validGuesses) == 0) return("Error: Scoring problem?")
}
}
bullsAndCowsPlayer()</langsyntaxhighlight>
{{out}}
<pre>> bullsAndCowsPlayer()
Line 2,973 ⟶ 3,301:
=={{header|Racket}}==
Generate the list of possible choices. Each choice is represented as list of 4 numbers.
<langsyntaxhighlight Racketlang="racket">#lang racket/base
(require racket/string
racket/list)
Line 2,993 ⟶ 3,321:
 
(define (listnum->string list)
(apply string-append (map number->string list)))</langsyntaxhighlight>
 
Now define some auxiliary functions to parse the user input (with a minimum error checking) and calculate the score of another possible guess.
<langsyntaxhighlight Racketlang="racket"> (define (parse-score score)
(if (string? score)
(let ([splited-score (string-split score ",")])
Line 3,008 ⟶ 3,336:
(let ([bulls (count = guess chosen)]
[cows+bulls (count in-chosen guess)])
(values bulls (- cows+bulls bulls))))</langsyntaxhighlight>
 
Main part of the game.
<langsyntaxhighlight Racketlang="racket">(printf "Playing Bulls & Cows with ~a unique digits\n" size)
(let loop ([choices all-choices] [num 1])
Line 3,033 ⟶ 3,361:
(begin
(printf "Sorry, I didn't understand that. Please try again.\n")
(loop choices num)))))))</langsyntaxhighlight>
 
'''Sample Output:'''
Line 3,056 ⟶ 3,384:
Bulls: 1, Cows: 0
Bad scoring! nothing fits those scores you gave.</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 3,062 ⟶ 3,389:
{{trans|Perl}}
 
<syntaxhighlight lang="raku" perl6line># we use the [] reduction meta operator along with the Cartesian Product
# operator X to create the Cartesian Product of four times [1..9] and then get
# all the elements where the number of unique digits is four.
Line 3,100 ⟶ 3,427:
say @candidates
?? "Your secret number is {@candidates[0].join}!"
!! "I think you made a mistake with your scoring.";</langsyntaxhighlight>
{{out}}
<pre>My guess: 4235.
Line 3,109 ⟶ 3,436:
2 1
Your secret number is 1234!</pre>
 
=={{header|Red}}==
ups - this is actually a solver, no input of intermediate results required...
<langsyntaxhighlight lang="red">Red []
 
digits: charset [#"1" - #"9"] ;; bitset for parse rule in valid function
Line 3,144 ⟶ 3,470:
print [CR "Found *" last k: keys-of results "* in " length? k " attempts" CR] ;; cr - constant for newline / carriage return
] ;; forever loop
</syntaxhighlight>
</lang>
'''Sample output'''
<pre>
Line 3,170 ⟶ 3,496:
(halted)
</pre>
 
=={{header|REXX}}==
About a third of the REXX program deals with presentation and/or validation of answers.
<langsyntaxhighlight lang="rexx">/*REXX program plays the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
parse arg ? .; if datatype(?,'W') then call random ,,? /*Random seed? Make repeatable*/
L=1234; H=9876; call gen@ /*generate all possibilities. */
Line 3,224 ⟶ 3,549:
if !\=='' then do; call serr; iterate; end /*prompt the user and try again. */
bull=bull/1; cow=cow/1; return /*normalize bulls & cows numbers.*/
end /*forever*/</langsyntaxhighlight><br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Bulls and cows/Player
 
Line 3,300 ⟶ 3,624:
see "giving " + bulls + " bull(s) and " + cows + " cow(s)." + nl
return [bulls, cows]
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Ruby Version 1.9+
<langsyntaxhighlight lang="ruby">size = 4
scores = []
guesses = []
Line 3,331 ⟶ 3,654:
break
end
end</langsyntaxhighlight>
'''Regular output'''
<pre>
Line 3,351 ⟶ 3,674:
6419 => bulls 1 cows 0
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
Line 3,388 ⟶ 3,710:
play(allCombinations)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,405 ⟶ 3,727:
Ye-haw!
</pre>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">set the remoteWorkInterval to .001 -- optional
repeat forever
repeat forever
Line 3,527 ⟶ 3,848:
end if
end repeat
end repeat</langsyntaxhighlight>
=={{header|Shale}}==
 
<syntaxhighlight lang="shale">#!/usr/local/bin/shale
 
maths library
file library
string library
 
lista var
listb var
firstTimeThrough var
guess var
guess0 var
guess1 var
guess2 var
guess3 var
bulls var
cows var
 
init dup var {
count a:: var
count b:: var
} =
 
randomDigit dup var {
random maths::() 18 >> 9 % 1 +
} =
 
makeGuess dup var {
firstTimeThrough {
guess0 randomDigit() =
guess1 randomDigit() =
{ guess1 guess0 == } { guess1 randomDigit() = } while
guess2 randomDigit() =
{ guess2 guess0 == guess2 guess1 == or } { guess2 randomDigit() = } while
guess3 randomDigit() =
{ guess3 guess0 == guess3 guess1 == guess3 guess2 == or or } { guess3 randomDigit() = } while
guess guess3 1000 * guess2 100 * guess1 10 * guess0 + + + =
} {
i var
 
i random maths::() count lista->:: % =
guess i.value lista->:: value =
guess0 guess 10 % =
guess1 guess 10 / 10 % =
guess2 guess 100 / 10 % =
guess3 guess 1000 / =
} if
} =
 
getAnswer dup var {
stdin file:: fgets file::() {
atoi string::()
} {
0 exit
} if
} =
 
getScore dup var {
haveBulls dup var false =
haveCows dup var false =
ans var
 
{ haveBulls not } {
"Bulls: " print
ans getAnswer() =
ans 0 < ans 4 > and {
"Please try again" println
} {
bulls ans =
haveBulls true =
} if
} while
 
{ haveCows not } {
"Cows: " print
ans getAnswer() =
ans 0 < ans 4 > and {
"Please try again" println
} {
cows ans =
haveCows true =
} if
} while
} =
 
check dup var {
d0 dup var swap = // units
d1 dup var swap =
d2 dup var swap =
d3 dup var swap = // thousands
b dup var 0 =
c dup var 0 =
 
d0 guess0 == { b++ } { d0 guess1 == { d0 guess2 == { d0 guess3 == } or } or { c++ } ifthen } if
d1 guess1 == { b++ } { d1 guess0 == { d1 guess2 == { d1 guess3 == } or } or { c++ } ifthen } if
d2 guess2 == { b++ } { d2 guess0 == { d2 guess1 == { d2 guess3 == } or } or { c++ } ifthen } if
d3 guess3 == { b++ } { d3 guess0 == { d3 guess1 == { d3 guess2 == } or } or { c++ } ifthen } if
 
b bulls >= c cows >= and
} =
 
add dup var {
n dup var swap =
 
n guess != { // never put our own guess back in the list.
i var
 
i count listb->:: =
i.value listb->:: defined not {
i.value listb->:: var
} ifthen
 
i.value listb->:: n =
count listb->::++
} ifthen
} =
 
filterList dup var {
firstTimeThrough {
a var
b var
c var
d var
 
a 1 =
{ a 10 < } {
b 1 =
{ b 10 < } {
b a != {
c 1 =
{ c 10 < } {
c a != c b != and {
d 1 =
{ d 10 < } {
d a != { d b != d c != and } and {
a b c d check() {
a 1000 * b 100 * c 10 * d + + + add()
} ifthen
} ifthen
d++
} while
} ifthen
c++
} while
} ifthen
b++
} while
a++
} while
} {
i var
j var
n var
 
count listb->:: 0 =
i 0 =
{ i count lista->:: < } {
n i.value lista->:: =
n 1000 / n 100 / 10 % n 10 / 10 % n 10 % check() {
n.value add()
} ifthen
i++
} while
} if
} =
 
solve dup var {
t var
f var
n var
 
lista a &=
listb b &=
firstTimeThrough true =
count a:: 0 =
count b:: 0 =
 
n 1 =
f 1 =
{ f } {
makeGuess()
guess0 guess1 guess2 guess3 n "\nGuess %d: %d %d %d %d\n" printf
getScore()
bulls 4 == {
"WooHoo, I won!" println
break
} ifthen
filterList()
f count listb->:: =
 
t lista =
lista listb =
listb t =
firstTimeThrough false =
n++
} while
 
count lista->:: 0 == {
"I've run out of numbers to choose from." println
} ifthen
} =
 
init()
{ true } {
solve()
} while</syntaxhighlight>
 
{{out}}
 
<pre>Guess 1: 9 2 8 1
Bulls: 1
Cows: 1
 
Guess 2: 3 9 8 2
Bulls: 0
Cows: 2
 
Guess 3: 8 4 3 1
Bulls: 1
Cows: 2
 
Guess 4: 4 3 9 1
Bulls: 0
Cows: 3
 
Guess 5: 1 2 3 4
Bulls: 4
Cows: 0
 
WooHoo, I won!</pre>
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Build a list of all possible solutions. The regular expression weeds
# out numbers containing zeroes or repeated digits.
var candidates = (1234..9876 -> grep {|n| !("#{n}" =~ /0 | (\d) .*? \1 /x) }.map{.digits});
Line 3,574 ⟶ 4,125:
candidates.len == 1 ? ("Your secret number is: %d" % candidates[0].join)
: ("I think you made a mistake with your scoring")
)->say</langsyntaxhighlight>
 
'''Output:'''
Line 3,588 ⟶ 4,139:
Your secret number is: 9571
</pre>
 
=={{header|Tcl}}==
{{trans|Python}}
{{tcllib|struct::list}}
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require struct::list
package require struct::set
 
Line 3,644 ⟶ 4,194:
break
}
}</langsyntaxhighlight>
'''Sample Output'''
<pre>
Line 3,667 ⟶ 4,217:
3241 -> (1, 0)
</pre>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Line 3,776 ⟶ 4,325:
Next
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>TOSS : 9 2 4 7
Line 3,804 ⟶ 4,353:
---------- THE END ------------
TOSS WAS : 9 2 4 7 We found : 9 2 4 7 </pre>
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">import "random" for Random
 
var countBullsAndCows = Fn.new { |guess, answer|
var bulls = 0
var cows = 0
var i = 0
for (d in guess) {
if (answer[i] == d) {
bulls = bulls + 1
} else if (answer.contains(d)) {
cows = cows + 1
}
i = i + 1
}
return [bulls, cows]
}
 
var r = Random.new()
var choices = []
// generate all possible distinct 4 digit (1 to 9) integer arrays
for (i in 1..9) {
for (j in 1..9) {
if (j != i) {
for (k in 1..9) {
if (k != i && k != j) {
for (l in 1..9) {
if (l != i && l != j && l != k) {
choices.add([i, j, k, l])
}
}
}
}
}
}
}
 
// pick one at random as the answer
var answer = choices[r.int(choices.count)]
 
// keep guessing, pruning the list as we go based on the score, until answer found
while (true) {
var guess = choices[r.int(choices.count)]
var bc = countBullsAndCows.call(guess, answer)
System.print("Guess = %(guess.join("")) Bulls = %(bc[0]) Cows = %(bc[1])")
if (bc[0] == 4) {
System.print("You've just found the answer!")
return
}
for (i in choices.count - 1..0) {
var bc2 = countBullsAndCows.call(choices[i], answer)
// if score is no better remove it from the list of choices
if (bc2[0] <= bc[0] && bc2[1] <= bc[1]) choices.removeAt(i)
}
if (choices.count == 0) {
System.print("Something went wrong as no choices left! Aborting program")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Guess = 3875 Bulls = 1 Cows = 1
Guess = 3867 Bulls = 0 Cows = 2
Guess = 7461 Bulls = 0 Cows = 3
Guess = 5794 Bulls = 1 Cows = 2
Guess = 6895 Bulls = 2 Cows = 0
Guess = 6945 Bulls = 3 Cows = 0
Guess = 6475 Bulls = 2 Cows = 2
Guess = 4657 Bulls = 0 Cows = 4
Guess = 4675 Bulls = 1 Cows = 3
Guess = 6745 Bulls = 4 Cows = 0
You've just found the answer!
</pre>
 
=={{header|Yabasic}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="yabasic">
<lang Yabasic>
clear screen
 
Line 3,912 ⟶ 4,535:
n = token(l$, c$(), d$)
return c$(i)
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">d9:="123456789";
choices:=Walker.cproduct(d9,d9,d9,d9).pump(List,// lazy,-->3024, order is important
fcn(list){ s:=list.concat(); (s.unique().len()==4) and s or Void.Skip });
Line 3,930 ⟶ 4,552:
 
if(not choices) "Nothing fits the scores you gave.".println();
else "Solution found: ".println(choices[0]);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,940 ⟶ 4,562:
Solution found: 1234
</pre>
 
{{omit from|GUISS}}
2

edits