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


(import random)
 
(def +size+ 4)
(def +digits+ "123456789")
(def +secret+ (random.sample +digits+ +size+))
 
(while True
  (while True
    (setv guess (list (distinct (raw-input "Enter a guess: "))))
    (when (and
        (= (len guess) +size+)
        (all (map (fn [c] (in c +digits+)) guess)))
      (break))
    (print "Malformed guess; try again"))
  (setv bulls 0)
  (setv cows 0)
  (for [i (range +size+)] (cond
    [(= (get guess i) (get +secret+ i)) (setv bulls (inc bulls))]
    [(in (get guess i) +secret+) (setv cows (inc cows))]))
  (when (= bulls +size+)
    (break))
  (print (.format "{} bull{}, {} cows"
    bulls (if (= bulls 1) "" "s")
    cows (if (= cows 1) "" "s"))))
 
(print "A winner is you!")