So a few days ago I came across this video on Digg discussing a programming question sometimes used in interviews, code the game FizzBuzz.  I've never had to do this since I've applied for a programming job, but I liked the idea of trying to figure out how many ways I could code FizzBuzz in Swift.  To make this a bit more fun I gave myself an hour to try and come up with the most convoluted and the simplest solutions I could.

The Rules

  1. Print the numbers 1 through 100, one number to a line
  2. If the number is divisible by 3, print "Fizz" instead
  3. If the number is divisible by 5, print "Buzz" instead
  4. If the number is divisible by both 3 and 5, print "FizzBuzz" instead

The Loop

So the first part of this game is a simple loop and there were really only two options available a for and a while loop.  They would look something like this.

var counter : Int = 1
let counterLimit : Int = 100

//While Loop Option
while counter <= counterLimit {
    //Do Something
    counter += 1
}

//For Loop Option
for i in 1...counterLimit {
    //Do Something
}

Running The Tests

The rest of the program just requires that we test the number to see if it is divisible by 3, 5 or both.  The sequence of our tests matters because doing things backwards would require more tests to cover the same scenarios.

//Requires fewer tests
for i in 1...100 {
    if i % 3 == 0 && i % 5 == 0 { print ("Fizz Buzz") }
    else if i % 3 == 0 { print ("Fizz") }
    else if i % 5 == 0 { print ("Buzz") }
    else { print ("\(i)") }
} 

//Requires more tests
for i in 1...100 {
    if i % 3 == 0 && i % 5 != 0 { print ("Fizz") }
    else if i % 5 == 0 && i % 3 != 0 { print ("Buzz") }
    else if i % 3 == 0 && i % 5 == 0 { print ("Fizz Buzz") }
    else { print ("\(i)") }
}

Simple

The simplest solution I could think of was the same as what was presented in the video, although you could get "fancy" using an array to capture the results instead of just printing them out.  But that may not be as efficient from a resources perspective.

for i : Int in 1...100 {

    var output : String = ""

    if i % 3 == 0 { output += "Fizz" }
    if i % 5 == 0 { output += "Buzz" }
    if output == "" { output = String(i) }

    print ("\(output)")

}

Convoluted

My complicated answer just does a lot of work that can be simplified through the use of the modular (%) operator.  There are clearly better ways of doing this.

//Function to determine remainder equals 0 (true)
func remainder (number : Int, divideBy : Int) -> Bool {
    let result = number % divideBy
    if result == 0 {
        return true
    } else {
        return false
    }
}

//Loop
for i in 1...100 {

    if remainder(number: i, divideBy: 3) && remainder(number: i, divideBy: 5) {
        print ("Fizz Buzz")
    } else if remainder(number: i, divideBy: 3) {
        print ("Fizz")
    } else if remainder(number: i, divideBy: 5) {
        print ("Buzz")
    } else {
        print ("\(i)")
    }
}
Posted
AuthorLee B Wilson