Subtract elements from a two-dimensional array

Asked

Viewed 179 times

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, can contain from 1 to N elements. How do I have 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]

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

  • this question is a homework or applies to a specific problem? It would be interesting to contextualize. Also, could you tell what solution you are thinking and what your difficulties.

1 answer

3


You can use the method each_cons. Observe:

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]]
  • I need to read more about array methods.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.