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


      secret$ = ""
      REPEAT
        c$ = CHR$(&30 + RND(9))
        IF INSTR(secret$, c$) = 0 secret$ += c$
      UNTIL LEN(secret$) = 4
 
      PRINT "Guess a four-digit number with no digit used twice."'
      guesses% = 0
      REPEAT
 
        REPEAT
          INPUT "Enter your guess: " guess$
          IF LEN(guess$) <> 4 PRINT "Must be a four-digit number"
        UNTIL LEN(guess$) = 4
        guesses% += 1
 
        IF guess$ = secret$ PRINT "You won after "; guesses% " guesses!" : END
 
        bulls% = 0
        cows% = 0
        FOR i% = 1 TO 4
          c$ = MID$(secret$, i%, 1)
          IF MID$(guess$, i%, 1) = c$ THEN
            bulls% += 1
          ELSE IF INSTR(guess$, c$) THEN
              cows% += 1
            ENDIF
          ENDIF
        NEXT i%
        PRINT "You got " ;bulls% " bull(s) and " ;cows% " cow(s)."
 
      UNTIL FALSE
 