Created
May 21, 2012 19:12
-
-
Save jhubert/2764044 to your computer and use it in GitHub Desktop.
Array Product of Other Items in the Array
This file contains hidden or 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
# Make it a prototype method for Array | |
Array.prototype.productOthers = -> | |
# Set some default values | |
[result, total, zeroIndex] = [[], 1, null] | |
# Loop through each item in the array | |
for num, index in @ | |
# Set the default value to 0 | |
result[index] = 0 | |
# If the number is a 0, handle it | |
if num == 0 | |
# If a zero has been found before, the entire array would be filled with 0s | |
if zeroIndex != null | |
# If we haven't filled the array yet, fill it before returning | |
if result.length != @length | |
while result.length < @length | |
result.push(0) | |
return result | |
break | |
# If this is the first 0, save the index so that we can use it later | |
else | |
zeroIndex = index | |
# Otherwise, multiply the total by the number | |
else | |
total = total * num | |
# If we did find one 0, set the spot where the 0 was found to the product of all other numbers and return | |
if zeroIndex != null | |
result[zeroIndex] = total | |
return result | |
# If we didn't find a zero, set the value of each item to the product of all the others (total / item) | |
for num, index in @ | |
result[index] = total / num | |
return result | |
firstArray = [0, 1, 0, 3, 7] | |
secondArray = firstArray.productOthers() | |
console.log firstArray, secondArray |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment