From f2f7b8dd7fd15d2ba959e022736a56cc45a1cca4 Mon Sep 17 00:00:00 2001 From: gogotanaka Date: Tue, 27 Jan 2015 09:46:51 -0800 Subject: [PATCH 1/1] Implement Set#powerset To: https://bugs.ruby-lang.org/ --- NEWS | 4 ++++ lib/set.rb | 16 ++++++++++++++++ test/test_set.rb | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/NEWS b/NEWS index 13185d1..c38d696 100644 --- a/NEWS +++ b/NEWS @@ -30,6 +30,10 @@ with all sufficient information, see the ChangeLog file. === Stdlib updates (outstanding ones only) +* lib/set.rb + * New methods: + * Set#powerset returns set of all subsets of +self+. + === Stdlib compatibility issues (excluding feature bug fixes) * lib/webrick/utils.rb diff --git a/lib/set.rb b/lib/set.rb index d1ea6d8..dec44c8 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -513,6 +513,22 @@ class Set end end + # Returns set of all subsets of +self+. + # + # e.g.: + # + # require 'set' + # set = Set[1, 2].powerset + # p set # => #, + # # #, + # # #, + # # #}> + def powerset + (0 .. 2 ** length - 1).map { |n| + select.with_index { |_, i| (n >> i) & 1 == 1 }.to_set + }.to_set + end + InspectKey = :__inspect_key__ # :nodoc: # Returns a string containing a human-readable representation of the diff --git a/test/test_set.rb b/test/test_set.rb index 961578b..a4522aa 100644 --- a/test/test_set.rb +++ b/test/test_set.rb @@ -570,6 +570,14 @@ class TC_Set < Test::Unit::TestCase } end + def test_powerset + assert_equal(Set[1, 2].powerset, Set[Set[], Set[1], Set[2], Set[1, 2]]) + assert_equal( + Set[1, 2, 3].powerset, + Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[3, 1], Set[1, 2, 3]] + ) + end + def test_taintness orig = set = Set[1,2,3] assert_equal false, set.tainted? -- gogotanaka