Skip to content

Instantly share code, notes, and snippets.

@dillon-mce
Last active November 7, 2018 17:47
Show Gist options
  • Save dillon-mce/5a72855079d1ed80320d585a5cb95a48 to your computer and use it in GitHub Desktop.
Save dillon-mce/5a72855079d1ed80320d585a5cb95a48 to your computer and use it in GitHub Desktop.
/*
Thoughts:
- Only have to deal with positive numbers
- Don't have to deal with zero
- Return first solution
Test cases:
sumAndProduct(6, 9) // [3, 3]
sumAndProduct(5, 4) // [1, 4]
sumAndProduct(7, 12) // [3, 4]
sumAndProduct(15, 36) // [3, 12]
sumAndProduct(3, 11) // should fail - []
Approach:
- Cycle through the numbers that can possibly add up to the sum and check to see if they also equal the product.
*/
//Simple solution. Cycles through all possibilities. Kind of inelegant/inefficient. O(n^2)
func sumAndProduct(_ sum: UInt, _ product: UInt) -> [UInt] {
var timesThroughLoop = 0
defer { print("Times through loop: \(timesThroughLoop)") }
// Check to make sure some joker didn't put zero.
guard sum != 0, product != 0 else { return [] }
// Cycle through all the numbers from 1 up to the sum
for num in 1 ..< sum {
// And again
for otherNum in num ..< sum {
timesThroughLoop += 1
if num + otherNum == sum && num * otherNum == product {
// If the two numbers add up to the sum AND multiply to the product
// return them
return [num, otherNum]
}
}
}
// Otherwise, return an empty array
return []
}
sumAndProduct(6, 9) // [3, 3]
sumAndProduct(5, 4) // [1, 4]
sumAndProduct(7, 12) // [3, 4]
sumAndProduct(15, 36) // [3, 12]
sumAndProduct(3, 11) // []
/*
// Better solution. O(n)
func sumAndProduct(_ sum: UInt, _ product: UInt) -> [UInt] {
var timesThroughLoop = 0
defer { print("Times through loop: \(timesThroughLoop)") }
// Make sure some joker didn't put zero
guard sum != 0, product != 0 else { return [] }
// Only need to cycle through half of the sum because after that the values repeat.
for value1 in 1 ... (sum / 2) {
// Don't need to cycle through the second value, because there is only one value that leads to the sum we're looking for.
let value2 = sum - value1
timesThroughLoop += 1
// If the two values lead to the product, return them
if value1 * value2 == product {
return [value1, value2]
}
}
// Otherwise return an empty array.
return []
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment