简体   繁体   English

用于生成置换的惯用红宝石?

[英]Idiomatic ruby for generating permutations?

I'm wondering what the idiomatic version of this function for generating permutations would look like in Ruby. 我想知道该函数用于生成置换的惯用版本在Ruby中会是什么样子。 I understand that [1,2,3].permutation.to_a will generate the same result, but I'm more interested in learning Ruby and how to approach a recursive problem like this in Ruby. 我知道[1,2,3].permutation.to_a会产生相同的结果,但是我对学习Ruby以及如何在Ruby中解决递归问题更感兴趣。

def permutations(seq)
    if seq.empty? || seq.count == 1
        seq
    else
        seq.map { |x|
            permutations(seq.select { |e| e != x }).map { |p|
                if p.class == Fixnum
                    [x, p]
                else
                    p.unshift(x)
                end
            }
        }.flatten(1)
    end
end

Thanks! 谢谢!

class Array
  def permutations
    return [self] if size < 2
    perm = []
    each { |e| (self - [e]).permutations.each { |p| perm << ([e] + p) } }
    perm
  end
end 

[1, 2, 3].permutations #=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] 

Source: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/32844 来源: http//blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/32844

Edit: To avoid monkey-patching, put it into a module: 编辑:为避免猴子打补丁,请将其放入模块中:

module ArrayExtensions
  def permutations
    #snip
  end
end

Array.send :include, ArrayExtensions

It's pretty common in Ruby (esp. Rails) to add functionality like this directly to the core class. 在Ruby(尤其是Rails)中,将这样的功能直接添加到核心类中是很常见的。

One alternative to that approach would be a separate, static utility module: 一种替代方法是单独的静态实用程序模块:

module ArrayUtils
  def self.permute(array)
    return [array] if array.size < 2

    array.flat_map do |elem|
      permute(array - [elem]).map do |perm|
        ([elem] + perm)
      end
    end
  end
end

ArrayUtils.permute [1, 2, 3]
# => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM