By: perfectionatic
Re-posted from: https://perfectionatic.org/?p=753
Wordle is a fun and easy game that has shot to fame recently. It is completely minimalistic, no-fills and highly addictive. We will explore here how to write as simple solver for Wordle with Julia and then adding layers of complexity and sophistication as we go along.
In Wordle we are successively guessing five-letter words. After each guess the game tells us which of our letters occur in the secret word and whether they are in the correct position. As explained in their website.
So after each guess we narrow the set of possible words to choose from till we arrive at the secret word, and we only have six tries.
Our Dictionary
Wordle only deals with a valid five-letter English words. So we need to start grabbing such words. A good place to start is the Standford GraphBase data set.
Constraints
The next step is the try narrow down the set of feasible words as we are getting clues. Towards that end, we construct a Dict
to map letters that are in the word at the correct spot to their location, another Dict
to maps letter in the word that are in the wrong spot, and finally a Set
of letters that are not in the word:
Now we can encode the the response we get the game as String
of numbers, where 0 means that the character is not in the word, 1 means the that character is the word but not in the right spot, and 2 means that the character is in the word at the correct spot. For example
Secret Word: perky Candidate Word: ebony Response: 10002
We can update our set of constraint for any response by the following function:
Shrinking the feasible set of words
The constraints will reduce the feasible set of possible words. This can be done by applying filters that make use of constraints as in the following function:
Putting it all together
So all what we have to do now is to apply the following step
- Guess a candidate first word
- Get response from the Game
- Use that response to update the set of constraints
- Use the constraints to reduce the set of possible words
- Guess the new candidate word
- Repeat step 2 until a word is found or the game is over
In the steps 1 and 5 above, the simplest approach is just to pick a word at random. Below is Julia repl session showing how we go about applying the above. The secret word here is “super”
We see that we arrived at the correct word after guessing
- excel
- buyer
- fumer
- purer
- super
That is a 5/6 score. Not too bad! But we could do better. How? We explore that in the next part.
See also below an interactive session where the secret word is “wrung”