import Foundation
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
println("Time elapsed for \(title): \(timeElapsed) s")
}
func squaresSummed(first: Int, second: Int) -> Int {
return (first + (second * second))
}
func solution6() {
let firstHundredInts = [Int](1 ... 100)
let summed = firstHundredInts.reduce(0) { $0 + $1 }
let summedSquared = summed * summed
let squaredSummed = firstHundredInts.reduce(0, combine: squaresSummed)
let answer = summedSquared - squaredSummed
println(String(answer))
}
printTimeElapsedWhenRunningCode("Sum square difference", solution6)
Some of the built in Swift stuff made this quite nice. The syntax for declaring an array which is a simple list of integers is very convenient. It runs faster than iterating through a loop to set all the values, types faster and reads better than typing all the values out by hand.
I quite like the reduce
function on Swift arrays.
What could make this more Swift...-onic? What needs improvement?
println
s etc. in the methods that solve the problem. I don't want to include them in my time measurements. \$\endgroup\$wift
in Sonic. \$\endgroup\$