Skip to content

Instantly share code, notes, and snippets.

@adamjgrant
Last active November 1, 2016 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamjgrant/a19f683357796ce72c0a1a262d88f8be to your computer and use it in GitHub Desktop.
Save adamjgrant/a19f683357796ce72c0a1a262d88f8be to your computer and use it in GitHub Desktop.
Interview Question: Cross Multiply
def cross_multiply(a, b)
shorter, longer = a.size < b.size ? [a, b] : [b, a]
shorter.cycle.take(longer.size).zip(longer).map { |n| n.reduce(:*) }
end
# Given two arrays with different, non-zero lengths, multiply each item at their same index between arrays.
# After reaching the end of the shorter array but before the end of the longer array,
# start back at the beginning of the shorter array.
# Example
#
# (algebraically)
# cross_multiply [a, b, c, d, e], [f, g]
# #=> [af, bg, cf, dg, ef]
#
# (real values)
# cross_multiply [1, 2, 3], [4, 5, 6, 7]
# #=> [4, 10, 18, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment