Permalink
Browse files

Changed Combinatorics::PowerSet::Mixin to use Choose::Mixin.

  • Loading branch information...
1 parent add8237 commit 2725e1758cc5873ed892eaa7c7038f7b62d66cb7 @postmodern committed Oct 15, 2011
Showing with 15 additions and 17 deletions.
  1. +7 −14 lib/combinatorics/power_set/mixin.rb
  2. +8 −3 spec/power_set/mixin_examples.rb
@@ -1,6 +1,10 @@
+require 'combinatorics/choose'
+
module Combinatorics
module PowerSet
module Mixin
+ include Choose::Mixin
+
#
# Calculates the power-set of an Enumerable object.
#
@@ -27,21 +31,10 @@ module Mixin
#
# @see http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
#
- def powerset
- inject([self.class.new]) do |power_set, element|
- sub_set = []
-
- power_set.each do |previous_set|
- new_set = previous_set + [element]
-
- yield new_set if block_given?
-
- sub_set << previous_set
- sub_set << new_set
- end
+ def powerset(&block)
+ return enum_for(:powerset) unless block
- sub_set.enum_for
- end
+ 0.upto(length) { |n| self.choose(n,&block) }
end
alias power_set powerset
@@ -3,22 +3,27 @@
require 'combinatorics/power_set'
shared_examples_for "PowerSet::Mixin" do
+ let(:empty_set) { Set[] }
+
it "the powerset of an empty Set should only contain the empty Set" do
set = subject[]
- set.powerset.to_a.should == [set]
+ set.powerset.to_a.should == [empty_set]
end
it "the powerset of a single Set should contain that Set" do
set = subject[1]
- set.powerset.to_a.should == [subject[], set]
+ set.powerset.to_a.should == [empty_set, Set[*set]]
end
it "the powerset of a Set should all be subsets" do
set = subject[1, 2, 3]
+ superset = Set[]
+
+ set.powerset { |subset| superset += subset }
- set.powerset.each { |subset| (set & subset).should == subset }
+ superset.should == Set[*set]
end
it "should alias powerset to power_set" do

0 comments on commit 2725e17

Please sign in to comment.