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


: bullsAndCows
| numbers guess digits bulls cows |
 
   ListBuffer new ->numbers
   while(numbers size 4 <>) [ 9 rand dup numbers include ifFalse: [ numbers add ] else: [ drop ] ]
 
   while(true) [
      "Enter a number of 4 different digits between 1 and 9 : " print
      System.Console askln ->digits
      digits asInteger isNull digits size 4 <> or ifTrue: [ "Number of four digits needed" println continue ]
      digits map(#asDigit) ->guess
 
      guess numbers zipWith(#==) occurrences(true) ->bulls
      bulls 4 == ifTrue: [ "You won !" println return ]
 
      guess filter(#[numbers include]) size bulls - ->cows
      System.Out "Bulls = " << bulls << ", cows = " << cows << cr
      ] ;