Average loop length: Difference between revisions

→‎{{header|Scala}}: migrate to Scala 2.13
(Add Factor)
(→‎{{header|Scala}}: migrate to Scala 2.13)
Line 2,184:
object AverageLoopLength extends App {
 
val factorial: StreamLazyList[Double] = 1 #:: factorial.zip(StreamLazyList.from(1)).map(n => n._2 * factorial(n._2 - 1))
val results = for (n <- 1 to 20;
avg = tested(n, 1000000);
theory = expected(n)
) yield (n, avg, theory, (avg / theory - 1) * 100)
 
def expected(n: Int): Double = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum
 
def trialtested(n: Int, times: Int): Double = {(for (i <- 1 to times) yield trial(n)).sum / times
 
def trial(n: Int): Double = {
var count = 0
var x = 1
Line 2,200 ⟶ 2,206:
count
}
 
def tested(n: Int, times: Int) = (for (i <- 1 to times) yield trial(n)).sum / times
 
val results = for (n <- 1 to 20;
avg = tested(n, 1000000);
theory = expected(n)
) yield (n, avg, theory, (avg / theory - 1) * 100)
 
 
Line 2,212 ⟶ 2,211:
println("------------------------------------")
results foreach { n => {
println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%")
}
}
 
92

edits