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


var size = 4
var num = @(1..9).shuffle.first(size)
 
for (var guesses = 1; true; guesses++) {
 
    var bulls = 0
    var cows  = 0
 
    var input =
        read("Input: ", String).chars           \
                               .uniq            \
                               .grep(/^[1-9]$/) \
                               .map{.to_n}
 
    if (input.len != size) {
        warn "Invalid input!\n"
        guesses--
        next
    }
 
    if (input == num) {
        printf("You did it in %d attempts!\n", guesses)
        break
    }
 
    for i (^num) {
        if (num[i] == input[i]) {
            bulls++
        }
        elsif (num.contains(input[i])) {
            cows++
        }
    }
 
    "Bulls: %d; Cows: %d\n".printf(bulls, cows)
}