Module: Spruz::Minimize

Defined in:
lib/spruz/minimize.rb

Overview

This module can be mixed into all classes, whose instances respond to the [] and size-methods, like for example Array. The returned elements from [] should respond to the succ method.

Instance Method Summary collapse

Instance Method Details

#minimize ⇒ Object

Returns a minimized version of this object, that is successive elements are substituted with ranges a..b. In the situation ..., x, y,... and y != x.succ a range x..x is created, to make it easier to iterate over all the ranges in one run. A small example: [ 'A', 'B', 'C', 'G', 'K', 'L', 'M' ].minimize # => [ 'A'..'C', 'G'..'G', 'K'..'M' ]

If the order of the original elements doesn't matter, it's a good idea to first sort them and then minimize: [ 5, 1, 4, 2 ].sort.minimize # => [ 1..2, 4..5 ]



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/spruz/minimize.rb', line 15

def minimize
  result = []
  last_index = size - 1
  size.times do |i|
    result << [ self[0] ] if i == 0
    if self[i].succ != self[i + 1] or i == last_index
      result[-1] << self[i]
      result << [ self[i + 1] ] unless i == last_index
    end
  end
  result.map! { |a, b| a..b }
end

#minimize! ⇒ Object

First minimizes this object, then calls the replace method with the result.



30
31
32
# File 'lib/spruz/minimize.rb', line 30

def minimize!
  replace minimize
end

#unminimize ⇒ Object

Invert a minimized version of an object. Some small examples: [ 'A'..'C', 'G'..'G', 'K'..'M' ].unminimize # => [ 'A', 'B', 'C', 'G', 'K', 'L', 'M' ] and [ 1..2, 4..5 ].unminimize # => [ 1, 2, 4, 5 ]



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

def unminimize
  result = []
  for range in self
    for e in range
      result << e
    end
  end
  result
end

#unminimize! ⇒ Object

Invert a minimized version of this object in place.



49
50
51
# File 'lib/spruz/minimize.rb', line 49

def unminimize!
  replace unminimize
end