Thursday, 15 July 2010

ruby - All possible variants of a string with capital and lowercase letters -



ruby - All possible variants of a string with capital and lowercase letters -

this asked me in coding quesiton, , gave kind of ugly, though working solution. love see master's beautiful solution question.

given string includes letters , numbers i.e. "abcd1_k", homecoming array of every variant string capitalization of letters changed, i.e., "abcd1_k", "abcd1_k"....

a more simple problem case 'abcd1_k' 'ab', should homecoming ->

['ab', 'ab', 'ab' 'ab']

it seems me beautiful solution still have expensive time complexity definition. (at worst, 2 combinations each character, mean 2^n growth). if true, there must beautiful way in ruby.

how this:

def case_permutations(string) string .each_char .reduce(['']) |acc, char_string| acc.flat_map |prefix| [char_string.upcase, char_string.downcase] .uniq .map |modified_char| "#{prefix}#{modified_char}" end end end end

you're not going improve (2^n)*n time complexity because homecoming value have 2^n items of length n in worst case.

ruby

No comments:

Post a Comment