Class: Partitions::SetPartitions

Inherits:
Object
  • Object
show all
Defined in:
lib/partitions/set_partitions.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n, p = nil) ⇒ SetPartitions

Returns a new instance of SetPartitions.



5
6
7
8
9
10
11
# File 'lib/partitions/set_partitions.rb', line 5

def initialize(n, p=nil)
  @n = n
  @k = Array.new(n, 0)
  @m = Array.new(n, 0)
  @p = p
  @size = 0
end

Instance Attribute Details

#kObject

Returns the value of attribute k.



3
4
5
# File 'lib/partitions/set_partitions.rb', line 3

def k
  @k
end

#mObject

Returns the value of attribute m.



3
4
5
# File 'lib/partitions/set_partitions.rb', line 3

def m
  @m
end

#nObject

Returns the value of attribute n.



3
4
5
# File 'lib/partitions/set_partitions.rb', line 3

def n
  @n
end

#sizeObject

Returns the value of attribute size.



3
4
5
# File 'lib/partitions/set_partitions.rb', line 3

def size
  @size
end

Instance Method Details

#countObject



64
65
66
67
68
69
70
# File 'lib/partitions/set_partitions.rb', line 64

def count
  sum = 0
  (1..n).each do |k|
    sum += sterling_second(@n, k)
  end
  return sum
end

#each_partition {|@k| ... } ⇒ Object

Yields:

  • (@k)


52
53
54
55
56
57
58
59
60
61
62
# File 'lib/partitions/set_partitions.rb', line 52

def each_partition
  unless block_given?
    raise ArgumentError, "Missing block"
  end
  reinitialize
  yield @k
  (count - 1).times do
    yield next_partition
  end
  reinitialize
end

#next_partitionObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/partitions/set_partitions.rb', line 13

def next_partition
  (@n - 1).downto(1) do |i|
    if @k[i] <= @m[i - 1]
      @k[i] = @k[i] + 1
      @m[i] = max(@m[i], @k[i])
      j = i + 1
      while j <= (n - 1) do
        @k[j] = @k[0]
        @m[j] = @m[i]
        j = j + 1
      end
      @size = partition_size
      return @k
    end
  end

  @size = nil
  return
end

#previous_partitionObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/partitions/set_partitions.rb', line 33

def previous_partition
  (@n - 1).downto(1) do |i|
    if @k[i] > @k[0]
      @k[i] = @k[i] - 1
      @m[i] = @m[i - 1]
      j = i + 1
      while j <= n - 1 do
        @k[j] = @m[j] = @m[i] + j - i;
        j = j + 1
      end
      @size = partition_size
      return @k
    end
  end

  @size = nil
  return
end