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


 
# Project : Bulls and cows
 
secret = ""
while len(secret) != 4
        c = char(48 + random(9))
        if substr(secret, c) = 0
           secret = secret + c
        ok
end
 
see "guess a four-digit number with no digit used twice."
guesses = 0
guess = ""
while true
        guess = ""
        while len(guess) != 4
                see "enter your guess: "
                give guess
                if len(guess) != 4
                   see "must be a four-digit number" + nl
                ok
        end 
        guesses = guesses + 1 
        if guess = secret
           see "you won after " + guesses + " guesses!"
           exit             
        ok 
        bulls = 0
        cows = 0
        for i = 1 to 4
             c = secret[i]
             if guess[i] = c
                bulls = bulls + 1
             but substr(guess, c) > 0
                 cows = cows + 1
             ok
        next
        see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
end
 