Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vike27/5dc1ea0064257c252b2c to your computer and use it in GitHub Desktop.
Save vike27/5dc1ea0064257c252b2c to your computer and use it in GitHub Desktop.
You have an array of integers, and for each index you want to find the product of every integer except the integer at that index.
You have an array of integers, and for each index you want to find the product of every integer except the integer at that index.
Write a function get_products_of_all_ints_except_at_index() that takes an array of integers and returns an array of the products.
For example, given:
[1, 7, 3, 4]
your function would return:
[84, 12, 28, 21]
by calculating:
[7*3*4, 1*3*4, 1*7*4, 1*7*3]
Do not use division in your solution.
#solution
def get_products_of_all_ints_except_at_index(arr)
final_arr = []
i = 0
total = 1
while i < arr.length do
x = arr.slice(i)
arr.each do |int|
if int != x
total = total * int
end
end
final_arr << total
i += 1
total = 1
end
final_arr
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment