-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdice.php
114 lines (79 loc) · 1.74 KB
/
dice.php
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
#!/usr/bin/php
<?php
echo main($argv);
function main ($args) {
$params = parse($args);
$polys = array();
$combinations = 1;
foreach ($params["rolls"] as $r) {
$combinations *= pow($r["die"], $r["num"]);
$polys = array_merge($polys, mkroll($r));
}
$bigpoly = megamul($polys);
$final = array();
foreach($bigpoly as $x) {
$final[] = $x / $combinations;
}
$output = "\n";
for($exp = 1; $exp < count($final); $exp++) {
$coeff = $final[$exp];
if ($coeff > 0) {
$output .= sprintf(
"%d\t\t%.5f\t\t%s\n",
$exp + $params["const"],
$final[$exp],
str_repeat("#", round(500 * $final[$exp]))
);
}
}
return $output . "\n";
}
function parse ($args) {
$constant = 0;
$rolls = array();
foreach ($args as $t) {
if (strpos($t, "d")) {
$yarr = explode("d", $t);
$rolls[] = array("num" => $yarr[0], "die" => $yarr[1]);
}
else {
$constant += $t;
}
}
return array(
"const" => $constant,
"rolls" => $rolls
);
}
function mkroll ($r) {
$results = array();
for ($i = 1; $i <= $r["num"]; $i++) {
$result = array(0);
for ($j = 1; $j <= $r["die"]; $j++) {
$result[$j] = 1;
}
$results[] = $result;
}
return $results;
}
function poly_multiply ($p1, $p2) {
$ct1 = count($p1);
$ct2 = count($p2);
$result = array_fill(0, $ct1 + $ct2 - 1, 0);
for ($i = 1; $i < $ct1; $i++) {
for ($j = 1; $j < $ct2; $j++) {
$t1 = isset($p1[$i]) ? $p1[$i] : 0;
$t2 = isset($p2[$j]) ? $p2[$j] : 0;
$result[ $i + $j ] += $t1 * $t2;
}
}
return $result;
}
function megamul ($polys) {
$result = array_shift($polys);
foreach($polys as $p) {
$result = poly_multiply($result, $p);
}
return $result;
}
?>