cheenbabes
cheenbabes

Reputation: 382

Splitting an array by performing an arithmetic function in ruby

I have an array in Ruby like [3,4,5] and I want to create sub-arrays by diving or multiplying. For example, I want to multiply each number in the array by 2, 3, and 4, returning [[6,9,12],[8,12,16],[10,15,20]]

After that, what's the best way to count the total number of units? In this example, it would be 9, while array.count would return 3.

Thanks

Upvotes: 0

Views: 97

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

You might find it convenient to use matrix operations for this, particularly if it is one step among several involving matrices, vectors, and/or scalars.

Code

require 'matrix'

def doit(arr1, arr2)
   (Matrix.column_vector(arr2) * Matrix.row_vector(arr1)).to_a
end

def nbr_elements(arr1, arr2) arr1.size * arr2.size end

Examples

arr1 = [3,4,5]
arr2 = [3,4,5]

doit(arr1, arr2)
  #=> [[ 9, 12, 15],
  #    [12, 16, 20],
  #    [15, 20, 25]]

nbr_elements(arr1, arr2)
  #=> 9

doit([1,2,3], [4,5,6,7])
  #=> [[4,  8, 12],
  #    [5, 10, 15],
  #    [6, 12, 18],
  #    [7, 14, 21]]

nbr_elements([1,2,3], [4,5,6,7])
  #=> 12

Alternative

If you don't want to use matrix operations, you could do it like this:

arr2.map { |e| [e].product(arr1).map { |e,f| e*f } }

Here's an example:

arr1 = [1,2,3]
arr2 = [4,5,6,7]

arr2.map { |e| [e].product(arr1).map { |e,f| e*f } }
  #=> [[4,  8, 12],
  #    [5, 10, 15],
  #    [6, 12, 18],
  #    [7, 14, 21]]

Upvotes: 2

Daniël W. Crompton
Daniël W. Crompton

Reputation: 3518

The simplest way I could think of was:

[3,4,5].map { |v|
    [3,4,5].map { |w|
        w * v
    }
}

I'm sure there is a more elegant way.

As for the count you can use flatten to turn it into a single array containing all the elements.

[[9, 12, 15], [12, 16, 20], [15, 20, 25]].flatten
 => [9, 12, 15, 12, 16, 20, 15, 20, 25] 

Upvotes: 3

Related Questions