permutations.rb

Path: permutations.rb
Last Update: Sun Nov 06 10:21:41 Central Standard Time 2005

Permutations

Description

The Permutations class exposes an iterator that yields each of the permutations for numbers 0 .. n-1. This iterator is then used by Numeric and Array to expose permutations methods that likewise yield sequences of permutations.

The algorithm is simple:

  • if n is 1, yield the single-element Array [0]
  • otherwise yield all rotations of [permute(n - 1), n - 1]

Examples

 5.permutations { |a| puts a.join(', ') }
 %w(a b c d f).permutations { |a| puts a.join(', ') }

Required files

factorial  

[Validate]