Bulls and Cows


Task

Create a four digit random number from the digits   1   to   9,   without duplication.

The program should:

   ask for guesses to this number
   reject guesses that are malformed
   print the score for the guess


The score is computed as:

 The player wins if the guess is the same as the randomly chosen number, and the program ends.
 A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
 A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.


Related tasks

   Bulls and cows/Player
   Guess the number
   Guess the number/With Feedback
   Mastermind


procedure main()
    digits := "123456789"
    every !digits :=: ?digits
    num := digits[1+:4]
    repeat if score(num, getGuess(num)) then break
    write("Good job.")
end
 
procedure getGuess(num)
    repeat {
        writes("Enter a guess: ")
        guess := read() | stop("Quitter!")
        if *(guess ** '123456789') == *num then return guess
        write("Malformed guess: ",guess,". Try again.")
        }
end
 
procedure score(num, guess)
    bulls := 0
    cows := *(num ** guess)
    every (num[i := 1 to *num] == guess[i], bulls +:= 1, cows -:= 1)
    write("\t",bulls," bulls and ",cows," cows")
    return (bulls = *num)
end