Skip to content

Instantly share code, notes, and snippets.

@Syjgin
Created February 12, 2022 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Syjgin/81a7d0aafedacc7f5c88567e6b365627 to your computer and use it in GitHub Desktop.
Save Syjgin/81a7d0aafedacc7f5c88567e6b365627 to your computer and use it in GitHub Desktop.
Bruteforce dice possibility calculator
using System;
namespace Tests
{
public static class PossibilityUtils
{
public static float GetMoreOrEqualPossibilitySum(int dicesCount, int dice, int target)
{
var allPossibilies = (int)Math.Pow(dice, dicesCount);
var goodSumCount = 0;
var sums = new int[allPossibilies];
var indexes = new int[dicesCount];
for (int i = 0; i < dicesCount; i++)
{
indexes[i] = 1;
}
var index = 0;
var checkFinish = false;
while (true)
{
var currentSum = 0;
for (int i = 0; i < dicesCount; i++)
{
currentSum += indexes[i];
}
sums[index] = currentSum;
if (checkFinish)
break;
var currentDigit = dicesCount - 1;
if (indexes[currentDigit] < dice)
{
indexes[currentDigit]++;
}
else
{
var isTransfer = indexes[currentDigit] == dice;
while (currentDigit >= 0)
{
if (indexes[currentDigit] == dice && isTransfer)
{
indexes[currentDigit] = 1;
}
else
{
if (isTransfer)
{
indexes[currentDigit]++;
isTransfer = false;
}
}
currentDigit--;
}
}
var currentCheck = true;
for (int i = 0; i < dicesCount; i++)
{
if (indexes[i] == dice) continue;
currentCheck = false;
break;
}
if (currentCheck)
checkFinish = true;
index++;
}
foreach (var sum in sums)
{
if (sum >= target)
goodSumCount++;
}
return (float)goodSumCount / allPossibilies;
}
public static float GetMoreOrEqualAtLeastOnePossibility(int dicesCount, int dice, int target)
{
var allPossibilies = (int)Math.Pow(dice, dicesCount);
var goodCaseCount = 0;
var max = new int[allPossibilies];
var indexes = new int[dicesCount];
for (int i = 0; i < dicesCount; i++)
{
indexes[i] = 1;
}
var index = 0;
var checkFinish = false;
while (true)
{
var currentMax = 0;
for (int i = 0; i < dicesCount; i++)
{
if (currentMax < indexes[i])
currentMax = indexes[i];
}
max[index] = currentMax;
if (checkFinish)
break;
var currentDigit = dicesCount - 1;
if (indexes[currentDigit] < dice)
{
indexes[currentDigit]++;
}
else
{
var isTransfer = indexes[currentDigit] == dice;
while (currentDigit >= 0)
{
if (indexes[currentDigit] == dice && isTransfer)
{
indexes[currentDigit] = 1;
}
else
{
if (isTransfer)
{
indexes[currentDigit]++;
isTransfer = false;
}
}
currentDigit--;
}
}
var currentCheck = true;
for (int i = 0; i < dicesCount; i++)
{
if (indexes[i] == dice) continue;
currentCheck = false;
break;
}
if (currentCheck)
checkFinish = true;
index++;
}
foreach (var value in max)
{
if (value >= target)
{
goodCaseCount++;
}
}
return (float)goodCaseCount / allPossibilies;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment