Module: Partitions::IntegerPartitions
- Included in:
- Integer
- Defined in:
- lib/partitions/integer_partitions.rb
Instance Method Summary collapse
Instance Method Details
#partitions ⇒ Object
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 |
# File 'lib/partitions/integer_partitions.rb', line 4 def partitions n = self if n < 0 raise ArgumentError, "n should be greater than or equal to 0" end a = Array.new(n + 1, 0) k = 2 a[1] = 0 a[2] = n while k != 1 do y = a[k] - 1 k = k - 1 x = a[k] + 1 while x <= y do a[k] = x y = y - x k = 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 |