How to resolve the algorithm Probabilistic choice step by step in the zkl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Probabilistic choice step by step in the zkl programming language

Table of Contents

Problem Statement

Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Probabilistic choice step by step in the zkl programming language

Source code in the zkl programming language

var names=T("aleph", "beth", "gimel", "daleth",
			  "he", "waw", "zayin", "heth");
var ptable=T(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0).apply('/.fp(1.0));
ptable=ptable.append(1.0-ptable.sum(0.0)); // add last weight to sum to 1.0
var [const] N=ptable.len();

fcn ridx{ i:=0; s:=(0.0).random(1);
   while((s-=ptable[i]) > 0) { i+=1 }
   i
}

const M=0d1_000_000;
var r=(0).pump(N,List,T(Ref,0));  // list of references to int 0
(0).pump(M,Void,fcn{r[ridx()].inc()}); // 1,000,000 weighted random #s

r=r.apply("value").apply("toFloat"); // (reference to int)-->int-->float

println("  Name  Count    Ratio Expected");
foreach i in (N){
   "%6s%7d %7.4f%% %7.4f%%".fmt(names[i], r[i], r[i]/M*100,
		ptable[i]*100).println();
}

  

You may also check:How to resolve the algorithm Subtractive generator step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Tarjan step by step in the Rust programming language
You may also check:How to resolve the algorithm Loops/For with a specified step step by step in the PHP programming language
You may also check:How to resolve the algorithm Metronome step by step in the Ada programming language
You may also check:How to resolve the algorithm Fusc sequence step by step in the Racket programming language