Class: CombinationGenerator::CombinationIndex

Inherits:
Object
  • Object
show all
Defined in:
lib/combination_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(picking_size, element_size) ⇒ CombinationIndex

Returns a new instance of CombinationIndex.



25
26
27
28
29
# File 'lib/combination_generator.rb', line 25

def initialize(picking_size, element_size)
  self.element_size = element_size
  self.size = picking_size
  self.index_ary = [1] * self.size + [0] * (element_size - self.size)
end

Instance Attribute Details

#element_sizeObject

Returns the value of attribute element_size.



23
24
25
# File 'lib/combination_generator.rb', line 23

def element_size
  @element_size
end

#index_aryObject

Returns the value of attribute index_ary.



23
24
25
# File 'lib/combination_generator.rb', line 23

def index_ary
  @index_ary
end

#sizeObject

Returns the value of attribute size.



23
24
25
# File 'lib/combination_generator.rb', line 23

def size
  @size
end

Instance Method Details

#each {|self.index_ary| ... } ⇒ Object

Yields:



31
32
33
34
35
36
# File 'lib/combination_generator.rb', line 31

def each (&block)
  yield self.index_ary
  while self.move_next      
    yield self.index_ary
  end
end

#each_with_index {|self.index_ary, i| ... } ⇒ Object

Yields:



38
39
40
41
42
43
44
45
# File 'lib/combination_generator.rb', line 38

def each_with_index (&block)
  i = 0
  yield self.index_ary, i
  while self.move_next      
    i = i + 1
    yield self.index_ary, i
  end
end

#last_1_index(num = 1) ⇒ Object

the index of last ith 1



55
56
57
58
59
60
61
62
# File 'lib/combination_generator.rb', line 55

def last_1_index(num = 1)
  count = 0
  self.index_ary.reverse.each_with_index do |e, i|
    count = count + 1 if e==1
    return (self.index_ary.size - i - 1) if count>=num
  end
  return -1
end

#move_i_next(num = 1) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/combination_generator.rb', line 64

def move_i_next(num = 1)
  index = self.last_1_index(num)
  #if already move to the last position
  return nil if index == -1 or index >= self.index_ary.size - 1
  #if the element in next position is 1
  return nil if self.index_ary[index + 1]==1
  
  self.index_ary[index] = 0
  self.index_ary[index + 1] = 1
  return true
end

#move_nextObject



47
48
49
50
51
52
# File 'lib/combination_generator.rb', line 47

def move_next
  (1..self.size).each do |i|
    return true if self.move_i_next(i)
  end
  return false
end