Module: Partitions::IntegerPartitions

Included in:
Integer
Defined in:
lib/partitions/integer_partitions.rb

Instance Method Summary collapse

Instance Method Details

#partitionsObject

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/partitions/integer_partitions.rb', line 3

def partitions
  n = self
  raise ArgumentError, "n should be greater than or equal to 0" if n < 0

  if n.zero?
    if block_given?
      yield []
    else
      p []
    end
    return
  end

  a = Array.new(n + 1, 0)
  k = 2
  a[1] = 0
  a[2] = n

  while k != 1 do
    y = a[k] - 1
    k -= 1
    x = a[k] + 1

    while x <= y do
      a[k] = x
      y -= x
      k += 1
    end

    a[k] = x + y

    if block_given?
      yield a.values_at(1..k)
    else
      p a.values_at(1..k)
    end
  end
end