Average loop length: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 40:
{{trans|Python}}
 
<syntaxhighlight lang="11l">F ffactorial(n)
V result = 1.0
L(i) 2..n
Line 96:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Numerics.Discrete_Random;
Line 175:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> @% = &2040A
MAX_N = 20
TIMES = 1000000
Line 234:
=={{header|C}}==
 
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 318:
=={{header|C sharp|C#}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">public class AverageLoopLength {
private static int N = 100000;
Line 398:
=={{header|C++}}==
Partial translation of C using stl and std.
<syntaxhighlight lang="cpp">#include <random>
#include <vector>
#include <iostream>
Line 490:
=={{header|Clojure}}==
{{trans|Python}}
<syntaxhighlight lang="lisp">(ns cyclelengths
(:gen-class))
 
Line 562:
=={{header|D}}==
{{trans|Raku}}
<syntaxhighlight lang="d">import std.stdio, std.random, std.math, std.algorithm, std.range, std.format;
 
real analytical(in int n) pure nothrow @safe /*@nogc*/ {
Line 650:
{{libheader| System.Math}}
{{Trans|C}}
<syntaxhighlight lang=Delphi"delphi">
program Average_loop_length;
 
Line 746:
</pre>
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'math) ;; Σ aka (sigma f(n) nfrom nto)
Line 805:
{{trans|Ruby}}
{{works with|Elixir|1.1+}}
<syntaxhighlight lang="elixir">defmodule RC do
def factorial(0), do: 1
def factorial(n), do: Enum.reduce(1..n, 1, &(&1 * &2))
Line 861:
{{trans|Scala}}
<p>But uses the Gamma function instead of factorials.</p>
<syntaxhighlight lang="fsharp">open System
 
let gamma z =
Line 938:
The <code>loop-length</code> word is more or less a translation of the inner loop of C's <code>test</code> function.
{{works with|Factor|0.99 2020-01-23}}
<syntaxhighlight lang="factor">USING: formatting fry io kernel locals math math.factorials
math.functions math.ranges random sequences ;
 
Line 991:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Const max_N = 20, max_ciclos = 1000000
 
Function Factorial(Byval N As Integer) As Double
Line 1,038:
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_nmax = 20
_times = 1000000
Line 1,118:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,189:
 
=={{header|Haskell}}==
<syntaxhighlight lang=Haskell"haskell">import System.Random
import qualified Data.Set as S
import Text.Printf
Line 1,272:
 
We can implement f as {&LIST where LIST is an arbitrary list of N numbers, each picked independently from the range 0..(N-1). We can incrementally build the described sequence using (, f@{:) - here we extend the sequence by applying f to the last element of the sequence. Since we are only concerned with the sequence up to the point of the first repeat, we can select the unique values giving us (~.@, f@{:). This routine stops changing when we reach the desired length, so we can repeatedly apply it forever. For example:
<syntaxhighlight lang=J"j"> (~.@, {&0 0@{:)^:_] 0
0
(~.@, {&0 0@{:)^:_] 1
1 0</syntaxhighlight>
Once we have the sequence, we can count how many elements are in it.
<syntaxhighlight lang=J"j"> 0 0 ([: # (] ~.@, {:@] { [)^:_) 1
2</syntaxhighlight>
Meanwhile, we can also generate all possible values of 1..N by counting out N^N values and breaking out the result as a base N list of digits.
<syntaxhighlight lang=J"j"> (#.inv i.@^~)2
0 0
0 1
Line 1,286:
1 1</syntaxhighlight>
All that's left is to count the lengths of all possible sequences for all possible distinct instances of f and average the results:
<syntaxhighlight lang=J"j"> (+/ % #)@,@((#.inv i.@^~) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)1
1
(+/ % #)@,@((#.inv i.@^~) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)2
Line 1,299:
2.77469</syntaxhighlight>
Meanwhile the analytic solution (derived by reading the Ada implementation) looks like this:
<syntaxhighlight lang=J"j"> ana=: +/@(!@[ % !@- * ^) 1+i.
ana"0]1 2 3 4 5 6
1 1.5 1.88889 2.21875 2.5104 2.77469</syntaxhighlight>
To get our simulation, we can take the exact approach and replace the part that generates all possible values for f with a random mechanism. Since the task does not specify how long to run the simulation, and to make this change easy, we'll use N*1e4 tests.
<syntaxhighlight lang=J"j"> sim=: (+/ % #)@,@((]?@$~1e4,]) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)
sim"0]1 2 3 4 5 6
1 1.5034 1.8825 2.22447 2.51298 2.76898</syntaxhighlight>
Line 1,309:
 
Finally, we can generate our desired results:
<syntaxhighlight lang=J"j"> (;:'N average analytic error'),:,.each(;ana"0 ([;];-|@%[) sim"0)1+i.20
+--+-------+--------+-----------+
|N |average|analytic|error |
Line 1,340:
This uses a 0-based index (0, 1, ..., n-1) as opposed to the 1-based index (1, 2, ..., n) specified in the question, because it fits better with the native structure of Java.
 
<syntaxhighlight lang="java">import java.util.HashSet;
import java.util.Random;
import java.util.Set;
Line 1,399:
=={{header|Julia}}==
{{trans|Python}}
<syntaxhighlight lang="julia">using Printf
 
analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)
Line 1,457:
=={{header|Kotlin}}==
{{trans|Go}}
<syntaxhighlight lang="scala">const val NMAX = 20
const val TESTS = 1000000
val rand = java.util.Random()
Line 1,524:
=={{header|Liberty BASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="lb">
MAXN = 20
TIMES = 10000'00
Line 1,588:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function average(n, reps)
local count = 0
for r = 1, reps do
Line 1,639:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Grid@Prepend[
Table[{n, #[[1]], #[[2]],
Row[{Round[10000 Abs[#[[1]] - #[[2]]]/#[[2]]]/100., "%"}]} &@
Line 1,673:
=={{header|Nim}}==
{{trans|C}}
<syntaxhighlight lang="nim">import random, math, strformat
randomize()
Line 1,732:
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">
MODULE AvgLoopLen;
(* Oxford Oberon-2 *)
Line 1,832:
=={{header|PARI/GP}}==
{{trans|C}}
<syntaxhighlight lang="parigp">expected(n)=sum(i=1,n,n!/(n-i)!/n^i,0.);
test(n, times)={
my(ct);
Line 1,869:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use List::Util qw(sum reduce);
 
sub find_loop {
Line 1,915:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">MAX</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">20</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">ITER</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1000000</span>
Line 1,978:
=={{header|Phixmonti}}==
{{trans|Phix}}
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
20 var MAX
Line 2,048:
=={{header|PicoLisp}}==
{{trans|Python}}
<syntaxhighlight lang=PicoLisp"picolisp">(scl 4)
(seed (in "/dev/urandom" (rd 8)))
 
Line 2,093:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang=PowerShell"powershell">
function Get-AnalyticalLoopAverage ( [int]$N )
{
Line 2,155:
</syntaxhighlight>
Note: The use of the [pscustomobject] type accelerator to simplify making the test result table look pretty requires PowerShell 3.0.
<syntaxhighlight lang=PowerShell"powershell">
# Display results for N = 1 through 20
ForEach ( $N in 1..20 )
Line 2,197:
=={{header|Python}}==
{{trans|C}}
<syntaxhighlight lang="python">from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
Line 2,249:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">
expected <- function(size) {
result <- 0
Line 2,313:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(require (only-in math factorial))
Line 2,372:
(formerly Perl 6)
{{Works with|rakudo|2016.08}}
<syntaxhighlight lang=perl6"raku" line>constant MAX_N = 20;
constant TRIALS = 100;
Line 2,419:
 
Also note that the &nbsp; <big>'''!'''</big> &nbsp; (factorial function) &nbsp; uses memoization for optimization.
<syntaxhighlight lang="rexx">/*REXX program computes the average loop length mapping a random field 1···N ───► 1···N */
parse arg runs tests seed . /*obtain optional arguments from the CL*/
if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/
Line 2,508:
=={{header|Ruby}}==
Ruby does not have a factorial method, not even in it's math library.
<syntaxhighlight lang="ruby">class Integer
def factorial
self == 0 ? 1 : (1..self).inject(:*)
Line 2,561:
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang="rust">extern crate rand;
 
use rand::{ThreadRng, thread_rng};
Line 2,667:
=={{header|Scala}}==
 
<syntaxhighlight lang=Scala"scala">
import scala.util.Random
 
Line 2,733:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 2,819:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,911:
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func find_loop(n) {
var seen = Hash()
loop {
Line 2,960:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
REAL PROCEDURE FACTORIAL(N); INTEGER N;
Line 3,051:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl"># Generate a list of the numbers increasing from $a to $b
proc range {a b} {
for {set result {}} {$a <= $b} {incr a} {lappend result $a}
Line 3,119:
=={{header|Unicon}}==
{{trans|C}}
<syntaxhighlight lang="unicon">link printf, factors
 
$define MAX_N 20
Line 3,184:
=={{header|VBA}}==
{{trans|Phix}}
<syntaxhighlight lang="vb">Const MAX = 20
Const ITER = 1000000
Line 3,246:
=={{header|VBScript}}==
Ported from the VBA version. I added some precalculations to speed it up
<syntaxhighlight lang="vb">
Const MAX = 20
Const ITER = 100000
Line 3,325:
=={{header|Vlang}}==
{{trans|Go}}
<syntaxhighlight lang="vlang">import rand
import math
 
Line 3,395:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 3,468:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">const N=20;
 
(" N average analytical (error)").println();
10,333

edits