首页 > 解决方案 > 如何在 n 个骰子中找到最高的一对(两个骰子)。c代码

问题描述

如果我作为示例角色 5 骰子,其值为 2 4 4 5 2,则代码将显示“你得分:4”。

我如何获得骰子中最高的一对?

这是代码的一部分。

void Pairs(int n, char* Lower_score1, int* dies)
{
  int i, j;

  printf("Pairs:\t");

  roll_multiple_dies(n, dies);
  for ( i = 0; i < n; i++)
  {
    for ( j = 0; j < n; j++)
    {
      if (dies[i] == dies[j] && j != i)
        Lower_score1[0] += dies[i] && dies[j];
    }
  }
  printf(" You scored: %d\n", Lower_score1[0]);
} 

标签: cc89

解决方案


我假设这roll_multiple_dies(n, dies);将用卷填充数组n。然后执行以下操作:

roll_multiple_dies(n, dies);
int cnt_arr[7] = { 0 };
for(i=0; i<n; ++i)
{
    ++cnt_arr[dies[i]];  // Count the number of times each roll result appear
}

然后检查最高的一对。

“蛮力”方式:

if (cnt_arr[6] >= 2) puts("12");
else if (cnt_arr[5] >= 2) puts("10");
else ...
...
else if (cnt_arr[1] >= 2) puts("2");
else puts("No pairs found");

推荐阅读