如何使用ruby生成数字组合?

Mr.*_*ack 2 ruby math combinations

我需要使用ruby生成数字组合.例如 :

arr = [1,2,3,4,5]

约束是,组合号应包括数字5,长度最小为3或更高.(即125,521,1245等......).上述数组元素(值1至5)可以在组合数中出现一次或两次或更多次.

Den*_*rdy 6

试试这个:

arr = [1, 2, 3, 4, 5]
arr = arr * 5
out = []
3.upto(5) do |i|
  arr.combination(i) do |c|
    out << c if c.include? 5
  end
end
out = out.uniq.sort
puts out.inspect

# yields 2531 elements:
# [[1, 1, 1, 1, 5], [1, 1, 1, 2, 5], ... [2, 3, 5], ... [5, 5, 5, 5, 5]]
Run Code Online (Sandbox Code Playgroud)


tok*_*and 5

[edit]功能方法(需要Ruby 1.9):

xs = 3.upto(5).flat_map do |length|
  [1, 2, 3, 4, 5].repeated_permutation(length).select do |permutation|
    permutation.include?(5)
  end  
end
xs.size # 2531
Run Code Online (Sandbox Code Playgroud)