How to resolve the algorithm Average loop length step by step in the 11l programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Average loop length step by step in the 11l programming language

Table of Contents

Problem Statement

Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.

Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.

This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Average loop length step by step in the 11l programming language

Source code in the 11l programming language

F ffactorial(n)
   V result = 1.0
   L(i) 2..n
      result *= i
   R result

V MAX_N = 20
V TIMES = 1000000

F analytical(n)
   R sum((1..n).map(i -> ffactorial(@n) / pow(Float(@n), Float(i)) / ffactorial(@n - i)))

F test(n, times)
   V count = 0
   L(i) 0 .< times
      V (x, bits) = (1, 0)
      L (bits [&] x) == 0
         count++
         bits [|]= x
         x = 1 << random:(n)
   R Float(count) / times

print(" n      avg     exp.    diff\n-------------------------------")
L(n) 1 .. MAX_N
   V avg = test(n, TIMES)
   V theory = analytical(n)
   V diff = (avg / theory - 1) * 100
   print(‘#2 #3.4 #3.4 #2.3%’.format(n, avg, theory, diff))

  

You may also check:How to resolve the algorithm Subtractive generator step by step in the F# programming language
You may also check:How to resolve the algorithm Four bit adder step by step in the Swift programming language
You may also check:How to resolve the algorithm Factorial step by step in the Perl programming language
You may also check:How to resolve the algorithm Semiprime step by step in the Racket programming language
You may also check:How to resolve the algorithm Ulam spiral (for primes) step by step in the Kotlin programming language