Executable library: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|Scala}}: migrate to Scala 2.13) |
||
Line 1,819: | Line 1,819: | ||
In Scala it is possible to combine several "main"s |
In Scala it is possible to combine several "main"s |
||
(mixed-in by the App trait) in one file (e.g. HailstoneSequence.scala): |
(mixed-in by the App trait) in one file (e.g. HailstoneSequence.scala): |
||
⚫ | |||
object HailstoneSequence extends App { // Show it all, default number is 27. |
|||
def hailstone(n: Int): |
def hailstone(n: Int): LazyList[Int] = |
||
n #:: (if (n == 1) LazyList.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) |
|||
Hailstone.details(args.headOption.map(_.toInt).getOrElse(27)) |
Hailstone.details(args.headOption.map(_.toInt).getOrElse(27)) |
||
Line 1,828: | Line 1,829: | ||
object Hailstone extends App { // Compute a given or default number to Hailstone sequence |
object Hailstone extends App { // Compute a given or default number to Hailstone sequence |
||
def details(nr: Int) = { |
def details(nr: Int): Unit = { |
||
val collatz = HailstoneSequence.hailstone(nr) |
val collatz = HailstoneSequence.hailstone(nr) |
||
Line 1,835: | Line 1,836: | ||
println(s"It has ${collatz.length} elements.") |
println(s"It has ${collatz.length} elements.") |
||
} |
} |
||
details(args.headOption.map(_.toInt).getOrElse(27)) |
details(args.headOption.map(_.toInt).getOrElse(27)) |
||
} |
} |
||
Line 1,843: | Line 1,845: | ||
val (n, len) = (1 until 100000).map(n => (n, HailstoneSequence.hailstone(n).length)).maxBy(_._2) |
val (n, len) = (1 until 100000).map(n => (n, HailstoneSequence.hailstone(n).length)).maxBy(_._2) |
||
println(s"Longest hailstone sequence length= $len occurring with number $n.") |
println(s"Longest hailstone sequence length= $len occurring with number $n.") |
||
} |
|||
⚫ | |||
</lang> |
|||
Steps: |
Steps: |