How to resolve the algorithm FizzBuzz step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm FizzBuzz step by step in the Scala programming language
Table of Contents
Problem Statement
Write a program that prints the integers from 1 to 100 (inclusive).
But:
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm FizzBuzz step by step in the Scala programming language
Source code in the scala programming language
object FizzBuzz extends App {
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n
})
}
}
def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =
rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) =>
a fold(_ => b, s => b fold(_ => a, t => Right(s + t))))
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity)
1 to 100 map fizzbuzz foreach println
def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))
for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))
def fizzBuzzTerm(n: Int): String =
if (n % 15 == 0) "FizzBuzz"
else if (n % 3 == 0) "Fizz"
else if (n % 5 == 0) "Buzz"
else n.toString
def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)
def fizzBuzzTerm(n: Int): String | Int = // union types
(n % 3, n % 5) match // optional semantic indentation; no braces
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n // no need for `.toString`, thanks to union type
end match // optional `end` keyword, with what it's ending
end fizzBuzzTerm // `end` also usable for identifiers
val fizzBuzz = // no namespace object is required; all top level
LazyList.from(1).map(fizzBuzzTerm)
@main def run(): Unit = // @main for main method; can take custom args
fizzBuzz.take(100).foreach(println)
You may also check:How to resolve the algorithm String case step by step in the E programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the Lingo programming language
You may also check:How to resolve the algorithm Averages/Median step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Pig the dice game step by step in the Nim programming language
You may also check:How to resolve the algorithm Runtime evaluation step by step in the Arturo programming language