Project

General

Profile

Feature #10726 ยป implement_set_powerset.patch

gogotanaka (Kazuki Tanaka), 01/27/2015 05:48 PM

View differences:

NEWS
30 30

  
31 31
=== Stdlib updates (outstanding ones only)
32 32

  
33
* lib/set.rb
34
  * New methods:
35
    * Set#powerset returns set of all subsets of +self+.
36

  
33 37
=== Stdlib compatibility issues (excluding feature bug fixes)
34 38

  
35 39
* lib/webrick/utils.rb
lib/set.rb
513 513
    end
514 514
  end
515 515

  
516
  # Returns set of all subsets of +self+.
517
  #
518
  # e.g.:
519
  #
520
  #   require 'set'
521
  #   set = Set[1, 2].powerset
522
  #   p set     # => #<Set: {#<Set: {}>,
523
  #             #            #<Set: {1}>,
524
  #             #            #<Set: {2}>,
525
  #             #            #<Set: {1, 2}>}>
526
  def powerset
527
    (0 .. 2 ** length - 1).map { |n|
528
      select.with_index { |_, i| (n >> i) & 1 == 1 }.to_set
529
    }.to_set
530
  end
531

  
516 532
  InspectKey = :__inspect_key__         # :nodoc:
517 533

  
518 534
  # Returns a string containing a human-readable representation of the
test/test_set.rb
570 570
    }
571 571
  end
572 572

  
573
  def test_powerset
574
    assert_equal(Set[1, 2].powerset, Set[Set[], Set[1], Set[2], Set[1, 2]])
575
    assert_equal(
576
      Set[1, 2, 3].powerset,
577
      Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[3, 1], Set[1, 2, 3]]
578
    )
579
  end
580

  
573 581
  def test_taintness
574 582
    orig = set = Set[1,2,3]
575 583
    assert_equal false, set.tainted?
576
-