Hello,
I recently finished Ruby and Ruby on rails courses and now I’m working on my personal project.
The biggest struggle for me so far was optimization of my code, because i need it to be as fast as possible
As an example, let user input be
input = "cg?"
i also have an array which contains letters of the alphabet
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
In the input “?” acts like blank tile in Scrabble - it could be any letter.
What i need from my program is to generate keys, which in this case would be
final_keys = ["2ac", "2bc", "2cc", "2ag", "2bg", "2cg", "2dg", "2eg", "2fg", "2gg", "3acg", "3bcg", "3ccg", "3cdg", "3ceg", "3cfg", "3cgg", "2c", "2g", "3cg"]
each key consists of number of letters and letters in alphabetical order. As you can see last three keys are different - this is becase in my code “2c” acts exactly as [“2cd”, “2ce”, “2cf” … ] would act. I want it as fast as possible that’s why im generating only “2c” instead of [“2cd”, “2ce”, “2cf” … ].
My code For generating these keys is here:
def choose_letters(letters, key)
letters = letters.select{ |l| l <= key.chars.last }
end
letters = input.gsub(/\s+/, "").chars.sort
keys = (2..letters.length).flat_map{ |n| letters.combination(n).map(&:join).map{|n| n = n.length.to_s + n.chars.sort.join } }.uniq
keys_with_blanks = keys.select{ |k| k.include? "?" }.map{ |k| k.gsub("?","") }
final_keys = keys_with_blanks.map do |k|
current_letters = choose_letters(all_letters, k)
k = current_letters.map{ |l| l.gsub(l,l+k) }
end.flatten.map{ |k| k.chars.sort.join }.uniq
final_keys += keys_with_blanks
This is the slowest part
final_keys = keys_with_blanks.map do |k|
current_letters = choose_letters(all_letters, k)
k = current_letters.map{ |l| l.gsub(l,l+k) }
end.flatten.map{ |k| k.chars.sort.join }.uniq
My input sometimes reaches up to 15 characters, for example input = "abcdefghijklmn?"
For this input my program needs about 3-4 seconds which is to long.
QUESTION
How can i refactor my code to make it even faster? Up to 13 characters it’s very fast. I need it to be faster for up to 15 characters.