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


size = 4
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
 
i = 0
loop do
  i += 1
  loop do
    print "Guess #{i}: "
    guess = gets.not_nil!.chomp.chars
    exit if guess.empty?
 
    break if guess.size == size &&
             guess.all? { |x| ('1'..'9').includes? x } &&
             guess.uniq.size == size
 
    puts "Problem, try again. You need to enter #{size} unique digits from 1 to 9"
  end
 
  if guess == secret
    puts "Congratulations you guessed correctly in #{i} attempts"
    break
  end
 
  bulls = cows = 0
  size.times do |j|
    if guess[j] == secret[j]
      bulls += 1
    elsif secret.includes? guess[j]
      cows += 1
    end
  end
 
  puts "Bulls: #{bulls}; Cows: #{cows}"
end