Search code examples
arraysrubyproductcycle

How to multiply each value by each other value


I want to take each item in an array, multiply them by each other and then find the maximum of the multiples.

I tried many things until I landed upon the cycle method and then got this and am now stuck:

def adjacentElementsProduct(inputArray)
  outArray = inputArray.cycle(inputArray.length){|num| num[0] * num[1]}.to_a

  return outArray.max
end

This does not work because there is obviously no (stated) ability for Ruby to know what num[0] or num[1] are.

For instance:

adjacentElementsProduct([3, 6, -2, -5, 7, 3]) => 21 

because 3*7 is the biggest product when all numbers are multiplied.


Solution

  • You can find the two biggest values. There's no need to try each combination:

    [3, 6, -2, -5, 7, 3].max(2).inject(:*)
    #=> 42
    

    If you still want to do it with combinations, use the combination method:

    [3, 6, -2, -5, 7, 3].combination(2)
                        .map { |f, s| f * s }
                        .max
    #=> 42
    

    If you want to find the biggest one-by-other values, use each_cons:

    [3, 6, -2, -5, 7, 3].each_cons(2)
                        .map {|f, s| f * s }
                        .max
    #=> 21
    

    Also,

    max_by {|f, s| f * s }.inject(:*)
    

    could be used instead, but it's up to you.