wfmonster
wfmonster

Reputation: 31

How can I multiply a number in an array by its position in the array and then add up the sum of the array in ruby?

How can I multiply a number in an array by its position in the array and then add up the sum of the array in ruby? I don't understand how to access the index of the array within the map function

For example: how can i get [5, 7, 13, 2] to go to [5*0, 7*1, 13*2, 2*3] then get the sum of this array.

ie

def array_method (numbers)
   numbers.map{|i| i* ?????}
end
array_method([5, 7, 13, 2])

this isn't working either its returning an empty array and I don't know what i am doing wrong.

Upvotes: 2

Views: 2292

Answers (5)

codeLizt
codeLizt

Reputation: 21

def array_method (numbers)
   ans = 0
   numbers.each_with_index {| num, idx | ans += (idx) * num }
end

Upvotes: 1

sawa
sawa

Reputation: 168101

 [5,7,13,2].map.with_index(&:*).inject(:+)
 # => 39

Upvotes: 4

tihom
tihom

Reputation: 8003

Use inject

def dot_product_with_index(array)
  (0..array.count-1).inject(0) {|r,i| r + array[i]*i}
end

Upvotes: 0

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

You can monkey patch the Array class if you want the method to be available to all arrays:

class Array
  def sum_with_index
    self.map.with_index { |element, index| element * index }.inject(:+)
  end
end

Console output

2.0.0-p247 :001 > [5, 7, 13, 2].sum_with_index
 => 39

Upvotes: 4

Idan Arye
Idan Arye

Reputation: 12603

[5,7,13,2].each_with_index.map{|value,index|value*index}.reduce{|a,b|a+b}

Upvotes: 2

Related Questions