Verify distribution uniformity/Naive: Difference between revisions

Scala added
(Scala added)
Line 1,761:
10 92 ##################*</pre>
 
=={{header|Scala}}==
===Imperative, ugly===
<lang Scala>object DistrubCheck1 extends App {
 
private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {
val counts = scala.collection.mutable.Map[Int, Int]()
 
for (_ <- 0 until nRepeats)
counts.updateWith(f()) {
case Some(count) => Some(count + 1)
case None => Some(1)
}
 
val target: Double = nRepeats.toDouble / counts.size
val deltaCount: Int = (delta / 100.0 * target).toInt
counts.foreach {
case (k, v) =>
if (math.abs(target - v) >= deltaCount)
println(f"distribution potentially skewed for $k%s: $v%d")
}
counts.toIndexedSeq.foreach(entry => println(f"${entry._1}%d ${entry._2}%d"))
}
 
distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)
 
}</lang>
===Functional Style===
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/oYJWUvX/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/O513W3VoQ7ulspUMnGvTiQ Scastie (remote JVM)].
<lang Scala>object DistrubCheck2 extends App {
private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {
val counts: Map[Int, Int] =
(0 until nRepeats).map(_ => f()).groupBy(identity).map { case (k, v) => (k, v.size) }
val target = nRepeats / counts.size.toDouble
 
counts.withFilter { case (_, v) => math.abs(target - v) >= (delta / 100.0 * target) }
.foreach { case (k, v) => println(f"distribution potentially skewed for $k%s: $v%d") }
 
counts.toIndexedSeq.foreach(entry => println(f"${entry._1}%d ${entry._2}%d"))
}
 
distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)
 
}</lang>
=={{header|Tcl}}==
<lang tcl>proc distcheck {random times {delta 1}} {
Anonymous user