Last active
January 23, 2022 08:45
-
-
Save kddnewton/7d981122a4db3166678f1dc50a5d46b7 to your computer and use it in GitHub Desktop.
Wordle solver
This file contains 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
words = [] | |
letters = ("a".."z").to_a | |
File.foreach("/usr/share/dict/words", chomp: true) do |word| | |
words << word.downcase if word.match?(/\A[a-z]{5}\z/i) | |
end | |
while words.length > 1 | |
weights = letters.to_h { |letter| [letter, 0] } | |
words.each do |word| | |
word.each_char { |letter| weights[letter] += 1 if weights.key?(letter) } | |
end | |
values = words.to_h { |word| [word, word.each_char.uniq.sum { |letter| weights.fetch(letter, 0) }] } | |
guess = values.sort_by { |word, value| -value }.first.first | |
print "#{guess} (%05d)> " % words.length | |
input = gets.chomp.downcase | |
case input | |
when "?" | |
words.delete(guess) | |
when "l", "letters" | |
p letters | |
when "w", "words" | |
p words | |
when "q", "quit" | |
exit | |
when /[_gy]{5}/ | |
input.each_char.zip(guess.each_char).each_with_index do |(action, letter), index| | |
case action | |
when "_" | |
words.reject! { |word| word.include?(letter) } | |
letters.delete(letter) | |
when "g" | |
words.reject! { |word| word[index] != letter } | |
letters.delete(letter) | |
when "y" | |
words.reject! { |word| !word.include?(letter) || word[index] == letter } | |
end | |
end | |
end | |
end | |
puts "The word is: #{words.first}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment