rubypermutationanagramspelling

Ruby permutations


Simply put, I want to have an input of letters, and output all possible combinations for a set length range. for example: length range 1 - 2 input a, b, c ... output a, b, c, aa, ab, ac, bb, ba, bc, cc, ca, cb

I am trying to make an anagram/spell check solver so that I can 'automate' the NYT's Spelling Bee game. So, I want to input the letters given into my program, get an array of all possible combinations for specific lengths (they have a min word length of 4) and then check that array against an array of all English words. What I have so far is:

letters = ["m","o","r"]
words = []

# Puts all the words into an array
File.open('en_words.txt') do |word|
   word.each_line.each do |line|
      words << line.strip
   end
end

class String
  def permutation(&block)
    arr = split(//)
    arr.permutation { |i| yield i.join }
  end
end

letters.join.permutation do |i|
  p "#{i}" if words.include?(i)
end

=>"mor"
=>"rom"

my issue with the above code is that it stop s at the number of letters I have given it. For example, it will not repeat to return "room" or "moor". So, what I am trying to do is get a more complete list of combinations, and then check those against my word list.

Thank you for your help.


Solution

  • How about going the other way? Checking every word to make sure it only uses the allowed letters? I tried this with the 3000 most common words and it worked plenty fast.

    words = [..]
    letters = [ "m", "o", "r" ]
    words.each do |word|
      all_letters_valid = true
      word.chars.each do |char|
        unless letters.include?(char)
          all_letters_valid = false
          break
        end
      end
      if all_letters_valid
        puts word
      end
    end
    

    If letters can repeat there isn't a finite number of permutations so that approach doesn't make sense.

    Assumption: English ascii characters only