Search code examples
cc89

How do I find the highest pair(two dices) among n amount of dice. c code


If I as an example role 5 dice with the values 2 4 4 5 2 the code will spit out "You scored: 4".

How do I get the highest pair among the dice?

Here is a part of the code.

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]);
} 

Solution

  • I assume that roll_multiple_dies(n, dies); will fill an array with n rolls. Then do something like:

    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
    }
    

    Then check for the highest pair.

    The "brute force" way:

    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");