Skip to main content
2 of 4
added 280 characters in body
codez
  • 969
  • 1
  • 9
  • 29

Project Euler, Challenge #17 in Swift

Problem:

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

Result: Result: 21124 found in 0.0172510147094727 seconds (Correct according to Project Euler).

Since this hasn't been solved in Swift, I'd like a code review of this challenge which talks about the efficiency of the code, and how to optimise efficient, bad practices or violations of any concepts. Here is the code:

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 EulerSeventeen() -> 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("Result: \(result) found in \(timeInterval) seconds")
codez
  • 969
  • 1
  • 9
  • 29