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


dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
  h = i + random (9 - i)
  swap dig[i] dig[h]
.
# print dig[]
len g[] 4
attempts = 0
repeat
  repeat
    ok = 0
    s$[] = strchars input
    if len s$[] = 4
      ok = 1
      for i range 4
        g[i] = number s$[i]
        if g[i] = 0
          ok = 0
        .
      .
    .
    until ok = 1
  .
  print g[]
  attempts += 1
  bulls = 0
  cows = 0
  for i range 4
    if g[i] = dig[i]
      bulls += 1
    else
      for j range 4
        if dig[j] = g[i]
          cows += 1
        .
      .
    .
  .
  print "bulls:" & bulls & " cows:" & cows
  until bulls = 4
.
print "Well done! " & attempts & " attempts needed."