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

时间:2011-06-28 06:50:48

标签: ruby math combinations

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

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

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

3 个答案:

答案 0 :(得分: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]]

答案 1 :(得分: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

答案 2 :(得分:0)

arr = [1,2,3,4,5]
combos = []              
for i in 3..arr.length
  combos.push(arr.repeated_combination(i).to_a)
end
combos.flatten(1).select{|c|c.include?(5)}

这里我正在创建一个临时容器变量 combos ,它将存储数组中3个或更多数字的每个组合。然后我将数组过滤为仅包含含有5的组合。