How to resolve the algorithm Bulls and cows step by step in the ALGOL 68 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Bulls and cows step by step in the ALGOL 68 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 ALGOL 68 programming language
Source code in the algol programming language
STRING digits = "123456789";
[4]CHAR chosen;
STRING available := digits;
FOR i TO UPB chosen DO
INT c = ENTIER(random*UPB available)+1;
chosen[i] := available[c];
available := available[:c-1]+available[c+1:]
OD;
COMMENT print((chosen, new line)); # Debug # END COMMENT
OP D = (INT d)STRING: whole(d,0); # for formatting an integer #
print (("I have chosen a number from ",D UPB chosen," unique digits from 1 to 9 arranged in a random order.", new line,
"You need to input a ",D UPB chosen," digit, unique digit number as a guess at what I have chosen", new line));
PRIO WITHIN = 5, NOTWITHIN = 5;
OP WITHIN = (CHAR c, []CHAR s)BOOL: char in string(c,LOC INT,s);
OP NOTWITHIN = (CHAR c, []CHAR s)BOOL: NOT ( c WITHIN s );
INT guesses := 0, bulls, cows;
WHILE
STRING guess;
guesses +:= 1;
WHILE
# get a good guess #
print((new line,"Next guess [",D guesses,"]: "));
read((guess, new line));
IF UPB guess NE UPB chosen THEN
FALSE
ELSE
BOOL ok;
FOR i TO UPB guess WHILE
ok := guess[i] WITHIN digits AND guess[i] NOTWITHIN guess[i+1:]
DO SKIP OD;
NOT ok
FI
DO
print(("Problem, try again. You need to enter ",D UPB chosen," unique digits from 1 to 9", new line))
OD;
# WHILE #
guess NE chosen
DO
bulls := cows := 0;
FOR i TO UPB chosen DO
IF guess[i] = chosen[i] THEN
bulls +:= 1
ELIF guess[i] WITHIN chosen THEN
cows +:= 1
FI
OD;
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))
You may also check:How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the VBA programming language
You may also check:How to resolve the algorithm Multiplication tables step by step in the Tcl programming language
You may also check:How to resolve the algorithm Set puzzle step by step in the Python programming language
You may also check:How to resolve the algorithm File size step by step in the Phix programming language
You may also check:How to resolve the algorithm Strip a set of characters from a string step by step in the jq programming language