GIVEN AN ARRAY OF NUMBERS, REPLACE EACH NUMBER WITH THE PRODUCT OF ALL THE NUMBER IN THE ARRAY EXCEPT ITSELF WITHOUT DIVISION | CODING | RUBY | PROGRAMMING | INTERVIEW

By: Saurav

2018-04-08 23:36:00 UTC

This problem is similar to finding the sum of all elements of the array except the element itself and replacing it with the element.
The concept was sum all elements on the left, sum all elements on right and then add the two.

For this problem, we will use similar two arrays left and right where left stores product of elements on the left of that index and right will have the products of all elements on the right of that index. Finally, we will replace each element of the original array with the product of whats on the right and what's on the left.

let's see it in code:

def product_of_remaining(input)
  return input if input.length < 1 
  
  #product = input.inject(:*)
  
  left_arr = [1]
  right_arr = [1]
  
  (1..input.length-1).each do |i|
    left_arr << left_arr[-1]*input[i-1]
  end
  
  #left_arr << 1 
  
  (input.length-1).downto(1).each do |i|
    right_arr << right_arr[-1]*input[i]
  end 
  
  #right_arr << 1 
  
  right_arr.reverse!
  
  
  (0..input.length-1).each do |i|
    #p product/input[i]
    input[i] = left_arr[i]*right_arr[i]
    
  end 
  
  
  
  return input

  
  
end

product_of_remaining([3,7,9,2,6,4]) == [3024, 1296, 1008, 4536, 1512, 2268]

All our tests pass. All our functions do one and only one thing.

And so we are done for now :)


Let me know what you think!
twitter: sprakash24oct
linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)