Fellow Stranger Fellow Stranger - 7 months ago 39
Ruby Question

Efficient way to do addition on big array

I have an array with +20000 integer elements.

I want to create a new array where each element in the old array is added a modifying number. On a small sample array it would look like this:

old_array = [2,5,6,8]
modifying_number = 3
new_array = [5,8,9,11]

Is there any more efficient way than doing an iteration like this?

class Array
def addition_by(x)
collect { |n| n + x }


No. N iterations are the minimal complexity of this algorithm.

You can do it in place by modifying source array with collect!(if you for some reasons not need a source array). Complexity will be the same, additional big object will not created.