C++ to achieve N dice counting algorithm

  • 2020-04-02 02:47:17
  • OfStack

In this paper, the example of C++ to achieve N dice counting algorithm, to share for your reference. Specific methods are as follows:

They say: put n dice on the ground, all the points

The implementation code is as follows:


#include <iostream>

using namespace std;

const int g_maxValue = 6;
const int number = 6;

int array[(number - 1) * g_maxValue + 1];

void probility(int original, int current, int sum, int *array)
{
 if (current == 0)
 {
 array[sum - original]++;
 return;
 }

 for (int i = 1; i <= g_maxValue; i++)
 {
 probility(original, current - 1, sum + i, array);
 }
}

void generateValue(int *array, int size)
{
 if (array == NULL || size <= 0)
 return;

 for (int i = number; i <= number * g_maxValue; i++)
 {
 array[i - number] = 0;
 }

 probility(number, number, 0, array);

 for (int i = 0; i < (number - 1) * g_maxValue + 1; i++)
 {
 cout << array[i] << " ";
 }
}

void main()
{
 generateValue(array, (number - 1) * g_maxValue + 1);
}

The circular solution is essentially the same as the code above, but slightly different.

The specific implementation code is as follows:


#include <iostream>

using namespace std;

void PrintProbability(int number)
{
 const int g_maxValue = 6;

 int *array[2];
 for (int i = 0; i < 2; i++)
 {
 array[i] = new int[g_maxValue * number];
 }

 for (int i = 0; i < g_maxValue * number; i++)
 {
 array[0][i] = 0;
 array[1][i] = 0;
 }
 
 int flag = 0;
 for (int i = 0; i < g_maxValue; i++)
 {
 array[flag][i] = 1;
 }

 for (int i = 1; i < number; i++)
 {
 for (int j = 0; j < i; j++)
  array[1 - flag][j] = 0;
 for (int j = i; j < (i + 1) * g_maxValue; j++)
 {
  array[1 - flag][j] = 0;
  for (int k = 1; k <= j && k <= g_maxValue; k++)
  array[1 - flag][j] += array[flag][j - k];
 }

 flag = 1 - flag;
 }

 for (int i = number - 1; i < g_maxValue * number; i++)
 {
 cout << array[flag][i] << " ";
 }
}

void main()
{
 PrintProbability(2);
}

Hope that this article is helpful to the learning of C++ programming algorithm design.


Related articles: