user6820969
user6820969

Reputation:

Add corresponding elements in two arrays of different length

I have two arrays:

a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]

I want to add to the elements of b the corresponding elements of a. When the elements of a runs out, I want to cycle through a to supply the elements. The result should be:

c = [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

How could I go about this?

Upvotes: 1

Views: 389

Answers (4)

Sagar Pandya
Sagar Pandya

Reputation: 9497

a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]

enum = a.cycle
b.map { |e| e + enum.next }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

Upvotes: 4

Stefan
Stefan

Reputation: 114188

Another one, using map, with_index and modulo:

b.map.with_index { |e, i| e + a[i % a.size] }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

Upvotes: 0

Mark
Mark

Reputation: 6455

EDIT: Only works in rails

def add_arrays(array_a, array_b)
  results = []
  array_b.in_groups_of(4).each do |group|
    group.each_with_index do |record, j|
      results << (record + array_a[j])
    end
  end
  results
end

Not tested it but that should do the trick

Upvotes: -1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

b.zip(a * (b.size / a.size + 1)).map { |o| o.reduce(:+) }
#⇒ [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

Or, much better and more concise from @SimpleLime:

b.zip(a.cycle).map(&:sum)

Upvotes: 4

Related Questions