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


require 'misc'
 
plural=: conjunction define
 (":m),' ',n,'s'#~1~:m
)
 
bullcow=:monad define
  number=. 1+4?9
  whilst. -.guess-:number do.
    guess=. 0 "."0 prompt 'Guess my number: '
    if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do.
      if. 0=#guess do.
        smoutput 'Giving up.'
        return.
      end.
      smoutput 'Guesses must be four different non-zero digits'
      continue.
    end.
    bulls=. +/guess=number
    cows=. (+/guess e.number)-bulls
    smoutput bulls plural 'bull',' and ',cows plural 'cow','.'
  end.
  smoutput 'you win'
)