Skip to content

Instantly share code, notes, and snippets.

@akaralar
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaralar/4f244923dc294eea9817 to your computer and use it in GitHub Desktop.
Save akaralar/4f244923dc294eea9817 to your computer and use it in GitHub Desktop.
var data1 = [1, 4, 7]
var data2 = [123, -2, 477, 3, 14, 6551]
/*
* Write a recursive function which loops over the list adding the first element
* to all remaining elements
* until there is only 1 element remaining which is then returned
*/
func doStuff(input: [Int]) -> Int {
// helper function takes an array, extracts first element and
// adds it to remaining elements, returns the resulting array
func removeFirstAndAddToOthers(elements: [Int]) -> [Int] {
var remaining = elements
let toAdd = remaining.removeAtIndex(0)
return remaining.map({ element in element + toAdd})
}
switch input.count {
case 0: return 0
case 1: return input[0] // return the last remaining element
default: return doStuff(removeFirstAndAddToOthers(input)) // count > 1, call the function again
}
}
println("The expected answer for data1 is 13" // The expected answer for data1 is 13
println("Your answer is \(doStuff(data1))") // Your answer is 13
println("Your answer for data2 is \(doStuff(data2))") // Your answer for data2 is 10431
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment