Dice game probabilities: Difference between revisions

Add C# implementation
(Add C# implementation)
 
(5 intermediate revisions by 5 users not shown)
Line 389:
<pre>0.5731440767829801
0.6427886287176260</pre>
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
 
class Program
{
static uint MinOf(uint x, uint y)
{
return x < y ? x : y;
}
 
static void ThrowDie(uint nSides, uint nDice, uint s, uint[] counts)
{
if (nDice == 0)
{
counts[s]++;
return;
}
for (uint i = 1; i <= nSides; i++)
{
ThrowDie(nSides, nDice - 1, s + i, counts);
}
}
 
static double BeatingProbability(uint nSides1, uint nDice1, uint nSides2, uint nDice2)
{
uint len1 = (nSides1 + 1) * nDice1;
uint[] c1 = new uint[len1]; // initialized to zero by default
ThrowDie(nSides1, nDice1, 0, c1);
 
uint len2 = (nSides2 + 1) * nDice2;
uint[] c2 = new uint[len2];
ThrowDie(nSides2, nDice2, 0, c2);
double p12 = Math.Pow(nSides1, nDice1) * Math.Pow(nSides2, nDice2);
 
double tot = 0.0;
for (uint i = 0; i < len1; i++)
{
for (uint j = 0; j < MinOf(i, len2); j++)
{
tot += (double)(c1[i] * c2[j]) / p12;
}
}
return tot;
}
 
static void Main(string[] args)
{
Console.WriteLine(BeatingProbability(4, 9, 6, 6));
Console.WriteLine(BeatingProbability(10, 5, 7, 6));
}
}
</syntaxhighlight>
{{out}}
<pre>
0.573144076782982
0.642788628717627
 
</pre>
 
=={{header|C++}}==
Line 565 ⟶ 626:
<pre>0.5731440767829801
0.6427886287176262</pre>
 
=={{header|EasyLang}}==
{{trans|Phix}}
<syntaxhighlight>
proc throw_die n_sides n_dice s . counts[] .
if n_dice = 0
counts[s] += 1
return
.
for i = 1 to n_sides
throw_die n_sides (n_dice - 1) (s + i) counts[]
.
.
func proba n_sides1 n_dice1 n_sides2 n_dice2 .
len c1[] (n_sides1 + 1) * n_dice1
len c2[] (n_sides2 + 1) * n_dice2
throw_die n_sides1 n_dice1 0 c1[]
throw_die n_sides2 n_dice2 0 c2[]
p12 = pow n_sides1 n_dice1 * pow n_sides2 n_dice2
for i = 1 to len c1[]
for j = 1 to lower (i - 1) len c2[]
tot += c1[i] * c2[j] / p12
.
.
return tot
.
numfmt 5 0
print proba 4 9 6 6
print proba 10 5 7 6
</syntaxhighlight>
 
=={{header|Factor}}==
Line 1,093 ⟶ 1,184:
p1 wins 64.279% of the time</pre>
 
=={{header|JacaScriptJavaScript}}==
===simulating===
<syntaxhighlight lang="javascript">
Line 1,425 ⟶ 1,516:
for val in 1..nsides:
inc c[sum + val], result[sum]
result.shallowCopy = move(c)
 
proc probabilities(counts: seq[int]): seq[Rat] =
Line 2,669 ⟶ 2,760:
var (win,loss,tie) = (0,0,0)
p1.each_kv { |i, x|
win += x*p2.ftfirst(0,i-1).sum
tie += x*p2.ftslice(i, i).first(1).sum
loss += x*p2.ftslice(i+1).sum
}
[win, tie, loss] »/» p1.sum*p2.sum
Line 2,886 ⟶ 2,977:
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="ecmascriptwren">var throwDie // recursive
throwDie = Fn.new { |nSides, nDice, s, counts|
if (nDice == 0) {
337

edits