Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to do addition on big array

Tags:

ruby

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 }
  end
end
like image 489
Fellow Stranger Avatar asked Jan 06 '23 08:01

Fellow Stranger


2 Answers

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.

like image 107
Ilya Avatar answered Jan 07 '23 21:01

Ilya


20k records is not much to worry about performance.

ary = Array.new(20000) { 1 } 
ary.map! { |el| el + 1 }

would work totally fine.

I would just suggest to modify the initial array inplace instead of creating a new one (using method with bang), so it will definitely use less resources.

like image 39
Andrey Deineko Avatar answered Jan 07 '23 22:01

Andrey Deineko