【问题标题】:How can i generate the combinations of numbers using ruby?如何使用 ruby​​ 生成数字组合?
【发布时间】:2011-06-28 06:50:47
【问题描述】:

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

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

约束是,组合数必须包含数字5,并且长度至少为3或以上。 (即 125、521、1245 等)。上述数组元素(值 1 至 5)在组合数中可能出现一次或两次或更多次。

【问题讨论】:

  • 是的,我在上面提到过。我有一个数组( arr = [1,2,3,4,5] )。所以,我需要生成数字的组合,如(125、325、1245...等。这是我的预期输出)。但是,数字 5 应该包含在组合号中。
  • 在我发表评论后,我明白你的意思,所以我删除了它。有趣的问题。我想知道你需要这个做什么。我想知道是否有人也想出了一个优雅的答案。
  • :-) 不错!!谢谢米莎。如果您喜欢这个问题,请为我投票。
  • 考虑提高您的英语水平,以便更有效地向人们传达您的想法。我不太明白这句话:“值(1..5)可能会在结果中再出现一次。”
  • 这是谁干的(投反对票)?。我可以知道原因吗?。

标签: ruby math combinations


【解决方案1】:

试试这个:

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

【讨论】:

  • 优秀且深思熟虑的答案。这里有一些建议。代替 arr = arr * 5,尝试 arr *= 5 代替 out = out.uniq.sort 尝试 out.uniq!sort!
【解决方案2】:

[编辑] 函数式方法(需要 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

【讨论】:

  • 这不允许数字在结果数组中出现多次。
  • @Mladen:是的,好吧,我回答后问题变了。已更新。
【解决方案3】:
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 的组合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 2012-04-26
    • 1970-01-01
    • 2013-03-25
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多