Does anyone know of a function that multiplies the contents of an array.
For example:
one = [1,2,3]
two = [[2],[3],[4]]
output = [[2],[6],[12]]
I've written a simple function that does this, however I'm sure there is
a better way, instead of casting the item to a float.
def multiplyArray(arr1,arr2)
newArr = []
i=0
arr1.each do |x|
x = x.to_s.to_f
item = arr2[i].to_s.to_f
ele = x * item
newArr.push(ele)
i = i + 1
end
puts newArr
end
if you are doing lots of this then check out narray:
harp:~ > cat a.rb
require 'narray'
a = NArray.to_na [1,2,3]
b = NArray.to_na [2,3,4]
p( a * b )
harp:~ > ruby a.rb
NArray.int(3):
[ 2, 6, 12 ]
regards.
-a
···
On Wed, 24 Jan 2007, WKC CCC wrote:
HI,
Does anyone know of a function that multiplies the contents of an array.
For example:
one = [1,2,3]
two = [[2],[3],[4]]
output = [[2],[6],[12]]
I've written a simple function that does this, however I'm sure there is
a better way, instead of casting the item to a float.
def multiplyArray(arr1,arr2)
newArr =
i=0
arr1.each do |x|
x = x.to_s.to_f
item = arr2[i].to_s.to_f
ele = x * item
newArr.push(ele)
i = i + 1
end
puts newArr
end
Thanks,
--
we can deny everything, except that we have the possibility of being better.
simply reflect on that.
- the dalai lama
Does anyone know of a function that multiplies the contents of an array.
For example:
one = [1,2,3]
two = [[2],[3],[4]]
output = [[2],[6],[12]]
I've written a simple function that does this, however I'm sure there is
a better way, instead of casting the item to a float.
def multiplyArray(arr1,arr2)
newArr =
i=0
arr1.each do |x|
x = x.to_s.to_f
item = arr2[i].to_s.to_f
ele = x * item
newArr.push(ele)
i = i + 1
end
puts newArr
end
module Enumerable
def product
inject(1) { |prod, piece| prod*piece }
end
def sum
inject(0) { |total, piece| total+piece }
end
end
True, except the block parameters were reversed. In these cases, the
final result wasn't affected because the operations are commutative.
Man, I swear that every time I use #inject I get it backwards, and
think that I've fixed the answer in my mind for the next time. Thanks
for the correction. (Anyone got a good _why-like mnemonic they use for
remembering the order?)
I also added the argument to the inject within product for symmetry.
You could equally remove the 0 argument from the sum method's use of
inject.
I thought about that, but in my mind, the sum of an empty array is
zero, but the product of an empty array is nil (or 0?), not 1. Of
course, totally up the the OP as to how s/he wants to handle this edge
case.