Numble uses a four-digit code in which digits can repeat. After a guess, a tile is green in the right place, yellow when the digit is elsewhere in the code, and grey when it is absent or every copy has already been used. The hard part is a guess with more copies of a digit than the code holds.
An allowance per digit
For each digit, the number of coloured tiles is the smaller of its copies in the guess and its copies in the code. Greens are part of that allowance and the remainder goes to yellows, left to right:
from collections import Counter
def score(guess, code):
green = [g == c for g, c in zip(guess, code)]
greens = Counter(g for g, hit in zip(guess, green) if hit)
# coloured tiles per digit: copies in the guess or in the code, whichever is fewer
left = {d: min(n, code.count(d)) - greens[d] for d, n in Counter(guess).items()}
tiles = []
for g, hit in zip(guess, green):
if hit:
tiles.append("G")
elif left[g] > 0:
left[g] -= 1
tiles.append("Y")
else:
tiles.append("-")
return "".join(tiles)
Codes and guesses are strings, since a code may begin with a zero. Counter returns 0 for a digit it has not seen, so greens[d] needs no default.
Take guess 6066 against code 6606. Digit 6 appears three times in each, so three tiles may be coloured. Two are green, which leaves one yellow, and it goes to the third tile. The 0 has an allowance of one and gets a yellow. The result is GYYG.
With guess 9955 against code 5090 there are no greens. Each of 9 and 5 has an allowance of one, so the first 9 and the first 5 are yellow and the repeats are not coloured: Y-Y-.
Tests
A few hand-worked cases, then a check of the rule itself on random pairs:
import random
def test_table():
assert score("9955", "5090") == "Y-Y-"
assert score("6066", "6606") == "GYYG"
assert score("7777", "1779") == "-GG-"
def test_properties():
rng = random.Random(28)
for _ in range(200_000):
guess, code = (f"{rng.randrange(10_000):04d}" for _ in range(2))
tiles = score(guess, code)
for d in set(guess):
spots = [i for i in range(4) if guess[i] == d]
coloured = [i for i in spots if tiles[i] != "-"]
assert len(coloured) == min(len(spots), code.count(d))
assert all((tiles[i] == "G") == (code[i] == d) for i in spots)
Both pass, and test_properties runs in about a second. The property restates the allowance, so it mainly catches slips in the loop. A scorer that hands out colours in one left-to-right pass, taking a copy for each green or yellow as it goes, fails it on 7777 against 1779, where it returns YGG-, and on about 4 per cent of random pairs.
For an independent check I ran 100,000 random pairs through the colouring code that Numble itself serves and compared the output with score. They agreed on every pair.
Top comments (0)