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


(de ok? (N)
   (let D (mapcar 'format (chop N))
      (and (num? N)
           (not (member 0 D))
           (= 4 (length D))
           (= D (uniq D))
           D )) )
 
(de init-cows ()
   (until (setq *Hidden (ok? (rand 1234 9876)))) )
 
(de guess (N)
   (let D (ok? N)
      (if D
         (let Bulls (cnt '= D *Hidden)
            (if (= 4 Bulls)
               " You guessed it!"
               (let Cows (- (cnt '((N) (member N *Hidden)) D) Bulls)
                  (pack Bulls " bulls, " Cows " cows") ) ) )
         " Bad guess! (4 unique digits, 1-9)" ) ) )
 