How to resolve the algorithm Average loop length step by step in the Liberty BASIC programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Average loop length step by step in the Liberty BASIC 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 Liberty BASIC programming language

Source code in the liberty programming language

MAXN = 20
TIMES = 10000'00

't0=time$("ms")
FOR n = 1 TO MAXN
    avg = FNtest(n, TIMES)
    theory = FNanalytical(n)
    diff = (avg / theory - 1) * 100
    PRINT n, avg, theory, using("##.####",diff); "%"
NEXT
't1=time$("ms")
'print t1-t0; " ms"
END

function FNanalytical(n)
    FOR i = 1 TO n
        s = s+ FNfactorial(n) / n^i / FNfactorial(n-i)
    NEXT
    FNanalytical = s
end function

function FNtest(n, times)
    FOR i = 1 TO times
        x = 1 : b = 0
        WHILE (b AND x) = 0
            c = c + 1
            b = b OR x
            x = 2^int(n*RND(1))
        WEND
    NEXT
    FNtest = c / times
end function

function FNfactorial(n)
    IF n=1 OR n=0 THEN FNfactorial=1 ELSE FNfactorial= n * FNfactorial(n-1)
end function

  

You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the BCPL programming language
You may also check:How to resolve the algorithm Tau number step by step in the Lua programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the Dart programming language
You may also check:How to resolve the algorithm Variable size/Set step by step in the Scala programming language
You may also check:How to resolve the algorithm Exponentiation with infix operators in (or operating on) the base step by step in the R programming language