Callback Function

  1. After cards are dealt to four players, each player get 13 cards.
  2. Write a function to sort those 13 cards in the hand of each player.
  3. Try to write a function to sort by suit, and another function to sort by rank.
  4. You should utilize the standard qsort() library. As long as you prepare the correct callback function, this should be easy.
  5. The main program is given. You only need to design cmp1() and cmp2().
    #include <iostream>
    using std::cout;
    
    void print_card(int n) {
        const char* suit[] = { "♣", "♦", "♥", "♠" };
        const char rank[] = "23456789TJQKA";
        const char* RED    = "\x1b[31m";
        const char* GREEN  = "\x1b[32m";
        const char* NORMAL = "\x1b[m";
        int s = n / 13;
        int r = n % 13;
        cout << (s==1||s==2?RED:GREEN)
            << suit[s] << rank[r] << NORMAL << ' ';
    }
    
    void shuffle(int* a, int n) {
        int i, j, temp;
        for (i=n-1; i>=1; --i) {
            j = rand() % (i+1);
            temp = *(a+i);
            *(a+i) = *(a+j); // a[i] = a[j]
            *(a+j) = temp;
        }
    }
    
    int main()
    {
        int card[52];
        for (int i=0; i<52; ++i)
            card[i]=i;
        shuffle(card, 52);
    
        for (int i=0; i<4; ++i)
            qsort(card+i*13, 13, sizeof(card[0]), cmp1);
        for (int i=0; i<4; ++i) {
            for (int j=i*13; j<(i+1)*13; ++j)
                print_card(card[j]);
            cout << '\n';
        }
        cout << '\n';
    
        for (int i=0; i<4; ++i)
            qsort(card+i*13, 13, sizeof(card[0]), cmp2);
        for (int i=0; i<4; ++i) {
            for (int j=i*13; j<(i+1)*13; ++j)
                print_card(card[j]);
            cout << '\n';
        }
    
        return 0;
    }
    
    
  6. Q: When sorted by suit, if I don't want diamonds and hearts are contiguous (because that will be easy to mix up), how should I design my compare function?