как узнать, есть ли 1 или 2 покерные пары в руке в C - PullRequest
0 голосов
/ 07 апреля 2020

Я пытаюсь разработать программу C, которая проверяет наличие 1 или 2 пар в 5-карточной покерной руке.

Я использую массив 5x3, где каждая строка - карточка (3-й столбец для символа \ 0). Каждый раз, когда я выполняю код, он всегда показывает печать «две пары».

Я хочу убедиться, что каждая буква (i, j, a, b), представляющая каждую строку, отличается. Любая помощь?

PS: Это для проекта университета / колледжа, я только начал программировать всего несколько месяцев go с нуля, поэтому любые подробные объяснения моих ошибок будут очень признательны :)

#include <stdio.h>
#include <stdlib.h>

char (cards[5][3])=
{
    "5S", "6D", "4H", "KD", "5C"
};

int main ()
{
    pair (cards[5][3]);
    return 0;
}

void pair (char (arg[n][0]))
{
    int i,j,a,b;

    if (i!=j!=a!=b)
    {
        if ((arg[i][0]==arg[a][0])&&(arg[b][0]!=arg[j][0]))
        {
            printf("2 -> pair");
        }

        if ((arg[i][0]==arg[a][0])&&(arg[b][0]==arg[j][0]));
        {
            printf("3 -> two pairs");
        }

        if ((arg[i][0]!=arg[a][0])&&(arg[b][0]!=arg[j][0]))
        {
            printf("there is no pair");
        }
    }
    else
    {
        printf("there is no pair");
    }
}

Ответы [ 2 ]

1 голос
/ 07 апреля 2020

В опубликованном коде есть несколько проблем, как логических, так и синтаксических, некоторые из них были указаны в комментариях.

Просто чтобы выбрать одну, рассмотрите эту строку

if ((arg[i][0]==arg[a][0])&&(arg[b][0]==arg[j][0]));
{
     // This body will never be executed           ^
}

Я бы Предлагаю перезагрузить с нуля и приступить к работе небольшими шагами. См., Например, следующую минимальную реализацию

// Include all the needed header files, not the unneeded ones.
#include <stdio.h>

// Declare the functions prototype before their use, they will be defined after.
int count_pairs(int n, char const cards[][3]);
// Always specify the inner size,         ^  when passing a multidimensional array
void show_score(int n_pairs);
int have_the_same_value(char const *a, char const *b);

int main (void)
{
    char hand[5][3] = {
    //       ^^^^^^ You could omit the 5, here
        "5S", "6D", "4H", "KD", "5C"
    };

    int n_pairs = count_pairs(5, hand);
    // Always pass the size   ^ if there isn't a sentinel value in the array

    show_score(n_pairs);
    return 0;
}

// This is a simple O(n^2) algorithm. Surely not the best, but it's
// a testable starting point. 
int count_pairs(int n, char const cards[][3])
{
    // Always initialize the variables.
    int count = 0;

    // Pick every card...
    for (int i = 0; i < n; ++i)
    {
        // Compare (only once) with all the remaining others.
        for (int j = i + 1; j < n; ++j)
        { //         ^^^^^
            if ( have_the_same_value(cards[i], cards[j]) ) {
                ++count;
            }
        }
    }
    return count;
}

int have_the_same_value(char const *a, char const *b)
{
    return a[0] == b[0];
}

// Interpret the result of count_pairs outputting the score
void show_score(int n_pairs)
{
    switch (n_pairs)
    {
        case 1:
            printf("one pair.\n");
            break;
        case 2:
            printf("two pairs.\n");
            break;
        case 3:
            printf("three of a kind.\n");
            break;
        case 4:
            printf("full house.\n");
            break;
        case 6:
            printf("four of a kind.\n");
            break;
        default:
            printf("no pairs.\n");
    }
}

Обратите внимание, что моя count_pairs функция считает каждую возможную пару , поэтому, если вы передадите три карты одного вида, она вернется 3 (учитывая A C, AS, AD, все возможные пары: A C AS, A C AD, AS AD).

Как правильно рассчитать все покерные ряды оставлены читателю.

0 голосов
/ 07 апреля 2020

Можно сделать серьезные улучшения в парной функции, чтобы сделать ее стройнее. Тем не менее, это отвечает на ваши вопросы и решает несколько угловых случаев:

#include <stdio.h>
#include <stdlib.h>

void pairCheck(char hand[][2])
{
    int pairCount = 0;
    int tmpCount = 0;
    char tmpCard = '0';
    char foundPairs[2] = {0};

    // Check Hand One
    for(int i =0; i < 5; i++)
    {
        tmpCard = hand[i][0];
        for(int j = 0; j < 5; j++)
        {
            if(tmpCard ==  hand[j][0] && i != j)
            {

                tmpCount++;
            }

            if(tmpCount == 1 && (tmpCard != foundPairs[0] && tmpCard != foundPairs[1]))
            {
                foundPairs[pairCount] = tmpCard;
                pairCount++;
            }

            tmpCount = 0;
        }
    }

    printf("Pair Count Hand One: %i\r\n",pairCount);

    //Reset Variables
    foundPairs[0] = 0;
    foundPairs[1] = 0;
    tmpCard = '0';
    pairCount = 0;
        // Check Hand One
    for(int i =0; i < 5; i++)
    {
        tmpCard = hand[i][1];
        for(int j = 0; j < 5; j++)
        {
            if(tmpCard ==  hand[j][1] && i != j)
            {
                tmpCount++;
            }

            if(tmpCount == 1 && (tmpCard != foundPairs[0] && tmpCard != foundPairs[1]))
            {
                foundPairs[pairCount] = tmpCard;
                pairCount++;
            }

            tmpCount = 0;
        }
    }

    printf("Pair Count Hand Two: %i",pairCount);
}

int main ()
{
    char cards[5][2] = { {'5','H'},{'6','D'},{'4','H'},{'K','D'},{'5','C'}};
    pairCheck(cards);
    return 0;
}

Эта функция будет рассматривать три, четыре или пять одинаковых пар. Если вы хотите другого поведения, изменение должно быть легким.

...