Amazon Affiliate

Monday 11 April 2016

Calculate the product of maximum pair in an array in ruby.

class MaxPairwiseProduct
  def initialize
    array_elements = []
    puts "Enter the size of array :"
    array_size = gets.chomp.to_i
    for i in 0..array_size - 1
      puts "Enter the element of array"
      array_elements << gets.chomp.to_i
    end
    puts "Maximum Product is : #{getNaiveMaxProduct array_size, array_elements}"
    puts "Maximum Product is : #{getOptimisedMaxProduct array_size, array_elements}"
  end

# This is the native solution to find the product of maximum pair wise in an array.

  def getNaiveMaxProduct array_size, array_elements
    result = 0
    for i in 0..array_size - 1
      j = i+1
      for j in j..array_size - 1
        if array_elements[i] * array_elements[j] > result
          result = array_elements[i] * array_elements[j]
        end
      end
    end
    return result
  end

# This is the comparitively optimised solution than previous solution to find the product of maximum pair wise in an array.

  def getOptimisedMaxProduct array_size, array_elements
    max_index1 = -1
    max_index2 = -1
    for i in 0..array_size-1
      if array_elements[i] > array_elements[max_index1]
        max_index1 = i
      end
    end
    for j in 0..array_size - 1
      if (array_elements[j] != array_elements[max_index1]) && (array_elements[j] > array_elements[max_index2])
        max_index2 = j
      end
    end
    result = array_elements[max_index1] * array_elements[max_index2]
    return result
  end
end

max_product = MaxPairwiseProduct.new

No comments:

Post a Comment