Print all permutations of the top of the bottom line string

I am trying to print the entire permutation with an updated version of the bottom line string in Ruby. For example:

source string: aaa,

:

aaa
aaÃ
aAa
aaÃ
Aaa
AaA
aaÃ
AAA

Any help or tips are appreciated.

+4
source share
3 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

The main idea is that the output of the lines of the line n( 2**n == 1<<n) should be 2, where n=str.length. Therefore, you can use the index ifrom 0 to 2**n-1as a bit field for which letters will be inserted. For instance.

000 -> aaa
001 -> aaA
010 -> aAa
011 -> aAA
etc.
+3
source

repeated_permutation, , :

%w(a A).repeated_permutation(3).map(&:join)
# => ["aaa", "aaA", "aAa", "aAA", "Aaa", "AaA", "AAa", "AAA"]

, , , :

str = 'abcde'
chars = str.chars

[false, true].repeated_permutation(str.length).map do |permutation|
  chars.zip(permutation).map do |char, upcase|
    upcase ? char.upcase : char
  end.join
end

# => ["abcde", "abcdE", "abcDe", "abcDE", "abCde", "abCdE", "abCDe", "abCDE", 
#     "aBcde", "aBcdE", "aBcDe", "aBcDE", "aBCde", "aBCdE", "aBCDe", "aBCDE",
#     "Abcde", "AbcdE", "AbcDe", "AbcDE", "AbCde", "AbCdE", "AbCDe", "AbCDE",
#     "ABcde", "ABcdE", "ABcDe", "ABcDE", "ABCde", "ABCdE", "ABCDe", "ABCDE"]
+3

I prefer the @Uri solution for a specific case, but suggest this for arbitrary strings of lowercase letters:

str = "abad"

arr = str.chars.map { |c| [c,c.upcase] }
arr.shift.product(*arr).map(&:join)
  #=> ["abad", "abaD", "abAd", "abAD", "aBad", "aBaD", "aBAd", "aBAD",
  #    "Abad", "AbaD", "AbAd", "AbAD", "ABad", "ABaD", "ABAd", "ABAD"]
+3
source

Source: https://habr.com/ru/post/1546184/


All Articles