Skip to content

Instantly share code, notes, and snippets.

@jhubert
Created May 21, 2012 19:12
Show Gist options
  • Save jhubert/2764044 to your computer and use it in GitHub Desktop.
Save jhubert/2764044 to your computer and use it in GitHub Desktop.
Array Product of Other Items in the Array
# 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