Generate list of all possible permutations of a string

后端 未结 30 2855
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  不知归路
    2020-11-22 15:35

    I just whipped this up quick in Ruby:

    def perms(x, y, possible_characters)
      all = [""]
      current_array = all.clone
      1.upto(y) { |iteration|
        next_array = []
        current_array.each { |string|
          possible_characters.each { |c|
            value = string + c
            next_array.insert next_array.length, value
            all.insert all.length, value
          }
        }
        current_array = next_array
      }
      all.delete_if { |string| string.length < x }
    end
    

    You might look into language API for built in permutation type functions, and you might be able to write more optimized code, but if the numbers are all that high, I'm not sure there is much of a way around having a lot of results.

    Anyways, the idea behind the code is start with string of length 0, then keep track of all the strings of length Z where Z is the current size in the iteration. Then, go through each string and append each character onto each string. Finally at the end, remove any that were below the x threshold and return the result.

    I didn't test it with potentially meaningless input (null character list, weird values of x and y, etc).

提交回复
热议问题