Bulls and cows/Player: Difference between revisions
m
Fix variable name typo
Thundergnat (talk | contribs) (Rename Perl 6 -> Raku, alphabetize, minor clean-up) |
m (Fix variable name typo) |
||
(31 intermediate revisions by 13 users not shown) | |||
Line 13:
* [[Guess the number/With Feedback (Player)]]
<br><br>
=={{header|Ada}}==
{{works with|Ada 2005}}
bulls_player.adb:
<
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
Line 147 ⟶ 146:
Testant : constant Sequence := V.Element (Position);
Bull_Score : Natural := 0;
begin
for I in Testant'Range loop
Line 227 ⟶ 226:
-- solve the puzzle
Solve;
end Bulls_Player;</
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}}==
<
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
}</
=={{header|BBC BASIC}}==
<
REPEAT
c$ = CHR$(&30 + RND(9))
Line 422 ⟶ 496:
NEXT i%
ENDPROC
</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 526 ⟶ 599:
return 0;
}</
Secret | 5437
--------+--------------------
Line 541 ⟶ 614:
Score | 4 bull, 0 cow
--------+--------------------
</
Secret | 758214936
--------+--------------------
Line 576 ⟶ 649:
Guess 11| 758214936 (from: 1)
Score | 9 bull, 0 cow
--------+--------------------</
=={{header|C sharp|C#}}==
{{works with|C#|3.0}}
<
using System;
using System.Collections.Generic;
Line 662 ⟶ 734:
}
}
</syntaxhighlight>
Example output:-
<pre>
Line 674 ⟶ 746:
Hooray! The answer is 5936!
</pre>
=={{header|C++}}==
<
#include <iostream>
#include <sstream>
Line 796 ⟶ 867:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
Output:
<pre>
Line 816 ⟶ 887:
It is: 6281
</pre>
=={{header|Common 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>
Output:
<pre>
Line 876 ⟶ 946:
NIL
</pre>
=={{header|Crystal}}==
{{trans|Ruby}}
<
scores = [] of Tuple(Int32, Int32)
guesses = [] of Array(Char)
Line 907 ⟶ 976:
break
end
end</
=={{header|D}}==
<
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]);
}</
{{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}}
<
def player(size \\ 4) do
possibility = permute(size) |> Enum.shuffle
Line 984 ⟶ 1,051:
end
Bulls_and_cows.player</
{{out}}
Line 998 ⟶ 1,065:
Solved!
</pre>
=={{header|Euphoria}}==
{{trans|C}}
{{works with|Euphoria|4.*}}
<
constant line = "--------+--------------------\n"
Line 1,085 ⟶ 1,151:
sequence secret = get_digits(n)
printf(1,"%sSecret | %s\n%s", {line, secret, line})
game(secret)</
Output:
Line 1,106 ⟶ 1,172:
Score | 4 bull, 0 cow
--------+--------------------</pre>
=={{header|Factor}}==
<
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</
{{out}}
<pre>
Line 1,149 ⟶ 1,214:
Success!
</pre>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,260 ⟶ 1,324:
end if
end do
end program</
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.
<
import (
Line 1,380 ⟶ 1,585:
}
}
}</
=={{header|Haskell}}==
<
import Control.Monad
import System.Random (randomRIO)
Line 1,415 ⟶ 1,620:
do putStrLn "Wrong input. Try again"
takeInput
else return ui</
Example:
<
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</
=={{header|J}}==
<
poss=:1+~.4{."1 (i.!9)A.i.9
fmt=: ' ' -.~ ":
play=:
while.1<#poss=.poss do.
bc=.
poss=.poss #~({.bc)=guess+/@:="1 poss
poss=.poss #~(
end.
if.#poss do.
Line 1,451 ⟶ 1,654:
'no valid possibilities'
end.
}}</syntaxhighlight>
For example:
<
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</
=={{header|Java}}==
<syntaxhighlight lang="java">
public class BullsAndCowsPlayerGame {
Line 1,547 ⟶ 1,749:
}
}
</syntaxhighlight>
<syntaxhighlight lang="java">
public abstract class AbstractGuessNumber {
Line 1,588 ⟶ 1,790:
}
}
</syntaxhighlight>
<syntaxhighlight lang="java">
public class GameNumber extends AbstractGuessNumber {
Line 1,659 ⟶ 1,861:
}
}
</syntaxhighlight>
<syntaxhighlight lang="java">
public class AutoGuessNumber extends AbstractGuessNumber {
Line 1,691 ⟶ 1,893:
}
}
</syntaxhighlight>
<syntaxhighlight lang="java">
public class GuessResult {
Line 1,742 ⟶ 1,944:
}
}
</syntaxhighlight>
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">
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>
Example game:
<syntaxhighlight lang="julia">
My guess: 9517. How many bulls and cows?
0 1
Line 1,827 ⟶ 2,028:
4 0
The winning pick: 3124
</syntaxhighlight>
=={{header|Kotlin}}==
<
import java.util.Random
Line 1,881 ⟶ 2,081:
println("Something went wrong as no choices left! Aborting program")
}
}</
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">
guesses =0
Line 1,999 ⟶ 2,198:
if instr( i$, "0") then check =1
end function
</syntaxhighlight>
=={{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)
-- print (a, b)
return a & b -- Lua 5.3
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>
Output:
<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>
=={{header|MATLAB}}==
<
% 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</
{{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.
<syntaxhighlight lang="nim">import parseutils
import random
import sequtils
import strformat
import strutils
const
Digits = "123456789"
DigitSet = {Digits[0]..Digits[^1]}
Size = 4
InvalidScore = -1
type
Digit = range['1'..'9']
Score = tuple[bulls, cows: int]
HistItem = tuple[guess: string, bulls, cows: int]
#---------------------------------------------------------------------------------------------------
proc buildChoices(digits: set[Digit]; size: Natural): seq[string] =
## Build the list of choices when starting the game.
if size == 0:
return @[""]
for d in digits:
for s in buildChoices(digits - {d}, size - 1):
result.add(d & s)
#---------------------------------------------------------------------------------------------------
proc getValues(): Score =
## Read the number of bulls and cows provided by the user.
let input = stdin.readLine().strip()
let fields = input.splitWhitespace()
if fields.len != 2 or
fields[0].parseInt(result.bulls, 0) == 0 or result.bulls notin 0..Size or
fields[1].parseInt(result.cows, 0) == 0 or result.cows notin 0..Size:
echo &"Wrong input; expected two number between 0 and {Size}"
return (InvalidScore, InvalidScore)
if result.bulls + result.cows > Size:
echo &"Total number of bulls and cows exceeds {Size}"
return (InvalidScore, InvalidScore)
#---------------------------------------------------------------------------------------------------
func score(value, guess: string): Score =
## Return the score of "guess" against "value".
for idx, digit in guess:
if digit == value[idx]:
inc result.bulls
elif digit in value:
inc result.cows
#---------------------------------------------------------------------------------------------------
proc findError(history: seq[HistItem]) =
## Find the scoring error.
var value: string
## Get the number to find.
while true:
stdout.write("What was the number to find? ")
value = stdin.readLine().strip()
if value.len == Size and allCharsInSet(value, DigitSet) and value.deduplicate.len == Size:
break
# Find inconsistencies.
for (guess, userbulls, usercows) in history:
let (bulls, cows) = score(guess, value)
if userbulls != bulls or usercows != cows:
echo &"For guess {guess}, score was wrong:"
echo &" Expected {bulls} / {cows}, got {userBulls} / {userCows}."
#---------------------------------------------------------------------------------------------------
func suffix(n: Positive): string =
## Return the suffix for an ordinal.
case n
of 1: "st"
of 2: "nd"
of 3: "rd"
else: "th"
#---------------------------------------------------------------------------------------------------
var history: seq[HistItem]
randomize()
var choices = buildChoices(DigitSet, Size)
choices.shuffle()
echo "Choose a number with four unique digits between 1 and 9."
echo "Give the number of bulls and cows separated by one or more spaces."
var guesses = 0
var remaining: seq[string]
while true:
inc guesses
var userbulls, usercows: int
let guess = choices.pop()
echo &"My {guesses}{suffix(guesses)} guess is {guess}"
# Get scoring.
while true:
stdout.write("How many bulls and cows? ")
(userbulls, usercows) = getValues()
if userbulls != InvalidScore and usercows != InvalidScore:
break
if userbulls == Size:
echo &"Victory! I found the number in {guesses} attempts."
break
history.add((guess, userbulls, usercows))
# Eliminate incompatible choices.
remaining.setLen(0)
for choice in choices:
let (bulls, cows) = score(guess, choice)
if bulls == userbulls and cows == usercows:
remaining.add(choice)
if remaining.len == 0:
echo &"There is an impossibility. For some guess you made an error in scoring."
history.findError()
break
choices = move(remaining)</syntaxhighlight>
{{out}}
<pre>Choose a number with four unique digits between 1 and 9.
Give the number of bulls and cows separated by one or more spaces.
My 1st guess is 3748
How many bulls and cows? 0 2
My 2nd guess is 4139
How many bulls and cows? 1 2
My 3rd guess is 4971
How many bulls and cows? 0 2
My 4th guess is 8193
How many bulls and cows? 0 2
My 5th guess is 9436
How many bulls and cows? 1 1
My 6th guess is 1234
How many bulls and cows? 4 0
Victory! I found the number in 6 attempts.
----
Choose a number with four unique digits between 1 and 9.
Give the number of bulls and cows separated by one or more spaces.
My 1st guess is 6251
How many bulls and cows? 0 2
My 2nd guess is 1597
How many bulls and cows? 1 0
My 3rd guess is 3692
How many bulls and cows? 1 1
My 4th guess is 2687
How many bulls and cows? 1 0
My 5th guess is 1634
How many bulls and cows? 3 0
There is an impossibility. For some guess you made an error in scoring.
What was the number to find? 1234
For guess 6251, score was wrong:
Expected 1 / 1, got 0 / 2.
For guess 3692, score was wrong:
Expected 0 / 2, got 1 / 1.
For guess 2687, score was wrong:
Expected 0 / 1, got 1 / 0.</pre>
=={{header|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 2,157 ⟶ 2,661:
# $+{BULLS} and $+{COWS}.
sub read_score :prototype($) {
(my $guess) = @_;
Line 2,171 ⟶ 2,675:
}
sub score_correct :prototype($$$$) {
my ($a, $b, $bulls, $cows) = @_;
Line 2,195 ⟶ 2,699:
"Your secret number is @candidates":
"I think you made a mistake with your scoring");
</syntaxhighlight>
Sample game:
<
My guess: 1869 (from 3024 possibilities)
1 0
Line 2,208 ⟶ 2,712:
0 3
Your secret number is 1357
msl@64Lucid:~/perl$</
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #000000;">bulls</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">else</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;">goal</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<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>
<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>
<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>
<span style="color: #008080;">else</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">bits</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<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>
<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>
<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>
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #000000;">attempt</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<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>
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
<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>
<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,338 ⟶ 2,845:
+---------+-----------------------------+-------+------+
</pre>
=={{header|PicoLisp}}==
<
(de bullsAndCows ()
Line 2,358 ⟶ 2,864:
Choices ) )
(NIL Choices "No matching solution")
(NIL (cdr Choices) (pack "The answer is " (car Choices))) ) ) ) )</
Output:
<pre>: (bullsAndCows)
Line 2,372 ⟶ 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 :
<
:- use_module(library(clpfd)).
Line 2,509 ⟶ 3,014:
H #\= H1,
compte_bien_placees(T, T1, MPC, MPF).
</syntaxhighlight>
The code to play :
<
retractall('ia.pl':guess(_,_)),
retractall(coups(_)),
Line 2,532 ⟶ 3,037:
add_1(X, Y) :-
Y is X + 1.
</syntaxhighlight>
A game :
<pre> ?- bulls_and_cows.
Line 2,557 ⟶ 3,062:
true .
</pre>
=={{header|PureBasic}}==
<
Structure history
answer.s
Line 2,664 ⟶ 3,168:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>Playing Bulls & Cows with 4 unique digits.
Line 2,678 ⟶ 3,182:
Press ENTER to exit</pre>
=={{header|Python}}==
<
from random import shuffle
Line 2,734 ⟶ 3,237:
'\n '.join("%s -> %s" % (''.join(an),sc)
for an,sc in izip(answers, scores)))
break</
'''Sample output'''
Line 2,756 ⟶ 3,259:
1549 -> (0, 0)
3627 -> (1, 0)</pre>
=={{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.
<syntaxhighlight lang="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 <- nrow(validGuesses)
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] "))
#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 following lines make 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)
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE]
if(nrow(validGuesses) == 0) return("Error: Scoring problem?")
}
}
bullsAndCowsPlayer()</syntaxhighlight>
{{out}}
<pre>> bullsAndCowsPlayer()
Possibilities remaining: 3024
My guess is 3619. Bull score? [0-4] 0
Cow score? [0-4] 3
Possibilities remaining: 220
My guess is 1923. Bull score? [0-4] 1
Cow score? [0-4] 1
Possibilities remaining: 48
My guess is 1736. Bull score? [0-4] 4
[1] "Your number is 1736. I win!"</pre>
=={{header|Racket}}==
Generate the list of possible choices. Each choice is represented as list of 4 numbers.
<
(require racket/string
racket/list)
Line 2,779 ⟶ 3,321:
(define (listnum->string list)
(apply string-append (map number->string list)))</
Now define some auxiliary functions to parse the user input (with a minimum error checking) and calculate the score of another possible guess.
<
(if (string? score)
(let ([splited-score (string-split score ",")])
Line 2,794 ⟶ 3,336:
(let ([bulls (count = guess chosen)]
[cows+bulls (count in-chosen guess)])
(values bulls (- cows+bulls bulls))))</
Main part of the game.
<
(let loop ([choices all-choices] [num 1])
Line 2,819 ⟶ 3,361:
(begin
(printf "Sorry, I didn't understand that. Please try again.\n")
(loop choices num)))))))</
'''Sample Output:'''
Line 2,842 ⟶ 3,384:
Bulls: 1, Cows: 0
Bad scoring! nothing fits those scores you gave.</pre>
=={{header|Raku}}==
(formerly Perl 6)
Line 2,848 ⟶ 3,389:
{{trans|Perl}}
<syntaxhighlight lang="raku"
# 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 2,886 ⟶ 3,427:
say @candidates
?? "Your secret number is {@candidates[0].join}!"
!! "I think you made a mistake with your scoring.";</
{{out}}
<pre>My guess: 4235.
Line 2,895 ⟶ 3,436:
2 1
Your secret number is 1234!</pre>
=={{header|Red}}==
ups - this is actually a solver, no input of intermediate results required...
<
digits: charset [#"1" - #"9"] ;; bitset for parse rule in valid function
Line 2,930 ⟶ 3,470:
print [CR "Found *" last k: keys-of results "* in " length? k " attempts" CR] ;; cr - constant for newline / carriage return
] ;; forever loop
</syntaxhighlight>
'''Sample output'''
<pre>
Line 2,956 ⟶ 3,496:
(halted)
</pre>
=={{header|REXX}}==
About a third of the REXX program deals with presentation and/or validation of answers.
<
parse arg ? .; if datatype(?,'W') then call random ,,? /*Random seed? Make repeatable*/
L=1234; H=9876; call gen@ /*generate all possibilities. */
Line 3,010 ⟶ 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*/</
=={{header|Ring}}==
<
# Project : Bulls and cows/Player
Line 3,086 ⟶ 3,624:
see "giving " + bulls + " bull(s) and " + cows + " cow(s)." + nl
return [bulls, cows]
</syntaxhighlight>
=={{header|Ruby}}==
Ruby Version 1.9+
<
scores = []
guesses = []
Line 3,117 ⟶ 3,654:
break
end
end</
'''Regular output'''
<pre>
Line 3,137 ⟶ 3,674:
6419 => bulls 1 cows 0
</pre>
=={{header|Scala}}==
<
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
Line 3,174 ⟶ 3,710:
play(allCombinations)
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,191 ⟶ 3,727:
Ye-haw!
</pre>
=={{header|SenseTalk}}==
<
repeat forever
repeat forever
Line 3,313 ⟶ 3,848:
end if
end repeat
end repeat</
=={{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}}==
<
# out numbers containing zeroes or repeated digits.
var candidates = (1234..9876 -> grep {|n| !("#{n}" =~ /0 | (\d) .*? \1 /x) }.map{.digits});
Line 3,360 ⟶ 4,125:
candidates.len == 1 ? ("Your secret number is: %d" % candidates[0].join)
: ("I think you made a mistake with your scoring")
)->say</
'''Output:'''
Line 3,374 ⟶ 4,139:
Your secret number is: 9571
</pre>
=={{header|Tcl}}==
{{trans|Python}}
{{tcllib|struct::list}}
{{tcllib|struct::set}}
<
package require struct::set
Line 3,430 ⟶ 4,194:
break
}
}</
'''Sample Output'''
<pre>
Line 3,453 ⟶ 4,217:
3241 -> (1, 0)
</pre>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,562 ⟶ 4,325:
Next
End Sub
</syntaxhighlight>
{{out}}
<pre>TOSS : 9 2 4 7
Line 3,590 ⟶ 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">
clear screen
Line 3,698 ⟶ 4,535:
n = token(l$, c$(), d$)
return c$(i)
end sub</
=={{header|zkl}}==
{{trans|D}}
<
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,716 ⟶ 4,552:
if(not choices) "Nothing fits the scores you gave.".println();
else "Solution found: ".println(choices[0]);</
{{out}}
<pre>
Line 3,726 ⟶ 4,562:
Solution found: 1234
</pre>
{{omit from|GUISS}}
|