Ruby get permutations of all lengths from a string in order

前端 未结 2 896
小蘑菇
小蘑菇 2021-01-26 17:47

Here\'s my code-

$arr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-\"
def scan(f)
    begin
        if f.size == 6
              exit
             


        
2条回答
  •  天命终不由人
    2021-01-26 18:11

    Since you're expecting A, AA, AAA, etc... to be included in the resulted list, then you might find the repeated_permutations method to be useful, because you need permutations with repetitions.

    Unfortunately, the number of permutations is extremely large ($arr contains 64 symbols) and permutations with up to 6 chars must be calculated. The number of permutations is:

    64^7 = 4_398_046_511_104
    

    But still, here's an example of calculating permutations of up to 6 chars:

    (1..6).to_a.flat_map { |i| $arr.chars.repeated_permutation(i).map(&:join) }
    

    Which is even for 4 is quite slow, but it's up to you.

提交回复
热议问题