Last active
May 26, 2025 11:34
-
-
Save jsundram/4db7db8e3bb28bb3386ca3392360fdee to your computer and use it in GitHub Desktop.
Solve the NY Times' Letter Boxed game in 2 guesses (modified version of KV's code/algorithm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import time | |
import re | |
import sys | |
def get_words(filename='words.txt'): | |
# https://raw.githubusercontent.com/dwyl/english-words/master/words.txt | |
with open(filename) as f: | |
return [line.strip() for line in f] | |
def is_valid(word, box, pat): | |
if not pat.fullmatch(word): | |
return False | |
prev_side = None | |
for c in word: | |
side = box[c] | |
if side == prev_side: | |
return False | |
prev_side = side | |
return True | |
def find_solutions(possibilities): | |
lasts = set(s[-1] for s in possibilities) | |
# Possibilities Starting With Letter => pswl | |
pswl = {l: [s for s in possibilities if s[0] == l] for l in lasts} | |
solutions = [] | |
for s in possibilities: | |
for t in pswl[s[-1]]: | |
if len(set(s + t)) == 12: | |
solutions.append((s, t)) | |
return solutions | |
def main(puzzle): | |
words = get_words() | |
start = time() | |
box = {c: i//3 for i, c in enumerate(puzzle)} | |
pat = re.compile("^[%s]+" % puzzle) | |
possibilities = [w for w in words if is_valid(w, box, pat)] | |
solutions = find_solutions(possibilities) | |
for s, t in solutions: | |
print("Success! %s + %s" % (s, t)) | |
print("%2.3fs" % (time() - start)) | |
if __name__ == '__main__': | |
try: | |
main(sys.argv[1]) | |
except IndexError: | |
puzzle = 'IFTELHDRWMAO'.lower() | |
main(puzzle) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh! this is how the website owner found two word solutions of letter boxed puzzle within few minutes. i wounder how they can quickly give today Letterboxed answers of daily NYT puzzle and publish it on their website within 5 minutes. It took me half an hour to solve the puzzle. I am not much technical and coding person but i got an idea.