Created
November 26, 2022 07:37
-
-
Save tmasjc/9ef68deb1e95316988705918078e7a82 to your computer and use it in GitHub Desktop.
Fizz Buzz demo in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// if x is a multiple of 3 then output "fizz", | |
// if x is a multiple of 5 then output "buzz" | |
// if x is a multiple of 15 then output "fizz buzz" | |
// basic | |
func fizz_buzz_alpha(max: Int) -> () { | |
for number in 1...max { | |
if number % 15 == 0 { | |
print("fizz buzz") | |
} else if number % 3 == 0 { | |
print("fizz") | |
} else if number % 5 == 0 { | |
print("buzz") | |
} else { | |
print(String(number)) | |
} | |
} | |
} | |
// a better way | |
func fizz_buzz_beta(max: Int) -> () { | |
for number in 1...max { | |
var output: String = "" | |
if number % 3 == 0 { output += "fizz" } | |
if number % 5 == 0 { output += "buzz" } | |
if output == "" { output = String(number) } | |
print(output) | |
} | |
} | |
// an even better way | |
func fizz_buzz_gamma(max: Int) -> () { | |
for number in 1...max { | |
// declare pairings here | |
var dict = [ | |
3: "Fizz", | |
5: "Buzz" | |
] | |
var output: String = "" | |
for (k, v) in dict { | |
if number % k == 0 { output += v } | |
} | |
if output == "" { output = String(number) } | |
print(output) | |
} | |
} | |
// using Closures to detach dictionary | |
func make_fizz_buzz(kvs: [Int:String]) -> ((Int) -> ()) { | |
func fizz_buzz(max: Int) -> () { | |
for number in 1...max { | |
var output = "" | |
for (k, v) in kvs { | |
if number % k == 0 { output += v } | |
} | |
if output == "" { output = String(number) } | |
print(output) | |
} | |
} | |
return fizz_buzz | |
} | |
var dict = [3: "Fizz", 5: "Buzz"] | |
let fizz_buzz_rho = make_fizz_buzz(kvs: dict) | |
fizz_buzz_rho(15) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment