Module: Combinatorics::Derange::Mixin

Included in:
Array
Defined in:
lib/combinatorics/derange/mixin.rb

Overview

Author:

Since:

  • 0.4.0

Instance Method Summary collapse

Instance Method Details

#derange {|derangement| ... } ⇒ Enumerator

Calculate all derangements for an Enumerable object.

Examples:

Produce the derangements of a three-element Array

[1, 2, 3].derange.to_a
# => [[2, 3, 1], [3, 1, 2]]

Yields:

  • (derangement)

    If a block is given, it will be passed an Array representing an individual derangement from the full calculation.

Yield Parameters:

  • derangement (Array)

    One of the calculated derangements.

Returns:

  • (Enumerator)

    If no block is given, an Enumerator of all derangements will be returned.

See Also:

Since:

  • 0.4.0



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/combinatorics/derange/mixin.rb', line 32

def derange
  return enum_for(:derange) unless block_given?

  if size <= 1
    yield []
  else
    elements = self.to_a

    elements.permutation do |x|
      unless elements.each_with_index.any? { |e,i| e == x[i] }
        yield x
      end
    end
  end
end