Created
March 16, 2021 11:51
-
-
Save YummyLoop/10b1cc40ebc464b9575f6c70debe61b4 to your computer and use it in GitHub Desktop.
A FizzBuzz implementation
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
/** | |
* A FizzBuzz implementation | |
* https://en.wikipedia.org/wiki/Fizz_buzz | |
* | |
* You can edit, run, and share this code. | |
* https://pl.kotl.in/i6mEZnV8B | |
*/ | |
fun version(n : Int){ | |
when(n) { | |
1 -> {// Version 1 | |
val fizz = 3 | |
val buzz = 5 | |
val max = 100 | |
for (i in 1..max){ | |
if (i%fizz == 0) print("Fizz") | |
if (i%buzz == 0) print("Buzz") | |
if (i%fizz == 0 || i%buzz == 0) { | |
print("\n") | |
}else println("$i") | |
} | |
} | |
2 -> {// Version 2 | |
val fizz = 3 | |
val buzz = 5 | |
val max = 100 | |
for (i in 1..max){ | |
if (i%(fizz*buzz) == 0) println("FizzBuzz") | |
else if (i%fizz == 0) println("Fizz") | |
else if (i%buzz == 0) println("Buzz") | |
else println("$i") | |
} | |
} | |
3 -> {// Version 3 | |
val fizz = 3 | |
val buzz = 5 | |
val max = 100 | |
val fizzArray = IntArray(max / fizz + 1) { it * fizz } | |
val buzzArray = IntArray(max / buzz + 1) { it * buzz } | |
val fizzBuzzMap = mutableMapOf<Int, String>().also { | |
fizzArray.forEach { i -> it[i] = "Fizz" } | |
buzzArray.forEach { i -> it.merge(i, "Buzz") { f: String, b: String -> f + b } } | |
}.also { for (i in 1..max) if (it.contains(i)) println(it[i]) else println(i) } | |
} | |
else -> {} | |
} | |
} | |
fun main() { | |
val v = 3 | |
version(v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment