Added test that dice rolls are random.

This commit is contained in:
rbamforth
2021-04-11 20:57:43 +01:00
parent c675cd3af8
commit e1f2c92b19
3 changed files with 69 additions and 4 deletions

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Craps
{
@@ -19,6 +18,6 @@ namespace Craps
this.sides = sides;
}
public int Roll() => rand.Next(1, sides);
public int Roll() => rand.Next(1, sides + 1);
}
}

View File

@@ -1,12 +1,13 @@
using System;
namespace Craps
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

View File

@@ -1,6 +1,8 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Craps;
namespace CrapsTester
{
[TestClass]
@@ -27,5 +29,68 @@ namespace CrapsTester
Assert.IsTrue(roll >= 1 && roll <= dice.sides);
}
}
[TestMethod]
public void DiceRollsAreRandom()
{
// Roll 600,000 dice and count how many rolls there are for each side.
var dice = new Dice();
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0;
int numErrors = 0;
for (int i = 0; i < 600000; i++)
{
switch (dice.Roll())
{
case 1:
numOnes++;
break;
case 2:
numTwos++;
break;
case 3:
numThrees++;
break;
case 4:
numFours++;
break;
case 5:
numFives++;
break;
case 6:
numSixes++;
break;
default:
numErrors++;
break;
}
}
// We'll assume that a variation of 10% in rolls for the different numbers is random enough.
// Perfectly random rolling would produce 100000 rolls per side, +/- 5% of this gives the
// range 90000..110000.
const int minRolls = 95000;
const int maxRolls = 105000;
Assert.IsTrue(numOnes >= minRolls && numOnes <= maxRolls);
Assert.IsTrue(numTwos >= minRolls && numTwos <= maxRolls);
Assert.IsTrue(numThrees >= minRolls && numThrees <= maxRolls);
Assert.IsTrue(numFours >= minRolls && numFours <= maxRolls);
Assert.IsTrue(numFives >= minRolls && numFives <= maxRolls);
Assert.IsTrue(numSixes >= minRolls && numSixes <= maxRolls);
Assert.AreEqual(numErrors, 0);
}
}
}