Knuth's algorithm S: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 208: | Line 208: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{Output?}} |
|||
Instead of returning a closure we set the environment in a structure: |
Instead of returning a closure we set the environment in a structure: |
||
<lang c>#include <stdlib.h> |
<lang c>#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 1,400: | Line 1,400: | ||
(0..9).each {|digit| puts "#{digit}\t#{frequency[digit]}"}</lang> |
(0..9).each {|digit| puts "#{digit}\t#{frequency[digit]}"}</lang> |
||
Example |
Example |
||
<pre>0 29850 |
<pre>0 29850 |
||
Line 1,412: | Line 1,411: | ||
8 29953 |
8 29953 |
||
9 29852</pre> |
9 29852</pre> |
||
=={{header|Scala}}== |
|||
===Imperative (Ugly and side effects)=== |
|||
<lang Scala>import java.util |
|||
import scala.util.Random |
|||
object KnuthsAlgorithmS extends App { |
|||
import scala.collection.JavaConverters._ |
|||
val (n, rand, bin) = (3, Random, new Array[Int](10)) |
|||
for (_ <- 0 until 100000) { |
|||
val sample = new util.ArrayList[Int](n) |
|||
for (item <- 0 until 10) { |
|||
if (item < n) sample.add(item) |
|||
else if (rand.nextInt(item + 1) < n) |
|||
sample.asScala(rand.nextInt(n)) = item |
|||
} |
|||
for (s <- sample.asScala.toList) bin(s) += 1 |
|||
} |
|||
println(bin.mkString("[", ", ", "]")) |
|||
}</lang> |
|||
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/nlldfXD/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/WLaee5H9T72cximqK9gECA Scastie (JVM)]. |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl 6}} |
{{trans|Perl 6}} |
||
Line 1,615: | Line 1,637: | ||
dist.apply('wrap(n){"%.2f%%".fmt(n.toFloat()/N*100)}).println();</lang> |
dist.apply('wrap(n){"%.2f%%".fmt(n.toFloat()/N*100)}).println();</lang> |
||
{{out}} |
{{out}} |
||
⚫ | |||
<pre> |
|||
⚫ | |||
</pre> |