Skip to content

Instantly share code, notes, and snippets.

@joalbertg
Created June 7, 2022 17:19
Show Gist options
  • Save joalbertg/cc7b6d0935b602c07f34f6dedd846382 to your computer and use it in GitHub Desktop.
Save joalbertg/cc7b6d0935b602c07f34f6dedd846382 to your computer and use it in GitHub Desktop.
challenge: product without current index
[]: []
[6]: [1]
[2, 4]: [4, 2]
[1, 1, 1, 1, 1]: [1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]: [16, 16, 16, 16, 16]
[0, 1, 2, 3, 4]: [24, 0, 0, 0, 0]
[0, 1, 2, 0, 4]: [0, 0, 0, 0, 0]
[1, 2, 3, 4, 2]: [48, 24, 16, 12, 24]
# frozen_string_literal: true
# Quickstart
# ruby product_without_current_index.rb
# in: [1, 2, 3, 4, 2]
# out: { 1 => 1, 2 => 2, 3 => 1, 4 => 1 }
def index_array_by_element(arr)
arr.each_with_object({}) do |number, acc|
acc[number] ? acc[number] += 1 : acc[number] = 1
end
end
def product_without_current_index(arr)
hash = index_array_by_element(arr)
base_case = base_cases(arr, hash)
return base_case if base_case
has_zero = !hash.delete(0).nil?
hash.delete(1)
product = calculate_product(hash)
generate_output(arr, has_zero, product)
end
def base_cases(arr, hash)
size = hash.keys.size
return [] if size.zero?
return [1] if size == 1 && hash.values.sum == 1
return [0] * arr.size if hash[0] && hash[0] > 1
end
def calculate_product(hash)
hash.inject(1) do |acc, (key, count)|
acc * key**count
end
end
def generate_output(arr, has_zero, product)
arr.map do |element|
result = product if element.zero?
result = 0 if !element.zero? && has_zero
result || product / element
end
end
examples = [
[], # => []
[6], # => [1]
[2, 4], # => [4, 2]
[1, 1, 1, 1, 1], # => [1, 1, 1, 1, 1]
[2, 2, 2, 2, 2], # => [16, 16, 16, 16, 16]
[0, 1, 2, 3, 4], # => [24, 0, 0, 0, 0]
[0, 1, 2, 0, 4], # => [0, 0, 0, 0, 0]
[1, 2, 3, 4, 2] # => [48, 24, 16, 12, 24]
]
examples.each do |arr|
puts "#{arr}: #{product_without_current_index(arr)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment