Class: Array

Inherits:
Object
  • Object
show all
Includes:
Combinatorics::CartesianProduct::Mixin, Combinatorics::Choose::Mixin, Combinatorics::Derange::Mixin, Combinatorics::Permute::Mixin, Combinatorics::PowerSet::Mixin
Defined in:
lib/combinatorics/list_comprehension.rb,
lib/combinatorics/choose/extensions/array.rb,
lib/combinatorics/derange/extensions/array.rb,
lib/combinatorics/permute/extensions/array.rb,
lib/combinatorics/power_set/extensions/array.rb,
lib/combinatorics/cartesian_product/extensions/array.rb

Instance Method Summary collapse

Methods included from Combinatorics::CartesianProduct::Mixin

#cartesian_product

Methods included from Combinatorics::PowerSet::Mixin

#powerset

Methods included from Combinatorics::Permute::Mixin

#permute

Methods included from Combinatorics::Derange::Mixin

#derange

Methods included from Combinatorics::Choose::Mixin

#choose

Instance Method Details

#comprehension {|list| ... } ⇒ Enumerator

Iterates over each permutation of the enumerable values within the Array.

Examples:

[(1..5),(1..4),(1..3)].comprehension.to_a
# => [
  [1, 1, 1], [1, 1, 2], [1, 1, 3],
  [1, 2, 1], [1, 2, 2], [1, 2, 3],
  [1, 3, 1], [1, 3, 2], [1, 3, 3],
  [1, 4, 1], [1, 4, 2], [1, 4, 3],
  [2, 1, 1], [2, 1, 2], [2, 1, 3],
  [2, 2, 1], [2, 2, 2], [2, 2, 3],
  [2, 3, 1], [2, 3, 2], [2, 3, 3],
  [2, 4, 1], [2, 4, 2], [2, 4, 3],
  [3, 1, 1], [3, 1, 2], [3, 1, 3],
  [3, 2, 1], [3, 2, 2], [3, 2, 3],
  [3, 3, 1], [3, 3, 2], [3, 3, 3],
  [3, 4, 1], [3, 4, 2], [3, 4, 3],
  [4, 1, 1], [4, 1, 2], [4, 1, 3],
  [4, 2, 1], [4, 2, 2], [4, 2, 3],
  [4, 3, 1], [4, 3, 2], [4, 3, 3],
  [4, 4, 1], [4, 4, 2], [4, 4, 3],
  [5, 1, 1], [5, 1, 2], [5, 1, 3],
  [5, 2, 1], [5, 2, 2], [5, 2, 3],
  [5, 3, 1], [5, 3, 2], [5, 3, 3],
  [5, 4, 1], [5, 4, 2], [5, 4, 3]
]

Yields:

  • (list)

    The given block will be passed each permutation of the enumerable values in the Array.

Yield Parameters:

  • list (Array)

    A permutation of the enumerable values within the Array.

Returns:

  • (Enumerator)

    If no block is given, an enumerator object will be returned.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/combinatorics/list_comprehension.rb', line 46

def comprehension
  return enum_for(:comprehension) unless block_given?

  if empty?
    yield self
    return nil
  end

  enums = self.map do |value|
    case value
    when Combinatorics::Enumerator
      value
    when Enumerable
      value.enum_for
    else
      [value].enum_for
    end
  end

  iteration = enums.map { |e| e.next }

  loop do
    yield iteration.dup

    (enums.length - 1).downto(0) do |index|
      begin
        iteration[index] = enums[index].next
        break
      rescue StopIteration
        enums[index].rewind
        iteration[index] = enums[index].next
      end

      return nil if index == 0
    end
  end
end