Skip to content

Instantly share code, notes, and snippets.

@agilous
Last active November 5, 2022 06:22
Show Gist options
  • Save agilous/3488d03f298cef55289bc899e79e18a3 to your computer and use it in GitHub Desktop.
Save agilous/3488d03f298cef55289bc899e79e18a3 to your computer and use it in GitHub Desktop.
NYT Spelling Bee solver in Ruby

Spelling Bee

NYT Spelling Bee solver written in Ruby. It should work fine on any BSD/Linux/Unix system with Ruby installed.

Running the code

In a terminal:

git clone git@gist.github.com:3488d03f298cef55289bc899e79e18a3.git spelling_bee
cd spelling_bee
irb -r ./spelling_bee.rb

In the irb session:

game = SpellingBee.new(must_contain: 'h', may_contain: 'acilot')
game.pangrams # ["catholic"]
game.words    # ["achoo", "alcohol", "alcoholic", "aloha", "altho", ...]

Dictionary

If your operating system does not have a dictionary file located at '/usr/share/dict/words' this code will exit without producing a result. You can specify a custom dictionary file location by passing it in as a string:

# If your OS has a dictionary file located at: /opt/share/words
game = SpellingBee.new(dictionary: '/opt/share/words', must_contain: 'h', may_contain: 'acilot')
class SpellingBee
def initialize(dictionary: '/usr/share/dict/words', must_contain:, may_contain:)
@dictionary = dictionary
@must_contain = must_contain
@may_contain = may_contain
end
def pangrams
@pangrams ||= words.filter { |word| may_contain.chars.filter { |c| word.match(/#{c}/) }.count == may_contain.chars.count }
end
def words
@words ||= dictionary_words
.filter { |word| /(?=.*#{must_contain})/.match(word) }
.reject { |word| /(?=.*[#{must_not_contain}])/.match(word) }
end
private
attr_reader :dictionary, :may_contain, :must_contain
def dictionary_words
@dictionary_words = IO.readlines(dictionary, chomp: true).reject { |word| word.length < 4 }
rescue Errno::ENOENT
puts "Cannot find dictionary at: #{dictionary}"
exit!
end
def must_not_contain
('\'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.chars - may_contain.chars - [must_contain]).join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment