Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all permutations of the upcased of a lower cased string

Tags:

algorithm

ruby

I am trying to print out all of the upcased version permutation of a lower cased string in Ruby. For ex:

original string: aaa,

output is:

aaa
aaA
aAa
aAA
Aaa
AaA
AAa
AAA

Any help or hints is greatly appreciated.

like image 937
user2712937 Avatar asked Jan 10 '23 08:01

user2712937


1 Answers

str = 'aaa'

(0...1<<str.length).map { |i|
    str.chars.map.with_index { |a,b| ((i>>b)&1).zero? ? a : a.upcase }.join
}

# => aaa Aaa aAa AAa aaA AaA aAA AAA

Basic idea is that there are going to be 2 to the power of n (2**n == 1<<n) output strings, where n=str.length. Therefore you can use an index i from 0 to 2**n-1 as a bitfield for which letters are going to be upcased. E.g.

000 -> aaa
001 -> aaA
010 -> aAa
011 -> aAA
etc.
like image 145
Matt Avatar answered Jan 19 '23 10:01

Matt