Project

General

Profile

Feature #5145 ยป array-transpose.rb

metanest (Makoto Kishimoto), 08/02/2011 05:28 PM

 
class Array
alias orig_transpose transpose

def transpose *args
orig_transpose *args
rescue IndexError => ie
if is_monotone_noninc? then
that = self.class.new
self[0].each_with_index {|elem, i|
that[i] = [elem]
}
idx = 1
while idx < self.size do
self[idx].each_with_index {|elem, i|
that[i] << self[idx][i]
}
idx += 1
end
return that
else
raise ie
end
end

private

# check monotone nonincreasing
def is_monotone_noninc?
siz = self[0].size
i = 1
while i < self.size
s = self[i].size
if s > siz then
return false
end
siz = s
i += 1
end
return true
end
end

print "[[1, 2, 3], [4, 5], [6]].transpose\n=> "
p [[1, 2, 3], [4, 5], [6]].transpose
    (1-1/1)