Ruby get permutations of all lengths from a string in order

前端 未结 2 876
小蘑菇
小蘑菇 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:07

    Array#repeated_permutation can do the heavy lifting for you here:

    $arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
    def scan
      characters = $arr.chars
    
      (1..6).each do |length|
        characters.repeated_permutation(length) do |sequence|
          t = sequence.join
          puts t
        end
      end
    end
    

    Or as a more reusable enumerator:

    CHARACTERS = [*"A".."Z", *"a".."z", *"0".."9", "_", "-"]
    def each_permuted_string(max_length = 6, &block)
      sequences = (1..max_length).map { |n| CHARACTERS.repeated_permutation(n) }
    
      if block_given?
        sequences.each { |seq| seq.lazy.map(&:join).each(&block) }
      else
        enum_for(__method__, max_length) { sequences.map(&:size).inject(:+) }
      end
    end
    
    each_permuted_string do |t|
      puts t
    end
    

    It's going to take a very long time, though -- there are each_permuted_string.size => 69810262080 values. This sounds like it could be an XY Problem, and you might get a better solution by asking a question about the higher-level problem you're solving.

提交回复
热议问题