生成一个集合的poweret,而不必在Erlang或Ruby中保持堆栈 [英] Generate a powerset of a set without keeping a stack in Erlang or Ruby

查看:141
本文介绍了生成一个集合的poweret,而不必在Erlang或Ruby中保持堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个相当大的集合(大约30-50个元素)的权力,我知道需要 2 ^ n 来存储powerset。 / p>

是否可以一次生成一个子集?



即e。通过迭代生成集合的权力,将每个生成的子集保存到磁盘/数据库,将其从堆栈/内存中删除,然后继续生成其他子集?



遗憾的是,我未能修改 Erlang Ruby 示例,以满足我的需要。

解决方案

编辑:添加枚举器(如@JörgW Mittag),如果没有封锁。

  class Array 
def powerset
return to_enum(:powerset)除非block_given?
1.upto(self.size)do | n |
self.combination(n).each {| i |收益i}
end
end
end
#demo
['a','b','c']。powerset {| item | p item}#项目一次生成
ps = [1,2,3,4] .powerset#no block,所以你会得到一个枚举器
10.times.map {ps .next}#10.没有块的时间也是一个枚举器

输出

  [a] 
[b]
[c]
[a b]
[a,c]
[b,c]
[a,b,c] $ b $ [2],[2],[3],[3] ,4]]


I would like to generate a powerset of a rather big set (about 30-50 elements) and I know that it takes 2^n to store the powerset.

Is it possible to generate one subset at a time?

I.e. generate a powerset of a set with iterations, saving each generated subset to disk/database, removing it from the stack/memory and only then continuing to generate other subsets?

Unfortunately I have failed to modify Erlang and Ruby examples to my needs.

解决方案

Edit: Added the enumerator (as @Jörg W Mittag) if no block is given.

class Array
  def powerset
    return to_enum(:powerset) unless block_given?
    1.upto(self.size) do |n|
      self.combination(n).each{|i| yield i}
    end
  end
end
# demo
['a', 'b', 'c'].powerset{|item| p item} # items are generated one at a time
ps = [1, 2, 3, 4].powerset # no block, so you'll get an enumerator 
10.times.map{ ps.next } # 10.times without a block is also an enumerator

Output

["a"]
["b"]
["c"]
["a", "b"]
["a", "c"]
["b", "c"]
["a", "b", "c"]
[[1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

这篇关于生成一个集合的poweret,而不必在Erlang或Ruby中保持堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆