Skip to content

Instantly share code, notes, and snippets.

@acegreen
Last active July 11, 2018 19:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acegreen/1a9a63f27729278b0fa5 to your computer and use it in GitHub Desktop.
Save acegreen/1a9a63f27729278b0fa5 to your computer and use it in GitHub Desktop.
Interview Question 1
/* QUESTION:
In an unsorted array of negative and positive integers, write a function, hasSumOf3Ints(array, n), that returns true if you find three numbers in the array that add up to a passed number, "n".
(ie. array of [3,10,2,-3,100,4,0,-103], and n=14, 10, 4, and 0 is found and thus it would return true)
*/
// Error enum created at the end to properly throw errors including a function message() to directly display the error in the catch
enum Errors: ErrorType {
case EmptyArray
case Unknown
func message() -> String {
switch self {
case .EmptyArray:
return "Array seems to be empty"
case .Unknown:
return "Unknown error"
}
}
}
let array = [3,10,2,-3,100,4,0,-103]
// To simplify things we started with a sum of 2
func hasSumOf2Ints(array: [Int], n: Int) -> Bool {
guard array.count != 0 else { return false }
for (index, element) in array.enumerate() {
var array2 = array
array2.removeAtIndex(index)
for secondElement in array2 {
let sum = element + secondElement
if sum == n {
return true
}
}
}
return false
}
print(hasSumOf2Ints(array, n: 16))
// Used the above to do a more complex sum of 3
func hasSumOf3Ints(array: [Int], n: Int) throws -> Bool {
guard array.count != 0 else { throw Errors.EmptyArray }
let sortedArray = array.sort()
for (index, element) in sortedArray.enumerate() {
print("index", index)
print("element", element)
var first = index + 1
var last = sortedArray.count - 1
while first < last {
let sum = element + sortedArray[first] + sortedArray[last]
print("sum", sum)
print("first", first)
print("last", last)
if sum == n {
return true
}
if sum > n {
last -= 1
} else if sum < n {
first += 1
}
}
}
return false
}
do {
print(try hasSumOf3Ints(arrayUnsorted, n: 16))
} catch {
if let error = error as? Errors {
print(error.message())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment