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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With