Class: MoreMath::Subset

Inherits:
Object show all
Includes:
Enumerable, RankingCommon
Defined in:
lib/more_math/subset.rb

Instance Attribute Summary

Attributes included from RankingCommon

#collection, #last, #rank, #size

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RankingCommon

#each, #each!, #next, #next!, #pred, #pred!, #random, #random!

Constructor Details

#initialize(size, rank = 0) ⇒ Subset

Returns a Subset instance for a collection of size size with the rank rank.



10
11
12
13
# File 'lib/more_math/subset.rb', line 10

def initialize(size, rank = 0)
  @size, self.rank = size, rank
  @last = (1 << size) - 1
end

Class Method Details

.for(collection, rank = 0) ⇒ Object

Returns the subset of the collection collection for the rank rank.



16
17
18
19
20
# File 'lib/more_math/subset.rb', line 16

def self.for(collection, rank = 0)
  subset = new(collection.size, rank)
  subset.instance_variable_set(:@collection, collection)
  subset
end

.power_set(collection) ⇒ Object

Returns the power set of the collection collection.



23
24
25
# File 'lib/more_math/subset.rb', line 23

def self.power_set(collection)
  self.for(collection).map(&:value)
end

Instance Method Details

#rank=(m) ⇒ Object

Assigns m to the rank attribute of this object.



28
29
30
# File 'lib/more_math/subset.rb', line 28

def rank=(m)
  @rank = m % (1 << size)
end

#valueObject

Returns the subset for rank #rank and #collection. (If no collection was set it applies to the array [ 0, 1, …, size - 1 ] instead.)



34
35
36
37
38
39
40
41
42
# File 'lib/more_math/subset.rb', line 34

def value
  result = []
  c = @collection || (0...size).to_a
  r = @rank
  0.upto(size) do |i|
    r[i] == 1 and result << c[i]
  end
  result
end