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


 
Module Game {
      Malformed=lambda (a$)->{
            =true
            if len(a$)<>4 then exit
            n=0 : dummy=val(a$,"int",n)
            if n<>5 or dummy=0 then exit
            for i=1 to 9 
                  if len(filter$(a$,str$(i,0)))<3 then break
            next i
            =false
      }
      BullsAndCows$=lambda$ (a$, b$, &ok) ->{
            Def b, c
            for i=1 to 4
            if mid$(a$,i,1)=mid$(b$,i,1) then
                  b++
            else.if instr(b$,mid$(a$,i,1))>0 then
                  c++
            end if
            next i
            ok=b=4
            =format$("bulls {0}, cows {1}", b, c)
      }
      Random$=lambda$ ->{ 
            def repl$, bank$, c$
            bank$="123456789"
            for i=1 to 4
                  c$=mid$(bank$,random(1,len(bank$)),1)
                  bank$=filter$(bank$, c$)
                  repl$+=c$
            next i
            =repl$
      }
      target$=Random$()
      def boolean win=false, a$
      do
            do  
                  Input "Next guess ";a%
                  a$=str$(a%,0)
                  if Malformed(a$) then Print "Malformed input, try again" else exit
            always
            Print BullsAndCows$(a$, target$, &win)
            if win then exit
            Print "Bad guess! (4 unique digits, 1-9)"
      always
      Print "You guess it"
}
Game
 