-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathautodist.html
More file actions
864 lines (829 loc) · 28.6 KB
/
autodist.html
File metadata and controls
864 lines (829 loc) · 28.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
<head>
<title>Code Generator for Discrete Distributions</title>
<meta charset=utf-8>
</head>
<h2>Code Generator for Discrete Distributions</h2>
<p>This page generates standalone programming code that samples from a discrete distribution, or instructions to choose a random number by flipping a real coin or rolling a real die. That is, the code or instructions are designed to choose an integer in [0, n) at random where each of the n integers has a separate probability of occurring. The idea for a code generator like this came from Leydold et al. (2001). The generator supports generating JavaScript code, Ruby code, or coin-flipping instructions.</p>
<p>The code generator is powered by the recently presented Fast Loaded Dice Roller (Saad et al. 2020) and by the Fast Dice Roller (Lumbroso 2013). The code generator is also powered by JavaScript, at least the kind supported by modern Web browsers. Accordingly, the generator requires JavaScript (active scripting) to be enabled in the browser settings.</p>
<form action='javascript:void(null)'>
<p>In the text box below, enter one of the following:
<ul>
<li>A comma-separated list of integer weights. Each weight must be 0 or greater. Spaces can appear at the beginning and end of the value as well as around the commas. In the following example <code>10, 30, 40</code>, 0 is chosen with probability (10/(10+30+40)) and 1 is chosen with probability (30/(10+30+40)).
<li>A dice specification of the following form: [XX]dYY[+ZZ], where XX is the number of dice, YY is the number of faces per die, and ZZ is a number to add to the final die roll. Examples: d20, d6, 2d10, 4d8+25. Up to 99 dice and 100 faces per die are supported. Note, however, that with high numbers of faces and dice, the code generation may take so long to build that the browser may time out.
</ul>
<br><input type=text id=probabilities /><br>
Name of generator: <input type=text id=genname value="discrete_gen"/><br>
Language of generated code: <select id=genlang>
<option value='javascript'>JavaScript</option>
<option value='ruby'>Ruby</option>
<option value='coinflip'>Coin Flipping (start at 0)</option>
<option value='coinflip1'>Coin Flipping (start at 1)</option>
<option value='dieroll'>Die Rolling (start at 0)</option>
<option value='dieroll1'>Die Rolling (start at 1)</option>
</select>
<div style='color: red' id=error> </div>
<div>The generated code will appear below. No rights are claimed to the code generated by this page (it can be used and distributed freely).</div>
<textarea rows=30 cols=40 id=code></textarea>
</form>
<p>This is an <a href="https://github.com/peteroupc/peteroupc.github.io/blob/master/autodist.html">open-source generator</a> written by Peter Occil. Any copyright to this page is released to the Public Domain. In case this is not possible, this page is also licensed under <a href="https://creativecommons.org/publicdomain/zero/1.0/">Creative Commons Zero</a>. If you have comments or issues on this generator, send them to the <a href="https://github.com/peteroupc/peteroupc.github.io/issues">GitHub issues page</a>.</p>
<h3>About the Coin-Flipping and Die-Rolling Instructions</h3>
<p>This generator supports generating instructions that choose a nonuniform random number by flipping a real coin or rolling a real six-sided die.</p>
<ul>
<li>The coin-flipping instructions were generated by running the Fast Loaded Dice Roller on fixed sequences of coin flip results (such as H/T/T/H/H). For dice specifications, the coin-flipping instructions were generated similarly to the die-rolling instructions instead, because it's considerably faster than checking all sequences with the Fast Loaded Dice Roller.
<li>The die-rolling instructions implement a variant of the "greedy simulation" process described in B. Kloeckner, "<a href="https://perso.math.u-pem.fr/kloeckner.benoit/papiers/DiceSimulation.pdf">Simulating a dice with a dice</a>", 2008, except it supports any nonuniform discrete distribution (within reason), that is, the output die can be a loaded die, not just a fair one. The die-rolling instructions allow a nonuniform random number to be chosen by rolling a real (fair) six-sided die.</li>
</ul>
<h3>References</h3>
<p>Saad, F.A., Freer C.E., et al. "The Fast Loaded Dice Roller: A Near-Optimal Exact Sampler for Discrete Probability Distributions", in _AISTATS 2020_ 108.</p>
<p>Leydold, et al., "An Automatic Code Generator for Nonuniform Random Variate Generation", 2001.</p>
<p>Lumbroso, J., "<a href='https://arxiv.org/abs/1304.1916'>Optimal Discrete Uniform Generation from Coin Flips, and Applications</a>", arXiv:1304.1916 [cs.DS]</p>
<script>
function times(n) {
let x=[]
for(let i=0;i<n;i++){
x.push(i)
}
return x
}
function min(a) {
let x=a[0]
for(let i=1;i<a.length;i++){
x=Math.min(x, a[i])
}
return x
}
function maxval(a) {
let x=a[0]
for(let i=1;i<a.length;i++){
x=Math.max(x, a[i])
}
return x
}
function sum(a) {
let x=0
for(let i=0;i<a.length;i++){
x+=a[i]
}
return x
}
function zeros(n) {
let x=[]
for(let i=0;i<n;i++){
x.push(0)
}
return x
}
function fdrruby(name, v) {
name=name||"discrete_gen"
ret="def "+name+"()\n"
if (v==1) {
ret += "return 0\n"
} else if(v==2) {
// Special case of 2 items with equal probability
ret += " return rand(2)\n"
} else {
ret += " x = 1\n"
ret += " y = 0\n"
ret += " while true\n"
ret += " x = (x << 1)\n"
ret += " y = rand(2) + (y << 1)\n"
ret += " if x > "+(v-1)+"\n"
ret += " return y if y <= "+(v-1)+"\n"
ret += " x -= "+(v)+"\n"
ret += " y -= "+(v)+"\n"
ret += " end\n"
ret += " end\n"
}
ret+="end\n"
return ret
}
function fdr(name, v) {
name=name||"discrete_gen"
ret="function "+name+"() {\n"
if (v==1) {
ret += "return 0\n"
} else if(v==2) {
// Special case of 2 items with equal probability
ret += " return Math.random() < 0.5 ? 0 : 1;\n"
} else {
ret += " let x = 1;\n"
ret += " let y = 0;\n"
ret += " while (true) {\n"
ret += " x = (x * 2);\n"
ret += " y = (Math.random() < 0.5 ? 0 : 1) + (y * 2);\n"
ret += " if (x > "+(v-1)+") {\n"
ret += " if (y <= "+(v-1)+") { return y; }\n"
ret += " x -= "+(v)+";\n"
ret += " y -= "+(v)+";\n"
ret += " }\n"
ret += " }\n"
}
ret+="}\n"
return ret
}
function codegenruby(fldr,name,offset) {
name=name||"discrete_gen"
ret="def "+name+"()\n"
if (fldr[0]==null) {
ret += "return " + (fldr[2]+(offset||0)) + "\n"
} else if(fldr[0][0].length==1) {
// Special case of 2 items with equal probability
ret += " return rand(2) == 0 ? " +(fldr[0][1][0]-1+(offset||0)) +" : " +
(fldr[0][2][0]-1+(offset||0))+"\n"
} else {
ret += " table = ["
for (let i=0;i<fldr[0].length;i++){
if(i > 0) {
ret += ", "
}
ret += "["+fldr[0][i]+"]"
}
ret += "]\n\n"
ret += " x = 0\n"
ret += " y = 0\n"
ret += " while true\n"
ret += " x = rand(2) + (x * 2)\n"
ret += " leaves = table[0][y]\n"
ret += " if x < leaves\n"
if (fldr[2]<fldr[1]) {
// No rejection leaf
if (offset && offset!=0) {
ret += " return (table[x + 1][y] - 1) + " + (offset||0) + "\n"
} else {
ret += " return table[x + 1][y] - 1\n"
}
} else {
ret += " label = table[x + 1][y]\n"
ret += " if label <= "+fldr[1]+"\n"
if (offset && offset!=0) {
ret += " return (label - 1) + " + (offset||0) + "\n"
} else {
ret += " return label - 1\n"
}
ret += " end\n"
ret += " x = 0\n"
ret += " y = 0\n"
}
ret += " else\n"
ret += " x -= leaves\n"
ret += " y += 1\n"
ret += " end\n"
ret += " end\n"
}
ret+="end\n"
return ret
}
function codegen(fldr,name,offset) {
name=name||"discrete_gen"
ret="var "+name+" = (function() {\n"
if (fldr[0]==null) {
ret += "return function(){\n"
ret += " return " + (fldr[2]+(offset||0)) + "\n"
} else if(fldr[0][0].length==1) {
// Special case of 2 items with equal probability
ret += "return function(){\n"
ret += " return Math.random() < 0.5 ? " +((fldr[0][1][0]-1)+(offset||0)) +" : " +
((fldr[0][2][0]-1)+(offset||0))+"\n"
} else {
ret += "var table = ["
for (let i=0;i<fldr[0].length;i++){
if(i > 0) {
ret += ", "
}
ret += "["+fldr[0][i]+"]"
}
ret += "]\n\n"
ret += "return function(){\n"
ret += " let x = 0\n"
ret += " let y = 0\n"
ret += " while (true) {\n"
ret += " x = (Math.random() < 0.5 ? 0 : 1) + (x * 2)\n"
ret += " let leaves = table[0][y]\n"
ret += " if(x < leaves){\n"
if (fldr[2]<fldr[1]) {
// No rejection leaf
if (offset && offset!=0) {
ret += " return (table[x + 1][y] - 1) + " + (offset||0) + "\n"
} else {
ret += " return table[x + 1][y] - 1\n"
}
} else {
ret += " let label = table[x + 1][y]\n"
ret += " if (label <= "+fldr[1]+") {\n"
if (offset && offset!=0) {
ret += " return (label - 1) + " + (offset||0) + "\n"
} else {
ret += " return label - 1\n"
}
ret += " }\n"
ret += " x = 0\n"
ret += " y = 0\n"
}
ret += " } else {\n"
ret += " x -= leaves\n"
ret += " y += 1\n"
ret += "}}\n"
}
ret+="}})();\n"
return ret
}
function fldrResult(table,coinresult,max){
let i=0
let x=0
let y=0
let numcoins=0
while(true){
x=(coinresult&1)+x*2
coinresult>>=1
numcoins+=1
let leaves=table[0][y]
if(x<leaves){
let label=table[x+1][y]
if(label<=max)
return [label-1,numcoins]
// Rejected
return null
} else {
x-=leaves
y+=1
}
}
}
function headstails(coinresult,coins,truecoins){
let ret=[]
for(var i=0;i<coins;i+=1){
if (i<truecoins)
ret.push((coinresult&1)==1 ? "H" : "T")
else
ret.push("X")
coinresult>>=1
}
return ret.join("/")
}
function dieroll(dice,truecoins){
let ret=[]
for(var i=0;i<truecoins;i+=1){
if (i<dice.length)
ret.push((Number(dice[i])+1)+"")
else
ret.push("X")
}
return ret.join("/")
}
function cointoss(dice,truecoins){
let ret=[]
for(var i=0;i<truecoins;i+=1){
if (i<dice.length)
ret.push(("TH").charAt(Number(dice[i]))+"")
else
ret.push("X")
}
return ret.join("/")
}
function chancenote(weights,offset){
let wmax=weights[0]
let wmin=weights[0]
let ret=""
for(var i=0;i<weights.length;i++){
wmax=Math.max(wmax,weights[i])
wmin=Math.min(wmin,weights[i])
}
if(wmax==wmin) {
ret+="With these instructions, there is an equal chance of " +
"getting any whole number from " +
(offset||0) + " through " + ((weights.length-1)+(offset||0))+".\n"
} else {
ret+="With these instructions, the chance of getting:\n\n"
let wsum=sum(weights)
for(var i=0;i<weights.length;i++){
let pct=Math.floor((weights[i]/wsum)*10000)/100.0
let w=weights[i]
if (w == 0) {
ret+="- "+(i+(offset||0)) + " is 0 (0%).\n"
} else {
let wgcd=gcd(w,wsum)
ret+="- "+(i+(offset||0)) + " is "+(weights[i]/wgcd)+"/"+(wsum/wgcd)
if(pct/100.0 == (weights[i]/wsum)) {
ret+=" ("+pct+"%).\n"
} else {
ret+=" (about "+pct+"%).\n"
}
}
}
}
return ret
}
function fldrTable(data,offset,weights){
if(!data || !data[0]){
return "The result is "+(offset||0)+".\n\n"
}
let table=data[0]
let max=data[1]
let coins=table[0].length
let ret="Flip a coin"+(coins>1 ? " up to "+coins+" times" : "")+". If you get:\n\n"
let results={}
let items=[]
let quick1=0
let quick2=0
let quick3=0
let quick4=0
let quick5=0
let reject=false
let x=0
//console.log("fldrtable")
for (var i=0;i<2**coins;i+=1){
if((quick1 & (1<<(i&1)))!=0)continue;
if((quick2 & (1<<(i&3)))!=0)continue;
if((quick3 & (1<<(i&0x07)))!=0)continue;
if((quick4 & (1<<(i&0x0f)))!=0)continue;
if((quick5 & (1<<(i&0x1f)))!=0)continue;
//if(x%10000==0)console.log([x,i])
//x+=1
let r=fldrResult(table,i,max)
if(r!=null){
let res=headstails(i,coins,r[1])
if (!results[res]){
if(r[1]==1)quick1|=1<<(i&0x01);
if(r[1]==2)quick2|=1<<(i&0x03);
if(r[1]==3)quick3|=1<<(i&0x07);
if(r[1]==4)quick4|=1<<(i&0x0F);
if(r[1]==5)quick5|=1<<(i&0x1f);
//console.log([r[1],quick1,quick2,quick3,quick4,quick5])
items.push("- "+res+", the result is "+(r[0]+(offset||0))+".")
results[res]=true
}
} else {
reject=true
}
}
ret+=items.sort().reverse().join("\n")+"\n"
if(reject){
ret+="- Anything else, start over.\n"
}
ret+="\n"
ret+="T = Tails (or 1, 2, or 3 on a six-sided die).\n"
ret+="H = Heads (or 4, 5, or 6 on a six-sided die).\n"
ret+="X = Either T or H.\n\n"
ret+=chancenote(weights,offset)+"\n"
return ret
}
function ceilingToPowerOf2Or3Or6(x) {
let power2=2
let power3=3
let power6=6
while(x>power2) {
power2*=2
}
while(x>power3) {
power3*=3
}
while(x>power6) {
power6*=6
}
return Math.min(Math.min(power2,power3), power6)
}
function ceilingToPowerOf2(x) {
let power2=2
while(x>power2) {
power2*=2
}
return power2
}
function rational(x,y) {
if(typeof y=="undefined")y=1
if(typeof BigInt!="undefined") {
return [BigInt(x),BigInt(y)]
} else {
return [x,y]
}
}
function rationalpow(rat,y) {
if(y>Number.MAX_SAFE_INTEGER)throw new Error("unsupported y")
var n=Number(y)
var j=rational(1)
var m=rat
while(n>0){
if(n%2==1){
j=rationalmul(j,m)
}
n=Math.floor(n/2)
m=rationalmul(m,m)
}
return j
}
function rationalmul(rat,rat2) {
return [rat[0]*rat2[0],rat[1]*rat2[1]]
}
function rationaladd(rat,rat2) {
return [rat[0]*rat2[1]+rat[1]*rat2[0],rat[1]*rat2[1]]
}
function rationalabssub(rat,rat2) {
let r=rat[0]*rat2[1]-rat[1]*rat2[0]
if(r<0)r=-r
return [r,rat[1]*rat2[1]]
}
function rationaldiv(rat,rat2) {
return [rat[0]*rat2[1],rat[1]*rat2[0]]
}
function rationalcmp(rat,rat2) {
if(typeof rat2=="number")rat2=rational(rat2)
s=rat[0]*rat2[1]-rat[1]*rat2[0]
return s<0 ? -1 : (s==0 ? 0 : 1)
}
function rationalsum(a) {
let x=rational(0)
for(let i=0;i<a.length;i++){
x=rationaladd(x,a[i])
}
return x
}
function rationalnum(rat) {
return Number(rat[0])/Number(rat[1])
}
function dicetable(weights, offset, srcFaces) {
// Reference: Benoît Kloeckner, "Simulating a dice with a dice", 2008.
// Extended to allow the output die to have an arbitrary discrete
// distribution (loaded dice), not just a uniform distribution (fair dice).
// This requires only a trivial modification to the greedy simulation
// process in that paper.
if(weights.length<2){
return "The result is "+(offset||0)+".\n\n"
}
let origweights=weights
let wgcd=weightsgcd(weights)
weights=weights.map(o=>o/wgcd)
// Notice that this method works for any number of faces
// if the sum of weights adjusts so that every prime number
// dividing that sum also divides 'srcFaces' (see Lemma 3 of
// Kloeckner's paper).
if(srcFaces==null)srcFaces=6
let dstWords=[];
for(var i=0;i<weights.length;i++) { dstWords.push([]) }
let dstWeights=[];
for(var i=0;i<weights.length;i++) { dstWeights.push(rational(0)) }
let srcWord=0
let srcWordCount=1
let onen=1
let wsum=sum(weights)
if(typeof BigInt!="undefined"){
srcFaces=BigInt(srcFaces)
srcWordCount=BigInt(srcWord)
srcWord=BigInt(srcWordCount)
onen=BigInt(onen)
}
let dstFaces=weights.length // Max. number of outcomes
// Make the sum of weights a power of all prime factors of srcFaces,
// or a power of 6 if srcFaces==6, to give
// the simulation a bounded running time (see Lemma 3 of
// Kloeckner's paper). Assumes srcFaces is either 2 or 6.
// This is similar to an idea used by the
// Fast Loaded Dice Roller, where it changes the weight table
// to make the sum of weights a power of 2, by adding a
// rejection event.
let wsp2or3=(srcFaces==6) ? ceilingToPowerOf2Or3Or6(wsum) :
ceilingToPowerOf2(wsum)
if(wsum!=wsp2or3) {
// Add a "rejection" weight
let newWeights=[]
for(var i=0;i<weights.length;i++) { newWeights.push(weights[i]) }
let newWeight = wsp2or3-wsum
wsum+=newWeight
newWeights.push(newWeight)
dstWords.push([])
dstWeights.push(rational(0))
weights=newWeights
}
while (true) {
let wordsAddedInAll=true
for (var i=0;i<dstWords.length;i++){
let wordsAdded=0
//console.log([srcWord,srcFaces**srcWordCount])
if(srcWord+onen==srcWord){
return "Accuracy error detected, so the die-rolling instructions could not be created."
}
while(srcWord<srcFaces**srcWordCount) {
let t=srcWord
let wordToAdd=[]
for (var j=0;j<srcWordCount;j++){
wordToAdd.push(t%srcFaces)
t=t/srcFaces
if(typeof BigInt=="undefined"){
t=Math.floor(t)
}
}
let newWeight=rationaladd(
dstWeights[i],
rationalpow(rational(1,srcFaces),srcWordCount))
// Instead of 1/k (as in the paper), we check whether
// newWeight is greater than the face's corresponding probability
if (rationalcmp(newWeight,rational(weights[i],wsum))>0) {
if(wordsAdded>0) {
wordsAddedInAll=false
}
break
}
dstWeights[i]=newWeight
srcWord+=onen
wordsAdded+=1
wordToAdd=wordToAdd.reverse()
dstWords[i].push(wordToAdd)
}
}
// Stop if all the faces are filled with words and their
// "weights" sum to 1.
let minWordsLength=-1
for(var i=0;i<weights.length;i++){
if(weights[i]>0) {
if (minWordsLength==-1)
minWordsLength=dstWords[i].length
else
minWordsLength=Math.min(minWordsLength,dstWords[i].length)
}
}
var dw=rationalsum(dstWeights)
if(minWordsLength>0 && rationalcmp(dw,1)==0) {
break
}
srcWord*=srcFaces
srcWordCount+=onen
}
let coins=0
for(var i=0;i<dstWords.length;i++){
for(var j=0;j<dstWords[i].length;j++){
coins=Math.max(coins,dstWords[i][j].length)
}
}
let ret=(srcFaces==2 ? "Flip a coin" : "Roll a "+srcFaces+"-sided die")
ret+=(coins>1 ? " up to "+coins+" times" : "")+". If you get:\n\n"
let results={}
let items=[]
let reject=false
for(var i=0;i<dstWords.length;i++){
for(var j=0;j<dstWords[i].length;j++){
if(dstWords[i][j].length>0 && i < dstFaces) {
items.push("- "+(srcFaces==2 ? cointoss : dieroll)(dstWords[i][j],coins)+", the result is "+(i+(offset||0))+".")
}
}
}
items=items.sort()
if(srcFaces==2)items=items.reverse()
ret+=items.join("\n")+"\n"
if(sum(dstWeights)<1 || dstFaces < dstWeights.length){
ret+="- Anything else, start over.\n"
}
ret+="\n"
if(srcFaces==2) {
ret+="T = Tails (or 1, 2, or 3 on a six-sided die).\n"
ret+="H = Heads (or 4, 5, or 6 on a six-sided die).\n"
ret+="X = Either T or H.\n\n"
} else {
ret+="X = Any die roll.\n\n"
}
ret+=chancenote(origweights,offset)+"\n"
return ret
}
function gcd(a, b) {
if(a==0||b==0)return 0
while(true){
var c=Math.floor(a/b)
var d=a-b*c
a=b
b=d
if(b==0)return a
}
}
function weightsgcd(weights){
var lastgcd=-1
for(var i=0;i<weights.length;i++){
if(weights[i]!=0){
if(lastgcd<0){
lastgcd=weights[i]
} else {
lastgcd=gcd(lastgcd,weights[i])
}
}
}
return Math.max(1, lastgcd)
}
function fldr(weights) {
// Initialize data for Fast Loaded Dice Roller
let n = weights.length
let weightBits = 0
// Find GCD of all weights, to optimize the table's size
let wgcd = weightsgcd(weights)
weights=weights.map(o=>o/wgcd)
let totalWeights = sum(weights)
if(totalWeights==0)return null
if(totalWeights < 0)
throw new Error("Sum of weights is negative")
let minWeight = min(weights)
if(minWeight<0)return null
let realLabels=null
let rejectionLabel=n
if(minWeight==0) {
// Some weights are zero
newWeights=[]
realLabels=[]
for(let i=0;i<weights.length;i++){
if(weights[i]!=0) {
newWeights.push(weights[i])
realLabels.push(i + 1)
}
}
realLabels.push(rejectionLabel + 1)
weights=newWeights
n=weights.length
}
if(weights.length==1) {
// Degenerate case
return [null, -1, realLabels ? (realLabels[0]-1) : 0]
}
let tmp = (totalWeights-1)
while(tmp > 0) {
tmp = Math.floor(tmp/2)
weightBits += 1
}
let maxLeaf = 0
let lasta = Math.pow(2, weightBits) - totalWeights
let leavesAndLabels = times(n+2).map(o=>zeros(weightBits))
let shift = weightBits - 1
for (let j=0;j<weightBits;j++){
let level = 1
for (let i=0;i<n+1;i++){
let ai = (i==n) ? lasta : weights[i]
if (ai < 0) { return null; }
let leaf = Math.floor(ai/Math.pow(2, shift)) & 1
if (leaf > 0) {
// NOTE: Labels start at 1
leavesAndLabels[0][j] += leaf
label = realLabels ? realLabels[i] : i + 1
leavesAndLabels[level][j] = label
maxLeaf = Math.max(maxLeaf, label - 1)
level += 1
}
}
shift -= 1
}
return [leavesAndLabels, rejectionLabel, maxLeaf]
}
function sameweights(x){
if(x.length<2)return true
for(var i=1;i<x.length;i++){
if(x[i]!=x[0])return false
}
return true
}
function binco(n, i) {
// A robust form of the binomial coefficient that
// returns NaN if the result would exceed MAX_SAFE_INTEGER.
// Except in certain trivial cases, also returns NaN
// if either argument exceeds MAX_SAFE_INTEGER.
if(i === 0 || i === n) {
return 1;
} else if(isNaN(n) || isNaN(i) || n > 9007199254740991 ||
i > 9007199254740991) {
return 0.0 / 0.0;
} else if(i === 1) {
return n;
} else if(i > n || n < 0 || i < 0) {
return 0;
} else if(n - 1 === i) {
return n;
} else if(n < binco._fact.length) {
return binco._fact[n] / (binco._fact[i] * binco._fact[n - i]);
} else if(n / 2 < i && n - i !== i) {
return binco(n, n - i);
} else {
var bc = binco(n - 1, i - 1);
if(isNaN(bc))return bc;
if(bc % i === 0) {
var ret = bc / i * n;
if(ret <= 9007199254740991)return ret;
} else {
var tret = bc * n;
if(tret <= 9007199254740991)return tret / i;
}
var bc2 = binco(n - 1, i);
bc2 += bc;
if(bc2 <= 9007199254740991)return bc2;
return 0.0 / 0.0;
}
}
binco._fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880,
3628800, 39916800, 479001600, 6227020800, 87178291200,
1307674368000, 20922789888000, 355687428096000,
6402373705728000];
var changefunc=function() {
var curval=document.getElementById("probabilities").value+"|"+
document.getElementById("genname").value+"|"+
document.getElementById("genlang").value
if(currentValue==curval)return
currentValue=curval
var weights=document.getElementById("probabilities").value
if(weights.length==0)return
var genname=document.getElementById("genname").value
var glang=document.getElementById("genlang").value
var d20test=(/^\s*(\d\d?)?d(\d+?)(?:\+(\d+))?\s*$/).exec(weights)
//console.log(d20test)
var weightints=[]
var code=""
if(d20test) {
let numdice=d20test[1]==null ? 1 : parseInt(d20test[1],10)
let numfaces=parseInt(d20test[2],10)
let bonus=d20test[3]==null ? 0 : parseInt(d20test[3],10)
if(numfaces>100 || numfaces<2) {
document.getElementById("error").innerHTML="This generator supports "+
"only 2 through 100 die faces."
return
}
if(numdice>99) {
document.getElementById("error").innerHTML="This generator does not "+
"support die numbers greater than 99."
return
}
if(bonus>Number.MAX_SAFE_INTEGER) {
document.getElementById("error").innerHTML="This generator does not "+
"support bonuses greater than "+Number.MAX_SAFE_INTEGER+"."
return
}
weightints=[]
for(var i=0;i<=numdice*numfaces;i++){
var p=i
var lim=Math.floor(((p+1)-numdice)/numfaces)
//console.log(lim)
if(lim<0) {
weightints.push(0)
} else {
var weight=0
for(var j=0;j<=lim;j++){
weight+=Math.pow(-1,j) * binco(numdice, j) * binco(p - numfaces*j - 1, numdice-1)
}
weightints.push(weight)
}
}
var data=fldr(weightints)
if(!data && document.getElementById("probabilities").value!="") {
document.getElementById("error").innerHTML="Failed to generate code for these weights."
return
}
//console.log([weightints,bonus])
if (glang=="javascript")code=codegen(data,genname,bonus)
if (glang=="ruby")code=codegenruby(data,genname,bonus)
if (glang=="coinflip")code=dicetable(weightints,bonus,2)
if (glang=="coinflip1")code=dicetable(weightints,bonus+1,2)
if (glang=="dieroll")code=dicetable(weightints,bonus)
if (glang=="dieroll1")code=dicetable(weightints,bonus+1)
} else {
genname=genname.replace(/[^A-Za-z0-9_]+/g,"_")
.replace(/^[0-9]/,"_")
weights=weights.replace(/^\s+/g,"")
weights=weights.replace(/\s+$/g,"")
weights=weights.replace(/,\s*$/g,"")
weights=weights.split(/\s*,\s*/)
for(var i=0;i<weights.length;i++){
if(!(/^\d+$/).test(weights[i])) {
document.getElementById("error").innerHTML="Not a valid list of integer weights."
return
}
num=Number.parseInt(weights[i],10)
if(num>Number.MAX_SAFE_INTEGER) {
document.getElementById("error").innerHTML="This generator does not "+
"support weights greater than "+Number.MAX_SAFE_INTEGER+"."
return
}
weightints.push(num)
}
if(weightints.length==0)return
if(sum(weightints)>Number.MAX_SAFE_INTEGER){
document.getElementById("error").innerHTML="This generator does not "+
"support a sum of weights greater than "+Number.MAX_SAFE_INTEGER+"."
return
}
if(sameweights(weightints) && (glang=="javascript" || glang=="ruby")) {
// All weights are the same
if (glang=="javascript")code=fdr(data,weightints.length)
if (glang=="ruby")code=fdrruby(data,weightints.length)
} else {
var data=fldr(weightints)
if(!data && document.getElementById("probabilities").value!="") {
document.getElementById("error").innerHTML="Failed to generate code for these weights."
return
}
if (glang=="javascript")code=codegen(data,genname)
if (glang=="ruby")code=codegenruby(data,genname)
if (glang=="coinflip")code=fldrTable(data,0,weightints)
if (glang=="coinflip1")code=fldrTable(data,1,weightints)
if (glang=="dieroll")code=dicetable(weightints,0)
if (glang=="dieroll1")code=dicetable(weightints,1)
}
}
document.getElementById("code").value=code
document.getElementById("error").innerHTML=""
}
var currentValue = null
document.getElementById("probabilities").addEventListener(
"change",
changefunc)
window.setInterval(function() {
changefunc()
}, 200)
</script>