如何使用惰性评估获得数组的长度 N 组合?
How can I get the length N combinations for an array using lazy evaluation?
我想我明白了排列和组合的区别:
简而言之,[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
的实现,但我遇到了困难。
"What I'm specifically trying to do is run a block for each element of the array.combination results, but I don't want to load up all the length-N combinations into memory first."
这正是您的代码所做的。您在没有块的情况下调用 combination
方法,这会导致枚举器。然后你使用它的 each
方法。一次只有一个组合在内存中。
我想我明白了排列和组合的区别:
简而言之,[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
的实现,但我遇到了困难。
"What I'm specifically trying to do is run a block for each element of the array.combination results, but I don't want to load up all the length-N combinations into memory first."
这正是您的代码所做的。您在没有块的情况下调用 combination
方法,这会导致枚举器。然后你使用它的 each
方法。一次只有一个组合在内存中。