Class: Sbn::Combination

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/sbn/combination.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods included from Enumerable

#average, #sample_variance, #standard_deviation, #sum

Constructor Details

#initialize(arr) ⇒ Combination

Returns a new instance of Combination.



23
24
25
26
# File 'lib/sbn/combination.rb', line 23

def initialize(arr)
  @arr = arr
  @current = Array.new(arr.size, 0)
end

Instance Method Details

#<=>(other) ⇒ Object



34
35
36
# File 'lib/sbn/combination.rb', line 34

def <=>(other)
  @current <=> other.current
end

#currentObject



46
47
48
49
50
# File 'lib/sbn/combination.rb', line 46

def current
  returnval = []
  @current.size.times {|i| returnval[i] = @arr[i][@current[i]] }
  returnval
end

#each {|current| ... } ⇒ Object

Yields:



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

def each
  iterations = @arr.inject(1) {|product, element| product * element.size } - 1
  yield current
  iterations.times { yield self.next_combination }
end

#firstObject



38
39
40
# File 'lib/sbn/combination.rb', line 38

def first
  @current.fill 0
end

#lastObject



42
43
44
# File 'lib/sbn/combination.rb', line 42

def last
  @current.size.times {|i| @current[i] = @arr[i].size - 1 }
end

#next_combinationObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sbn/combination.rb', line 52

def next_combination
  i = @current.size - 1
  @current.reverse.each do |e|
    if e == @arr[i].size - 1
      @current[i] = 0
    else
      @current[i] += 1
      break
    end
    i -= 1
  end
  current
end

#prev_combinationObject



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sbn/combination.rb', line 66

def prev_combination
  i = @current.size - 1
  @current.reverse.each do |e|
    if e == 0
      @current[i] = @arr[i].size - 1
    else
      @current[i] -= 1
      break
    end
    i -= 1
  end
  current
end