Efficient way to do an add on a large array

I have an array with integers +20000.

I want to create a new array in which each element in the old array will add a modifier number. In a small array of samples, it will look like this:

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

Is there a more efficient way than doing an iteration?

class Array
  def addition_by(x)
    collect { |n| n + x }
  end
end
+4
source share
4 answers

No. Niterations are the minimal complexity of this algorithm.

You can do this in place by modifying the original array with collect!(if for some reason you don't need the original array). The complexity will be the same, an additional large object will not be created.

+3
source

20 . .

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

.

inplace ( bang), .

+3

, map -? . @JörgWMittag @uishra. , speed , . @CarySwoveland .

require 'fruity'
require 'matrix'

class Array
  #jörg_w_mittag
  def new_map
    return enum_for(__callee__) unless block_given?
    inject([]) {|acc, el| acc << yield(el) }
  end

  #uishra
  def my_map(&block)
    result = []
    each do |element|
     result << block.call(element)
    end
    result
  end

  #cary_swoveland
  def vec_map(k)
    (Vector[*[k]*self.size] + Vector[*self]).to_a
  end

end

arr = (1..30000).to_a
k = 3

10.times do
  compare do
    core_map       { ar = arr.dup; ar.map     { |n| n + k } }
    jörg_w_mittag  { ar = arr.dup; ar.new_map { |n| n + k } }
    uishra         { ar = arr.dup; ar.my_map  { |n| n + k } }
    cary_swoveland { ar = arr.dup; ar.vec_map k }
  end
  puts
end

/:

#Running each test once. Test will take about 1 second.
#core_map is faster than jörg_w_mittag by 2x ± 1.0
#jörg_w_mittag is similar to uishra
#uishra is similar to cary_swoveland

#Running each test once. Test will take about 1 second.
#core_map is faster than jörg_w_mittag by 2x ± 0.1
#jörg_w_mittag is similar to uishra
#uishra is similar to cary_swoveland

#Running each test once. Test will take about 1 second.
#core_map is faster than uishra by 2x ± 1.0
#uishra is similar to jörg_w_mittag
#jörg_w_mittag is similar to cary_swoveland
+2
require 'matrix'

class Array
  def vec_map(k)
    (Vector[*[k]*self.size] + Vector[*self]).to_a
  end
end

[1,2,3].vec_map 4
  #=> [5, 6, 7]
+1

Source: https://habr.com/ru/post/1655455/


All Articles