<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: powerset code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 18 May 2008 10:59:18 GMT</pubDate>
    <description>DZone Snippets: powerset code</description>
    <item>
      <title>Ruby Hash Power-Set</title>
      <link>http://snippets.dzone.com/posts/show/4895</link>
      <description>// adds a #power_set method to Hash class&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# The Array power set is stolen from http://snippets.dzone.com/posts/show/3524&lt;br /&gt;class Array&lt;br /&gt;  # Returns the "power set" for this Array. This means that an array with all&lt;br /&gt;  # subsets of the array's elements will be returned.&lt;br /&gt;  def power_set&lt;br /&gt;    # the power set line is stolen from http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/&lt;br /&gt;    inject([[]]){|c,y|r=[];c.each{|i|r&lt;&lt;i;r&lt;&lt;i+[y]};r}&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class Hash&lt;br /&gt;  def power_set&lt;br /&gt;    # Returns the "power set" for this Hash. This means that a array with hashes of all&lt;br /&gt;    # subsets of the hash's (key =&gt; value) pairs will be returned.&lt;br /&gt;    # Example:&lt;br /&gt;    # &gt;&gt; {:feedback_type=&gt;"", :language_code=&gt;"", :comment=&gt;""}.power_set&lt;br /&gt;    #&lt;br /&gt;    # [{}, {:comment=&gt;""}, {:language_code=&gt;""}, {:language_code=&gt;"", :comment=&gt;""}, {:feedback_type=&gt;""}, {:feedback_type=&gt;"", :comment=&gt;""}, {:feedback_type=&gt;"", :language_code=&gt;""}, {:feedback_type=&gt;"", :language_code=&gt;"", :comment=&gt;""}]&lt;br /&gt;    &lt;br /&gt;    hash_to_array = self.to_a&lt;br /&gt;    array_power_set = hash_to_array.power_set&lt;br /&gt;    hash_power_set = array_power_set.collect { |pairs| pairs.inject({}) { |hash,pair| hash[pair[0]] = pair[1]; hash } }&lt;br /&gt;    hash_power_set&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 13 Dec 2007 12:14:16 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4895</guid>
      <author>helder (Helder Ribeiro)</author>
    </item>
  </channel>
</rss>
