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


secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")
 
while true
    guess = input("Your guess? ").split("")
    if guess.len != 4 then
        print "Please enter 4 numbers, with no spaces."
        continue
    end if
    bulls = 0
    cows = 0
    for i in guess.indexes
        if secret[i] == guess[i] then
            bulls = bulls + 1
        else if secret.indexOf(guess[i]) != null then
            cows = cows + 1
        end if
    end for
    if bulls == 4 then
        print "You got it!  Great job!"
        break
    end if
    print "You score " + bulls + " bull" + "s"*(bulls!=1) + 
    " and " + cows + " cow" + "s"*(cows!=1) + "."
end while