Created
May 31, 2012 06:30
-
-
Save roryokane/2841492 to your computer and use it in GitHub Desktop.
exploratory FizzBuzz in Scala
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
import scala.collection.mutable.ArrayBuffer | |
object Runner { | |
def main(args: Array[String]) { | |
// printFizzBuzz(20) | |
val max = 20 | |
val factorsAndWords = Map(3 -> "Fizz", 5 -> "Buzz") | |
printGenericFizzBuzz(max, factorsAndWords) | |
} | |
def printFizzBuzz(max: Int): Unit = { | |
for (num <- 1 to max) { | |
if (isDivisible(num, 3) || isDivisible(num, 5)) { | |
if (isDivisible(num, 3)) | |
print("Fizz") | |
if (isDivisible(num, 5)) | |
print("Buzz") | |
} else { | |
print(num) | |
// Is there a way to call print without parens, like `print "something"`? If not, why not? | |
} | |
println() | |
} | |
} | |
def printGenericFizzBuzz(max: Int, factorsAndWords: Map[Int, String]) : Unit = { | |
// uses algorithm from http://news.ycombinator.com/item?id=4614757 | |
for (num <- 1 to max) { | |
var specialSyllables = ArrayBuffer[String]() | |
for ((factor, word) <- factorsAndWords) { | |
if (isDivisible(num, factor)) | |
specialSyllables.append(word) | |
} | |
// after getting constructing specialSyllables working, rewrite that code to be immutable | |
// by using fold (reduce) starting with an empty map | |
if (specialSyllables.size > 0) { | |
print(specialSyllables.mkString) | |
} else { | |
print(num) | |
} | |
println() | |
} | |
} | |
// can I make this callable like `15 isDivisibleBy 5`? | |
// can I somehow write Int once to indicate that all parameters are Ints? | |
def isDivisible(number: Int, factor: Int) = { | |
number % factor == 0 | |
} | |
// function return values can be inferred, so I will probably be able to leave it out | |
def fizzBuzzStream(max: Int): Unit = { | |
// try to return a stream or "generator" that can be printed as the results are calculated | |
// perhaps the "for ... yield" syntax will help | |
} | |
// def printIntGenerator(generator: Generator[Int]) { | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment