Debian Codegraph @

terps/tads/tads3/test/data/shuffle3.t

raw
1 /*
2 * Test rand-wt (weighted random - 'as decreasingly likely outcomes') by
3 * make a histogram of values and making sure that the statistics come
4 * out the way they should. The defined weighting is that the last item
5 * in the list has relative weight 1, the second to last has weight 2,
6 * the third to last has weight 3, ..., the first item in the last has
7 * weight N.
8 */
9
10 #include <tads.h>
11 #include <bignum.h>
12
13
14 main(args)
15 {
16 local n = args.length() > 1 ? toInteger(args[2]) : 5, trials = 5000;
17
18 local lst = new OneOfIndexGen();
19 lst.numItems = n;
20 lst.listAttrs = 'rand-wt';
21
22 local hist = new Vector(n).fillValue(0, 1, n);
23 for (local i in 1..trials)
24 hist[lst.getNextIndex()]++;
25
26 local sum = n*(n+1)/2;
27 for (local i in 1..n)
28 {
29 local pct = new BigNumber(hist[i])/trials;
30 "<<i>> = <<sprintf('%.2f%% (%.1f/%d)', pct*100, pct*sum, sum)>>\n";
31 }
32 }