Home > Enterprise >  Ruby permutations
Ruby permutations

Time:10-12

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.

CodePudding user response:

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

CodePudding user response:

If the goal is not to recode the combination for an educational purpose :

In the ruby standard library, the Array class has a combination method.

Here an examples :

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

letters.combination(2).to_a
#  => [["m", "o"], ["m", "r"], ["o", "r"]]

You also have a magic permutation method :


letters.permutation(3).to_a
#  => [["m", "o", "r"], ["m", "r", "o"], ["o", "m", "r"], ["o", "r", "m"], ["r", "m", "o"], ["r", "o", "m"]] 

If the goal is to recode theses methods. Maybe you can use them as validation. For exemple by counting the elements in your method and in the standard library method.

  • Related