Class: CartesianIterator

Inherits:
Object
  • Object
show all
Includes:
Enumerable, GridSearch
Defined in:
lib/cartesian_iterator.rb,
lib/cartesian/grid_search.rb

Instance Method Summary collapse

Methods included from GridSearch

#argmax, #argmin

Constructor Details

#initialize(foo, bar) ⇒ CartesianIterator

Returns a new instance of CartesianIterator.



9
10
11
12
13
14
# File 'lib/cartesian_iterator.rb', line 9

def initialize(foo, bar)
  @lists = []
  @tot_iter = 1
  product!(foo)
  product!(bar)
end

Instance Method Details

#dupObject



16
17
18
# File 'lib/cartesian_iterator.rb', line 16

def dup
  Marshal.load(Marshal.dump(self))
end

#eachObject



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
# File 'lib/cartesian_iterator.rb', line 54

def each
  return false if @tot_iter < 1

  elems = []
  for list in @lists
    elems << list.restart_and_raw_next
  end
  if RUBY_VERSION <= '1.9.1'; yield(*elems.map {|x| x }); else; yield(*elems); end # Yeah, v.map{|x|x} should be equal to v, but strangely it is NOT in Ruby versions prior to 1.9.2.

  last_list_index = @lists.size-1
  n = last_list_index
  loop do
    if !@lists[n].done?
      elems[n] = @lists[n].raw_next
      if RUBY_VERSION <= '1.9.1'; yield(*elems.map {|x| x }); else; yield(*elems); end # See previous comment.
      n = last_list_index
      next
    elsif n > 0
      elems[n] = @lists[n].restart_and_raw_next
      n -= 1
    else
      return true
    end
  end
end

#equal(other) ⇒ Object Also known as: ==



20
21
22
23
24
25
# File 'lib/cartesian_iterator.rb', line 20

def equal(other)
  self.instance_variables.each do |var_name|
    return false if self.instance_variable_get(var_name) != other.instance_variable_get(var_name)
  end
  true
end

#left_product(other) ⇒ Object



49
50
51
52
# File 'lib/cartesian_iterator.rb', line 49

def left_product(other)
  (result = self.dup).left_product!(other)
  result
end

#left_product!(other) ⇒ Object



36
37
38
39
40
# File 'lib/cartesian_iterator.rb', line 36

def left_product!(other)
  @lists.unshift Array(other).dup
  @tot_iter *= @lists[-1].size
  self
end

#product(other) ⇒ Object Also known as: right_product, x



42
43
44
45
# File 'lib/cartesian_iterator.rb', line 42

def product(other)
  (result = self.dup).product!(other)
  result
end

#product!(other) ⇒ Object Also known as: right_product!, x!



28
29
30
31
32
# File 'lib/cartesian_iterator.rb', line 28

def product!(other)
  @lists << Array(other).dup
  @tot_iter *= @lists[-1].size
  self
end