How to resolve the algorithm Bulls and cows step by step in the Ceylon programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Bulls and cows step by step in the Ceylon programming language
Table of Contents
Problem Statement
Bulls and Cows is an old game played with pencil and paper that was later implemented using computers.
Create a four digit random number from the digits 1 to 9, without duplication. The program should:
The score is computed as:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Bulls and cows step by step in the Ceylon programming language
Source code in the ceylon programming language
import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
function generateDigits() =>
random.elements(1..9).distinct.take(4).sequence();
function validate(String guess) {
variable value ok = true;
if (!guess.every((Character element) => element.digit)) {
print("numbers only, please");
ok = false;
}
if ('0' in guess) {
print("only 1 to 9, please");
ok = false;
}
if (guess.distinct.shorterThan(guess.size)) {
print("no duplicates, please");
ok = false;
}
if (guess.size != 4) {
print("4 digits please");
ok = false;
}
return ok;
}
function score({Integer*} target, {Integer*} guess) {
variable value bulls = 0;
variable value cows = 0;
for ([a, b] in zipPairs(target, guess)) {
if (a == b) {
bulls++;
} else if (target.contains(b)) {
cows++;
}
}
return [bulls, cows];
}
while (true) {
value digits = generateDigits();
print("I have chosen my four digits, please guess what they are.
Use only the digits 1 to 9 with no duplicates and enter them with no spaces. eg 1234
Enter q or Q to quit.");
while (true) {
if (exists line = process.readLine()) {
if (line.uppercased == "Q") {
return;
}
if (validate(line)) {
value guessDigits = line.map((Character element) => Integer.parse(element.string)).narrow();
value [bulls, cows] = score(digits, guessDigits);
if (bulls == 4) {
print("You win!");
break;
}
else {
print("Bulls: ``bulls``, Cows: ``cows``");
}
}
}
}
}
}
You may also check:How to resolve the algorithm Secure temporary file step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the GAP programming language
You may also check:How to resolve the algorithm Paraffins step by step in the Raku programming language
You may also check:How to resolve the algorithm Find common directory path step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Letter frequency step by step in the Scala programming language