Bulls and cows/Player: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|J}}: slight simplification) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 18:
bulls_player.adb:
<
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
Line 227:
-- solve the puzzle
Solve;
end Bulls_Player;</
output:
Line 255:
=={{header|AutoHotkey}}==
<
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
}</
=={{header|BBC BASIC}}==
<
REPEAT
c$ = CHR$(&30 + RND(9))
Line 422:
NEXT i%
ENDPROC
</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 526:
return 0;
}</
Secret | 5437
--------+--------------------
Line 541:
Score | 4 bull, 0 cow
--------+--------------------
</
Secret | 758214936
--------+--------------------
Line 576:
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:
}
}
</syntaxhighlight>
Example output:-
<pre>
Line 676:
=={{header|C++}}==
<
#include <iostream>
#include <sstream>
Line 796:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
Output:
<pre>
Line 818:
=={{header|Common 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>
Output:
<pre>
Line 879:
=={{header|Crystal}}==
{{trans|Ruby}}
<
scores = [] of Tuple(Int32, Int32)
guesses = [] of Array(Char)
Line 907:
break
end
end</
=={{header|D}}==
<
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]);
}</
{{out|Example output}}
<pre>My guess is 9345. How many bulls and cows? 02
Line 940:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def player(size \\ 4) do
possibility = permute(size) |> Enum.shuffle
Line 984:
end
Bulls_and_cows.player</
{{out}}
Line 1,002:
{{trans|C}}
{{works with|Euphoria|4.*}}
<
constant line = "--------+--------------------\n"
Line 1,085:
sequence secret = get_digits(n)
printf(1,"%sSecret | %s\n%s", {line, secret, line})
game(secret)</
Output:
Line 1,108:
=={{header|Factor}}==
<
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</
{{out}}
<pre>
Line 1,152:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,260:
end if
end do
end program</
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.
<
import (
Line 1,380:
}
}
}</
=={{header|Haskell}}==
<
import Control.Monad
import System.Random (randomRIO)
Line 1,415:
do putStrLn "Wrong input. Try again"
takeInput
else return ui</
Example:
<
My guess is 4923
How many bulls and cows?
Line 1,430:
How many bulls and cows?
4 0
The answer is 4932</
=={{header|J}}==
<
poss=:1+~.4{."1 (i.!9)A.i.9
fmt=: ' ' -.~ ":
Line 1,450:
'no valid possibilities'
end.
}}</
For example:
<
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</
=={{header|Java}}==
<
public class BullsAndCowsPlayerGame {
Line 1,546:
}
}
</syntaxhighlight>
<
public abstract class AbstractGuessNumber {
Line 1,587:
}
}
</syntaxhighlight>
<
public class GameNumber extends AbstractGuessNumber {
Line 1,658:
}
}
</syntaxhighlight>
<
public class AutoGuessNumber extends AbstractGuessNumber {
Line 1,690:
}
}
</syntaxhighlight>
<
public class GuessResult {
Line 1,741:
}
}
</syntaxhighlight>
Sample game:
{{out}}
Line 1,779:
=={{header|Julia}}==
{{works with|Julia version 0.6.0}}
<
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>
Example game:
<
My guess: 9517. How many bulls and cows?
0 1
Line 1,826:
4 0
The winning pick: 3124
</syntaxhighlight>
=={{header|Kotlin}}==
<
import java.util.Random
Line 1,880:
println("Something went wrong as no choices left! Aborting program")
}
}</
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>
guesses =0
Line 1,998:
if instr( i$, "0") then check =1
end function
</syntaxhighlight>
=={{header|Lua}}==
{{Trans|Phix}}
<
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)</
{{out}}
Line 2,141:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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]<>"."];
]]]]</
Output:
<pre>120 candidates remaining.
Line 2,165:
=={{header|MATLAB}}==
<
% Plays the game Bulls and Cows as the player
Line 2,222:
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end</
{{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.
<
import random
import sequtils
Line 2,408:
history.findError()
break
choices.shallowCopy(remaining)</
{{out}}
Line 2,453:
{{works with|Perl 5.10.0 and above}}
<
use warnings;
use strict;
Line 2,506:
"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,519:
0 3
Your secret number is 1357
msl@64Lucid:~/perl$</
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<
<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>
<!--</
{{out}}
N=4:
Line 2,654:
=={{header|PicoLisp}}==
<
(de bullsAndCows ()
Line 2,672:
Choices ) )
(NIL Choices "No matching solution")
(NIL (cdr Choices) (pack "The answer is " (car Choices))) ) ) ) )</
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 :
<
:- use_module(library(clpfd)).
Line 2,823:
H #\= H1,
compte_bien_placees(T, T1, MPC, MPF).
</syntaxhighlight>
The code to play :
<
retractall('ia.pl':guess(_,_)),
retractall(coups(_)),
Line 2,846:
add_1(X, Y) :-
Y is X + 1.
</syntaxhighlight>
A game :
<pre> ?- bulls_and_cows.
Line 2,873:
=={{header|PureBasic}}==
<
Structure history
answer.s
Line 2,978:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>Playing Bulls & Cows with 4 unique digits.
Line 2,994:
=={{header|Python}}==
<
from random import shuffle
Line 3,048:
'\n '.join("%s -> %s" % (''.join(an),sc)
for an,sc in izip(answers, scores)))
break</
'''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.
<
{
guesses <- 1234:9876
Line 3,098:
}
}
bullsAndCowsPlayer()</
{{out}}
<pre>> bullsAndCowsPlayer()
Line 3,113:
=={{header|Racket}}==
Generate the list of possible choices. Each choice is represented as list of 4 numbers.
<
(require racket/string
racket/list)
Line 3,133:
(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 3,148:
(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 3,173:
(begin
(printf "Sorry, I didn't understand that. Please try again.\n")
(loop choices num)))))))</
'''Sample Output:'''
Line 3,202:
{{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 3,240:
say @candidates
?? "Your secret number is {@candidates[0].join}!"
!! "I think you made a mistake with your scoring.";</
{{out}}
<pre>My guess: 4235.
Line 3,252:
=={{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 3,284:
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 3,313:
=={{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,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*/</
=={{header|Ring}}==
<
# Project : Bulls and cows/Player
Line 3,440:
see "giving " + bulls + " bull(s) and " + cows + " cow(s)." + nl
return [bulls, cows]
</syntaxhighlight>
=={{header|Ruby}}==
Ruby Version 1.9+
<
scores = []
guesses = []
Line 3,471:
break
end
end</
'''Regular output'''
<pre>
Line 3,493:
=={{header|Scala}}==
<
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
Line 3,528:
play(allCombinations)
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,547:
=={{header|SenseTalk}}==
<
repeat forever
repeat forever
Line 3,667:
end if
end repeat
end repeat</
=={{header|Shale}}==
<
maths library
Line 3,875:
{ true } {
solve()
} while</
{{out}}
Line 3,902:
=={{header|Sidef}}==
<
# 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</
'''Output:'''
Line 3,965:
{{tcllib|struct::list}}
{{tcllib|struct::set}}
<
package require struct::set
Line 4,016:
break
}
}</
'''Sample Output'''
<pre>
Line 4,042:
=={{header|VBA}}==
<syntaxhighlight lang=vb>
Option Explicit
Line 4,148:
Next
End Sub
</syntaxhighlight>
{{out}}
<pre>TOSS : 9 2 4 7
Line 4,179:
=={{header|Wren}}==
{{trans|Kotlin}}
<
var countBullsAndCows = Fn.new { |guess, answer|
Line 4,235:
System.print("Something went wrong as no choices left! Aborting program")
}
}</
{{out}}
Line 4,254:
=={{header|Yabasic}}==
{{trans|Liberty BASIC}}
<
clear screen
Line 4,359:
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 4,377:
if(not choices) "Nothing fits the scores you gave.".println();
else "Solution found: ".println(choices[0]);</
{{out}}
<pre>
|