SolutionResult: Result: 21124 found in 0.0172510147094727 seconds (Correct according to Project Euler).
import Foundation
let unitNames:[String] = [
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
]
let tensNames:[String] = [
"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred"
]
func convertIntegerToWords(number:Int) -> String {
var words:String = ""
if number >= 0 && number <= 19 {
words = words + unitNames[number]
} else if number >= 20 && number <= 99 {
var digits = number.array
words = words + tensNames[digits[0]]
words = words + unitNames[digits[1]]
} else if number >= 100 && number <= 999 {
var digits = number.array
if number % 100 == 0 {
words = words + unitNames[digits[0]] + "hundred";
} else {
words = words + unitNames[digits[0]] + "hundredand";
var newNumber = number - digits[0] * 100;
words = words + convertIntegerToWords(newNumber)
}
} else if number == 1000 {
words = words + "onethousand"
}
return words
}
extension Int {
var array: [Int] {
return Array(description).map{String($0).toInt() ?? 0}
}
}
func eulerSeventeenEulerSeventeen() -> Int {
var length:Int = 0
for iterator in 1...1000 {
length = length + count(convertIntegerToWords(iterator))
}
let end = NSDate();
return length
}
let start = NSDate();
var result = EulerSeventeen()
let end = NSDate();
let timeInterval: Double = end.timeIntervalSinceDate(start);
println(eulerSeventeen"Result: \(result) found in \(timeInterval) seconds")