Bulls and cows/Player: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|J}}: slight simplification)
m (syntax highlighting fixup automation)
Line 18:
 
bulls_player.adb:
<langsyntaxhighlight lang=Ada>with Ada.Text_IO;
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
Line 227:
-- solve the puzzle
Solve;
end Bulls_Player;</langsyntaxhighlight>
 
output:
Line 255:
 
=={{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:
. 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:
NEXT i%
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 526:
 
return 0;
}</langsyntaxhighlight>sample output for 4 digits:<syntaxhighlight lang=text>--------+--------------------
Secret | 5437
--------+--------------------
Line 541:
Score | 4 bull, 0 cow
--------+--------------------
</langsyntaxhighlight>sample output for 9 digits<syntaxhighlight lang=text>--------+--------------------
Secret | 758214936
--------+--------------------
Line 576:
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:
}
}
</syntaxhighlight>
</lang>
Example output:-
<pre>
Line 676:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>
#include <iostream>
#include <sstream>
Line 796:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
Output:
<pre>
Line 818:
 
=={{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:
(setq b (bulls number guess))
(setq c (- (bulls+cows number guess) b)))))
</syntaxhighlight>
</lang>
Output:
<pre>
Line 879:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=Ruby>size = 4
scores = [] of Tuple(Int32, Int32)
guesses = [] of Array(Char)
Line 907:
break
end
end</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang=d>void main() {
import std.stdio, std.random, std.algorithm, std.range, std.ascii;
 
Line 929:
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 940:
=={{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:
end
 
Bulls_and_cows.player</langsyntaxhighlight>
 
{{out}}
Line 1,002:
{{trans|C}}
{{works with|Euphoria|4.*}}
<langsyntaxhighlight lang=euphoria>include std/sequence.e
 
constant line = "--------+--------------------\n"
Line 1,085:
sequence secret = get_digits(n)
printf(1,"%sSecret | %s\n%s", {line, secret, line})
game(secret)</langsyntaxhighlight>
 
Output:
Line 1,108:
 
=={{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:
] [ drop "Scoring inconsistency." print ] if* ;
 
possibilities game</langsyntaxhighlight>
{{out}}
<pre>
Line 1,152:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang=fortran>module Player
implicit none
 
Line 1,260:
end if
end do
end program</langsyntaxhighlight>
Output
<pre>
Line 1,285:
=={{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:
}
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import Data.List
import Control.Monad
import System.Random (randomRIO)
Line 1,415:
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:
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=: ' ' -.~ ":
Line 1,450:
'no valid possibilities'
end.
}}</langsyntaxhighlight>
 
For example:
<langsyntaxhighlight lang=j> play''
guessing 7461
how many bull and cows? 0 1
Line 1,462:
guessing 1359
how many bull and cows? 3 0
the answer is 1358</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang=Java>
public class BullsAndCowsPlayerGame {
 
Line 1,546:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Java>
public abstract class AbstractGuessNumber {
 
Line 1,587:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Java>
public class GameNumber extends AbstractGuessNumber {
 
Line 1,658:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Java>
public class AutoGuessNumber extends AbstractGuessNumber {
 
Line 1,690:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Java>
public class GuessResult {
 
Line 1,741:
}
}
</syntaxhighlight>
</lang>
Sample game:
{{out}}
Line 1,779:
=={{header|Julia}}==
{{works with|Julia version 0.6.0}}
<langsyntaxhighlight 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,808:
answ = doguess()
println("The winning pick: $(answ[1])$(answ[2])$(answ[3])$(answ[4])")
</syntaxhighlight>
</lang>
Example game:
<langsyntaxhighlight lang=Julia>
My guess: 9517. How many bulls and cows?
0 1
Line 1,826:
4 0
The winning pick: 3124
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.1.2
 
import java.util.Random
Line 1,880:
println("Something went wrong as no choices left! Aborting program")
}
}</langsyntaxhighlight>
Sample game:
{{out}}
Line 1,898:
=={{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,998:
if instr( i$, "0") then check =1
end function
</syntaxhighlight>
</lang>
 
 
=={{header|Lua}}==
{{Trans|Phix}}
<langsyntaxhighlight lang=Lua>local line = "---------+----------------------------------+-------+-------+"
local digits = {1,2,3,4,5,6,7,8,9}
 
Line 2,113:
print (line..'\nSecret '.. #secret.. ' | '..table.concat(secret) .. ' | Bulls | Cows |' .. '\n' .. line)
 
game (secret)</langsyntaxhighlight>
 
{{out}}
Line 2,141:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight 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,154:
Print[ToString@Length@candidates<>" candidates remaining."];
Print["Can try "<>StringJoin[ToString/@First@candidates]<>"."];
]]]]</langsyntaxhighlight>
Output:
<pre>120 candidates remaining.
Line 2,165:
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang=MATLAB>function BullsAndCowsPlayer
% Plays the game Bulls and Cows as the player
Line 2,222:
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end</langsyntaxhighlight>
{{out}}
Secret number: 5612
Line 2,276:
=={{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 lang=Nim>import parseutils
import random
import sequtils
Line 2,408:
history.findError()
break
choices.shallowCopy(remaining)</langsyntaxhighlight>
 
{{out}}
Line 2,453:
{{works with|Perl 5.10.0 and above}}
 
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use strict;
Line 2,506:
"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,519:
0 3
Your secret number is 1357
msl@64Lucid:~/perl$</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<langsyntaxhighlight 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>
Line 2,595:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
N=4:
Line 2,654:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(load "@lib/simul.l")
 
(de bullsAndCows ()
Line 2,672:
Choices ) )
(NIL Choices "No matching solution")
(NIL (cdr Choices) (pack "The answer is " (car Choices))) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (bullsAndCows)
Line 2,691:
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 lang=Prolog>:- module('ia.pl', [tirage/1]).
:- use_module(library(clpfd)).
 
Line 2,823:
H #\= H1,
compte_bien_placees(T, T1, MPC, MPF).
</syntaxhighlight>
</lang>
The code to play :
<langsyntaxhighlight lang=Prolog>bulls_and_cows :-
retractall('ia.pl':guess(_,_)),
retractall(coups(_)),
Line 2,846:
add_1(X, Y) :-
Y is X + 1.
</syntaxhighlight>
</lang>
A game :
<pre> ?- bulls_and_cows.
Line 2,873:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>#answerSize = 4
Structure history
answer.s
Line 2,978:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Playing Bulls & Cows with 4 unique digits.
Line 2,994:
 
=={{header|Python}}==
<langsyntaxhighlight lang=python>from itertools import permutations
from random import shuffle
 
Line 3,048:
'\n '.join("%s -> %s" % (''.join(an),sc)
for an,sc in izip(answers, scores)))
break</langsyntaxhighlight>
 
'''Sample output'''
Line 3,072:
=={{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 lang=rsplus>bullsAndCowsPlayer <- function()
{
guesses <- 1234:9876
Line 3,098:
}
}
bullsAndCowsPlayer()</langsyntaxhighlight>
{{out}}
<pre>> bullsAndCowsPlayer()
Line 3,113:
=={{header|Racket}}==
Generate the list of possible choices. Each choice is represented as list of 4 numbers.
<langsyntaxhighlight lang=Racket>#lang racket/base
(require racket/string
racket/list)
Line 3,133:
 
(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 lang=Racket> (define (parse-score score)
(if (string? score)
(let ([splited-score (string-split score ",")])
Line 3,148:
(let ([bulls (count = guess chosen)]
[cows+bulls (count in-chosen guess)])
(values bulls (- cows+bulls bulls))))</langsyntaxhighlight>
 
Main part of the game.
<langsyntaxhighlight lang=Racket>(printf "Playing Bulls & Cows with ~a unique digits\n" size)
(let loop ([choices all-choices] [num 1])
Line 3,173:
(begin
(printf "Sorry, I didn't understand that. Please try again.\n")
(loop choices num)))))))</langsyntaxhighlight>
 
'''Sample Output:'''
Line 3,202:
{{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,240:
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,252:
=={{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,284:
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,313:
=={{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,364:
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,440:
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,471:
break
end
end</langsyntaxhighlight>
'''Regular output'''
<pre>
Line 3,493:
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
Line 3,528:
play(allCombinations)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,547:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang=sensetalk>set the remoteWorkInterval to .001 -- optional
repeat forever
repeat forever
Line 3,667:
end if
end repeat
end repeat</langsyntaxhighlight>
 
=={{header|Shale}}==
 
<langsyntaxhighlight lang=Shale>#!/usr/local/bin/shale
 
maths library
Line 3,875:
{ true } {
solve()
} while</langsyntaxhighlight>
 
{{out}}
Line 3,902:
 
=={{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,946:
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,965:
{{tcllib|struct::list}}
{{tcllib|struct::set}}
<langsyntaxhighlight lang=tcl>package require struct::list
package require struct::set
 
Line 4,016:
break
}
}</langsyntaxhighlight>
'''Sample Output'''
<pre>
Line 4,042:
=={{header|VBA}}==
 
<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
Line 4,148:
Next
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>TOSS : 9 2 4 7
Line 4,179:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=ecmascript>import "random" for Random
 
var countBullsAndCows = Fn.new { |guess, answer|
Line 4,235:
System.print("Something went wrong as no choices left! Aborting program")
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,254:
=={{header|Yabasic}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang=Yabasic>
clear screen
 
Line 4,359:
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 4,377:
 
if(not choices) "Nothing fits the scores you gave.".println();
else "Solution found: ".println(choices[0]);</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits