Created
November 15, 2018 16:30
-
-
Save bhakes/92c07677cd154952097f48b5d656aec4 to your computer and use it in GitHub Desktop.
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
// assumptions: | |
// - I will get passed an array of ints | |
// - ints can be positive, negative or zero | |
// - If only one item in the array is passed early return 0 | |
import UIKit | |
// main function | |
func getProduct(for intArray: [Int])->[Int]{ | |
// early return [0] if only one int in the input array | |
guard !(intArray.count == 1) else {return [0]} | |
// instantiate vars | |
var sumArray: [Int] = [] | |
var inputArray = intArray | |
var sum: Int = 1 | |
var tempStorage: Int | |
// loop through each value in the input array | |
// remove it from the array | |
// do some calculations | |
// then put it back in | |
for index in 0..<intArray.count{ | |
// store the value at the current index for later then remove it | |
tempStorage = inputArray[index] | |
inputArray.remove(at: index) | |
for remainingItem in inputArray { | |
sum *= remainingItem | |
} | |
// add the sum to the sumArray that will be returned | |
sumArray.append(sum) | |
// reset sum & return to input array back to its original state | |
sum = 1 | |
inputArray.insert(tempStorage, at: index) | |
} | |
return sumArray | |
} | |
var testCases = [[1], [0], [1,2], [1,4,5,6], [1,9,6,5,2], [1,9,0,5,2], [1,-9,6,-5,-2], [0,-9,6,-5,-0]] | |
for test in testCases{ | |
print(getProduct(for:test)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment