Subtract elements from a two-dimensional array

2

I have an array

x = [[2,5,16,26],[5,28,35,46],[1,9,28,54,60,102],[...]...]

Arrays within the array do not have fixed sizes, they can contain 1 to N elements. How do I get a new array y with the subtraction of each element by its predecessor, if any. Ex:

[[3,11,10],[23,7,11],[8,19,26,6,42]

The 3 is the subtraction of 5-2, 11, 16-5 etc. And in this array y the index starting with 1.

    
asked by anonymous 23.05.2014 / 19:00

1 answer

3

You can use the each_cons . Note:

a = [1, 8, 17, 20]
a.each_cons(2) {|pair| p pair }

#=> [1, 8]
#=> [8, 17]
#=> [17, 20]

Based on this you can do the following:

x = [[2, 5, 16, 26], [5, 28, 35, 46], [1, 9, 28, 54, 60, 102]]
r = x.map{|e| e.each_cons(2).map{|pair| pair[1] - pair[0] } }

#=> [[3, 11, 10], [23, 7, 11], [8, 19, 26, 6, 42]]
    
23.05.2014 / 19:09