Last active
November 1, 2016 20:44
-
-
Save adamjgrant/a19f683357796ce72c0a1a262d88f8be to your computer and use it in GitHub Desktop.
Interview Question: Cross Multiply
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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