Skip to content

Instantly share code, notes, and snippets.

@proxpero
Last active October 5, 2015 12:44
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 proxpero/284ea35f9729e45474c4 to your computer and use it in GitHub Desktop.
Save proxpero/284ea35f9729e45474c4 to your computer and use it in GitHub Desktop.
Solution to problem 1 from "5 Programming Problems, 1 Hour"
//: Problem 1
// "Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion."
// https://www.shiftedup.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
// Xcode 7.0, Swift 2.0
let series = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
let realSum = series.reduce(0, combine: +)
// for-loop
var forLoopSum = 0
for n in series {
forLoopSum += n
}
assert(forLoopSum == realSum)
// while-loop
var whileLoopSum = 0
var i = 0
while i < series.count {
whileLoopSum += series[i]
i++
}
assert(whileLoopSum == realSum)
// recursion
func sum(var series: [Int]) -> Int {
guard series.count > 0 else { return 0 }
return series.removeFirst() + sum(series)
}
assert(sum(series) == realSum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment