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


 
 
    do while len( secret$) <4
        c$ =chr$( int( rnd( 1) *9) +49)
        if not( instr( secret$, c$)) then secret$ =secret$ +c$
    loop
 
    print " Secret number has been guessed....                                                                                 "; secret$
 
    guesses  =   0
 
[loop]
    print " Your guess ";
    input " "; guess$
 
    guesses  = guesses +1
 
    r$       =score$( guess$, secret$)
 
    bulls    =val( word$( r$, 1, ","))
    cows     =val( word$( r$, 2, ","))
 
    print "   Result: "; bulls; " bulls, and "; cows; " cows"
    print
 
    if guess$ =secret$ then
        print "  You won after "; guesses; " guesses!"
        print "  You guessed it in "; guesses
        print "  Thanks for playing!"
        wait
    end if
 
    goto [loop]
 
end '   _____________________________________________________________
 
function check( i$) '   check =0 if no digit repeats, else =1
    check =0
    for i =1 to 3
        for j =i +1 to 4
            if mid$( i$, i, 1) =mid$( i$, j, 1) then check =1
        next j
    next i
end function
 
function score$( a$, b$)    '   return as a csv string the number of bulls & cows.
    bulls    = 0:  cows     = 0
    for i = 1 to 4
        c$ = mid$( a$, i, 1)
        if mid$( b$, i, 1) = c$ then
            bulls = bulls + 1
        else
            if instr( b$, c$) <>0 and instr( b$, c$) <>i then
                cows = cows + 1
            end if
        end if
    next i
    score$ =str$( bulls); ","; str$( cows)
end function
 
[quit]
close #w
end
 