Class Permutations
In: permutations.rb
Parent: Object

Methods

each   new   permute  

Public Class methods

[Source]

# File permutations.rb, line 25
        def initialize(n)
                @n = n
        end

Public Instance methods

yield a sequence of all the permutations of numbers 0 .. n-1. returns nil

[Source]

# File permutations.rb, line 30
        def each
                return nil if @n <= 0
                ret = @n.factorial
                return ret if not block_given?
                permute(@n) {|a| yield a}
                ret
        end

Private Instance methods

yield a sequence of all the permuations of numbers 0 .. n-1. The algorithm is:

  • if n == 1 just yield the singe-element array [0]
  • otherwise, yield all rotations of (permute(n - 1) + (n - 1))

returns nil.

[Source]

# File permutations.rb, line 45
        def permute(n)
                if n == 1
                        yield [0]
                        return
                end
                permute(n - 1) do |a|
                        b = a.clone << (n - 1)
                        n.times { |i| yield b.rotate! }
                end
        end

[Validate]