开发者

How can i generate the combinations of numbers using ruby?

I need to generate the combinations of numbers using ruby. For Example :

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

开发者_运维知识库

The constraint is, the combination number should include the number 5 and the length is minimum 3 or above. (i.e 125, 521, 1245 etc.. ). The above array elements (values 1 to 5) may occur one or two or more times in the combination number.


Try this:

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]]


[edit] Functional approach (requires 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


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)}

Here I'm creating a temporary container variable combos that will store every combination of 3 or more numbers in the array. I'm then filtering the array to only include combinations containing 5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜