【问题标题】:How can I get the length N combinations for an array using lazy evaluation?如何使用惰性求值获得数组的长度 N 组合?
【发布时间】:2016-06-21 21:33:57
【问题描述】:

我想我理解排列和组合的区别:

简而言之,[1,20,30].permutation(3).map(&:sort).uniq[1,20,30].combination(3) 相同。

我目前有一个程序可以获取数组的所有组合:

array = [1,20,30,40,50,60]
1.upto(array.length).each do |combination_length|
  array.combination(combination_length).each do |combination|
    # ... do something here with the combination ...
  end
end

我正在尝试减少内存消耗,我认为我应该找到array.combination(combination_length).each 的替代品。

Ruby docs for Lazy Enumerators 似乎没有显示combination 方法。 Array#combination 方法的源代码是用 C 编写的,所以我真的没有能力去修改它。

我特别想做的是为array.combination 结果的每个元素运行一个块,但我想先将所有长度-N 组合加载到内存中.

我四处寻找我能理解的combination 的实现,但我遇到了困难。

【问题讨论】:

    标签: ruby lazy-evaluation


    【解决方案1】:

    “我特别想做的是为 array.combination 结果的每个元素运行一个块,但我不想先将所有长度-N 组合加载到内存中。”

    这正是您的代码正在做的事情。您正在调用没有块的combination 方法,这会产生一个枚举器。然后你使用它的each方法。一次只有一个组合在内存中。

    【讨论】:

    • 所以惰性求值是 Enumerator 对象的默认值?
    • 一个非常 ehh.. 懒惰的程序员可以只生成一个数组并使用它的 each 方法,完全忽略了拥有枚举器的意义;但总的来说是的,枚举器是懒惰的。
    猜你喜欢
    • 2015-03-14
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多