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 Nanoquery.Util; random = new(Random)
 
// a function to verify the user's input
def verify_digits(input)
	global size
	seen = ""
 
	if len(input) != size
		return false
	else
		for char in input
			if not char in "0123456789"
				return false
			else if char in seen
				return false
			end
 
			seen += char
		end
	end
 
	return true
end
 
size = 4
chosen = ""
while len(chosen) < size
	digit = random.getInt(8) + 1
 
	if not str(digit) in chosen
		chosen += str(digit)
	end
end
 
println "I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order."
println "You need to input a 4 digit, unique digit number as a guess at what I have chosen."
 
guesses = 1
won = false
while !won
	print "\nNext guess [" + str(guesses) + "]: "
	guess = input()
 
	if !verify_digits(guess)
		println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
	else
		if guess = chosen
			won = true
		else
			bulls = 0
			cows = 0
			for i in range(0, size - 1)
				if guess[i] = chosen[i]
					bulls += 1
				else if guess[i] in chosen
					cows += 1
				end
			end
 
			println format("  %d Bulls\n  %d Cows", bulls, cows)
			guesses += 1
		end
	end
end
 
println "\nCongratulations you guess correctly in " + guesses + " attempts"