Skip to content

Instantly share code, notes, and snippets.

@alanjcfs
Last active December 17, 2015 13:29
Show Gist options
  • Save alanjcfs/5617736 to your computer and use it in GitHub Desktop.
Save alanjcfs/5617736 to your computer and use it in GitHub Desktop.
This is an attempt to generalize FizzBuzz based on my current Scala understanding.
import scala.collection.SortedMap
object FizzBuzz {
def generator(mapping: SortedMap[Int, String], lst: List[Int]): List[String] = {
// sort Map descending - Unimplemented
// Something very simple
// (n: Int) => {
val l = lst map((n) => {
val result = mapping.foldLeft("")( (acc, kv) => acc + getResult(kv._1, kv._2, n))
if (result.isEmpty) { n.toString }
else { result }
})
return l
// }
}
def getResult(key: Int, value: String, num: Int): String = {
if (num % key == 0) { value }
else { "" }
}
def main(args: Array[String]) {
val listOfNumbers = (0 to 105).toList
val sortedDescending = listOfNumbers sortWith((x, y) => x > y)
val tuples = SortedMap((5, "Bar"), (7, "Piyo"), (3, "Foo"))
val generatedFunctions = generator(tuples, sortedDescending)
println(generatedFunctions)
}
}
import scala.collection.SortedMap
import scala.collection.mutable.ArrayBuffer
object HogeFuga {
def main(args: Array[String]) {
val tuples = SortedMap((3, "Hoge"), (5, "Fuga"), (7, "Piyo"))
val listOfNumbers = (1 to 105).toList
val arrayOfStrings = applyTuplesToList(tuples, listOfNumbers)
for(s <- arrayOfStrings) {
println(s)
}
}
def applyTuplesToList(tuples: SortedMap[Int, String], listOfNumbers: List[Int]): ArrayBuffer[String] = {
val array = new ArrayBuffer[String]
for (num <- listOfNumbers) {
var accumulated = ""
for ((key, value) <- tuples) {
if (num % key == 0) {
accumulated += value
}
}
if (accumulated.isEmpty) {
array += num.toString
}
else { array += accumulated }
}
return array
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment