array-transpose.rb

Makoto Kishimoto, 08/02/2011 05:28 PM

Download (821 Bytes)

 
1
class Array
2
  alias orig_transpose transpose
3

    
4
  def transpose *args
5
    orig_transpose *args
6
  rescue IndexError => ie
7
    if is_monotone_noninc? then
8
      that = self.class.new
9
      self[0].each_with_index {|elem, i|
10
        that[i] = [elem]
11
      }
12
      idx = 1
13
      while idx < self.size do
14
        self[idx].each_with_index {|elem, i|
15
          that[i] << self[idx][i]
16
        }
17
        idx += 1
18
      end
19
      return that
20
    else
21
      raise ie
22
    end
23
  end
24

    
25
  private
26

    
27
  # check monotone nonincreasing
28
  def is_monotone_noninc?
29
    siz = self[0].size
30
    i = 1
31
    while i < self.size
32
      s = self[i].size
33
      if s > siz then
34
        return false
35
      end
36
      siz = s
37
      i += 1
38
    end
39
    return true
40
  end
41
end
42

    
43
print "[[1, 2, 3], [4, 5], [6]].transpose\n=> "
44
p [[1, 2, 3], [4, 5], [6]].transpose