Skip to content
Game 11 Unit 3 of 6 1 hr learning time

Cows

The hard clue: a digit that is in the code but in the wrong place. Count it by tallying each digit in both arrays, summing the overlaps, and subtracting the bulls.

50% of Locksmith

A cow is a digit that is in the code but in the wrong place — and it is the one genuinely hard piece of Locksmith. The trap is double-counting: with repeated digits, a naive "is it anywhere in the code?" check scores the same digit too many times. The clean fix is to think in counts, not positions.

  10 BORDER 0: PAPER 0: INK 7: CLS
 130 RANDOMIZE
 140 DIM c(4)
 150 FOR i = 1 TO 4: LET c(i) = INT (RND * 6) + 1: NEXT i
 160 CLS
 170 PRINT "The code is: ";
 180 FOR i = 1 TO 4: PRINT c(i);: NEXT i
 190 PRINT
 220 INPUT "Your guess (4 digits): "; g$
 230 IF LEN g$ <> 4 THEN GO TO 220
 240 IF g$(1) < "1" OR g$(1) > "6" OR g$(2) < "1" OR g$(2) > "6" OR g$(3) < "1" OR g$(3) > "6" OR g$(4) < "1" OR g$(4) > "6" THEN GO TO 220
 250 DIM g(4)
 260 FOR i = 1 TO 4: LET g(i) = VAL g$(i): NEXT i
 270 LET bulls = 0
 280 FOR i = 1 TO 4
 290 IF g(i) = c(i) THEN LET bulls = bulls + 1
 300 NEXT i
 310 LET total = 0
 320 FOR d = 1 TO 6
 330 LET cc = 0: LET gc = 0
 340 FOR i = 1 TO 4
 350 IF c(i) = d THEN LET cc = cc + 1
 360 IF g(i) = d THEN LET gc = gc + 1
 370 NEXT i
 380 IF cc <= gc THEN LET total = total + cc
 390 IF gc < cc THEN LET total = total + gc
 400 NEXT d
 410 LET cows = total - bulls
 420 PRINT "Bulls: "; bulls; "  Cows: "; cows
ZX Spectrum Locksmith: The code is: 1666, a guess, and Bulls: 1  Cows: 2
The full clue: one digit right and placed, two more present but misplaced.

Count each digit in both, take the smaller

Lines 320–400 loop over every possible digit, FOR d = 1 TO 6. For each, an inner loop counts how many times d appears in the code (cc) and in the guess (gc). The number the two share is whichever count is smaller — if the code has two 6s and the guess has three, they share two. Lines 380–390 add that smaller count to a running total. After all six digits, total is how many digits the guess got right regardless of position — bulls and cows together.

Cows are the leftover

The last step is the neat one. total counts every correct digit, placed or not; the bulls are the ones already in the right spot. So line 410 — LET cows = total - bulls — is exactly the misplaced ones. Subtracting the bulls is what stops a placed digit being counted twice, and the "take the smaller count" rule is what stops a repeated digit being over-credited. Together they give the right answer even for codes like 1666.

This counting approach — tally each value, compare tallies — is a genuine algorithm, the kind you reach for whenever two collections have to be compared by content, not order. It is the heart of Locksmith, and the rest of the game is presentation around it.

Next: ten guesses, with every result kept on screen.