From d24e95ae02dd2eed13501181cb3d69b350973959 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 19 Dec 2020 20:18:06 -0800 Subject: [PATCH] Add brute force solution --- .../get_products_of_all_other_elements.rb | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 data_structures/arrays/get_products_of_all_other_elements.rb diff --git a/data_structures/arrays/get_products_of_all_other_elements.rb b/data_structures/arrays/get_products_of_all_other_elements.rb new file mode 100644 index 0000000..8bfe4a6 --- /dev/null +++ b/data_structures/arrays/get_products_of_all_other_elements.rb @@ -0,0 +1,23 @@ +# Arrays - Get Products of all other elements in Ruby + +# Algorithm challenge description: +# Given an array of integers, return a new array such that +# each element at index `i` of the new array is the product of +# all the numbers in the original array except the one at `i`. + +# 1. Brute force solution +def calculate_products_of_all_other_elements(nums) + products_other_elements = Array.new(nums.length, 1) + + nums.each_with_index do |num1, i| + nums.each_with_index do |num2, j| + if (i != j) + products_other_elements[i] = products_other_elements[i] * num2 + end + end + end + + products_other_elements +end + +puts(calculate_products_of_all_other_elements([1, 2, 3]))