Skip to content

Instantly share code, notes, and snippets.

@KiGi
Created April 26, 2015 22:52
Show Gist options
  • Save KiGi/6460dee4f352d2d8ffe0 to your computer and use it in GitHub Desktop.
Save KiGi/6460dee4f352d2d8ffe0 to your computer and use it in GitHub Desktop.
The ever popular FizzBuzz, here a few passes at it in Swift in a playground with multiple implementations and looping methods (including a generator)
import Foundation
// Make constants so the strings can be easily changed.
let fizz = "Fizz"
let buzz = "Buzz"
// Put this its own function just to make different implementations shorter and clearer.
func fizzbBuzzDeterminer( candidateNum : Int, isFizz: Bool, isBuzz : Bool ) -> String
{
var toPrint :String
if isFizz && isBuzz {
toPrint = "\(fizz)\(buzz)"
} else if isFizz {
toPrint = "\(fizz)"
} else if isBuzz {
toPrint = "\(buzz)"
} else {
toPrint = "\(candidateNum)"
}
return toPrint
}
// Simplest implementation, just use mod to find multiples.
func fbIt(i:Int) -> String {
let isFizz = (i%3 == 0)
let isBuzz = (i%5 == 0 )
return fizzbBuzzDeterminer(i, isFizz, isBuzz)
}
// NOTE: The use of stride() for genrators causes an amusing bug, if you try to go past 100 in checking FizzBuzz values you stop finding multiples!
var fizzMultFunc = stride(from: 3, through: 100, by: 3).generate()
var buzzMultFunc = stride(from: 5, through: 100, by: 5).generate()
var fizzNum = fizzMultFunc.next()
var buzzNum = buzzMultFunc.next()
// This second implentation uses generators for exact multiple values, so we can just do equality check with no divison. SO MUCH CODE though. And buggy; see above.
func fbIt2(i:Int) -> String {
var isFizz = false
var isBuzz = false
if i == fizzNum {
isFizz = true
fizzNum = fizzMultFunc.next()
}
if i == buzzNum {
isBuzz = true
buzzNum = buzzMultFunc.next()
}
return fizzbBuzzDeterminer(i, isFizz, isBuzz)
}
// Simplest way to just run through the values.
for i in 1...100 {
println(fbIt(i))
}
// Getting a little fancier, create a generator so that I can choose what number to start generation from, and only do calculations for the numbers I need output for. Also I return a tuple so the output can be validated.
class FizzBuzzGen
{
var i : Int = 1
func generate() -> GeneratorOf<(Int,String)> {
return GeneratorOf<(Int,String)> {
return (self.i, fbIt(self.i++))
}
}
init( i : Int )
{
self.i = i
}
}
var fizzBuzzer = FizzBuzzGen(i:5)
var generator = fizzBuzzer.generate()
// Simple loop again, this time using the generator. Note that now the generator starts at five, so the loop will really show 5-104.. or it would if I didn't also increment the generator value between pulls!
for i in 1...100 {
if let result = generator.next() {
println("\(result)")
}
// I can affect the next value in the sequence at any time!
fizzBuzzer.i += 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment