Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidkuster/f485e7675cf56ad95b9ffe18d4511279 to your computer and use it in GitHub Desktop.
Save davidkuster/f485e7675cf56ad95b9ffe18d4511279 to your computer and use it in GitHub Desktop.
Quick FizzBuzz implementations
// corrected from initial approach, using % 15. My first attempt was wrong. This is what I get for not writing tests. Although tests on println...hmm...
def fizzBuzz = {
for (int x=1; x <= 100; x++) {
if (x % (15) == 0) println "FizzBuzz"
else if (x % 3 == 0) println "Fizz"
else if (x % 5 == 0) println "Buzz"
else println x
}
}
// groovier with the range, and optimizing if modulo was expensive
def fizzBuzz2 = {
(1..100).each { x ->
StringBuilder sb = new StringBuilder()
if (x % 3 == 0) sb.append("Fizz")
if (x % 5 == 0) sb.append("Buzz")
if (sb.length() > 0) println sb
else println x
}
}
// optimizing if StringBuilder was expensive
def fizzBuzz3 = {
(1..100).each { x ->
boolean printNum = false
if (x % 3 == 0) {
printNum = true
print "Fizz"
}
if (x % 5 == 0) {
printNum = true
print "Buzz"
}
if (printNum) println ""
else println x
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment