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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With