How to combination/permutation in ruby?

后端 未结 3 1066
清歌不尽
清歌不尽 2021-01-18 19:46

I\'ve this familiar question that looks like permutation/combination of the Math world.

How can I achieve the following via ruby?

badges = \"1-2-3\"
         


        
相关标签:
3条回答
  • 2021-01-18 20:01

    Functional approach:

    bs = "1-2-3".split("-")
    strings = 1.upto(bs.size).flat_map do |n| 
      bs.permutation(n).map { |vs| vs.join("-") } 
    end
    #=> ["1", "2", "3", "1-2", "1-3", "2-1", "2-3", "3-1", "3-2", "1-2-3", "1-3-2", "2-1-3", "2-3-1", "3-1-2", "3-2-1"]
    
    0 讨论(0)
  • 2021-01-18 20:12

    Array#permutation(n) will give you all the permutations of length n as an Array of Arrays so you can call this with each length between 1 and the number of digits in badges. The final step is to map these all back into strings delimited with -.

    badges = "1-2-3"
    
    badges_split = badges.split('-')
    
    permutations = []
    
    (1..badges_split.size).each do |n|
        permutations += badges_split.permutation(n).to_a
    end
    
    result = permutations.map { |permutation| permutation.join('-') }
    

    Update: I think Alex's use of reduce is a more elegant approach but I'll leave this answer here for now in case it is useful.

    0 讨论(0)
  • 2021-01-18 20:13

    You ned to use Array#permutation method in order to get all permutations:

    arr = "1-2-3".split '-' # => ["1", "2", "3"]
    res = (1..arr.length).reduce([]) { |res, length|
      res += arr.permutation(length).to_a
    }.map {|arr| arr.join('-')}
    
    puts res.inspect
    # => ["1", "2", "3", "1-2", "1-3", "2-1", "2-3", "3-1", "3-2", "1-2-3", "1-3-2", "2-1-3", "2-3-1", "3-1-2", "3-2-1"]
    

    Let me explain the code:

    1. You split string into array passing separator '-' to String#split method

    2. You need all permutations of length 1, 2, 3. Range 1..arr.length represents all these lengths.

    3. You collect an array of all permutations using Enumerable#reduce. You will get array of arrays here:

      [["1"], ["2"], ["3"], ["1", "2"], ["1", "3"], ["2", "1"], ["2", "3"], ["3", "1"], ["3", "2"], ["1", "2", "3"], ["1", "3", "2"], ["2", "1", "3"], ["2", "3", "1"], ["3", "1", "2"], ["3", "2", "1"]]
      
    4. You transform all subarrays of this array into strings using Array#join with your '-' separator inside of Enumerable#map

    0 讨论(0)
提交回复
热议问题