Question

In: Computer Science

How do I make a template functions for these 2 functions to prevent code duplication These...

How do I make a template functions for these 2 functions to prevent code duplication

These are the 2 functions

1st:

virtual Card lead_card(const std::string &trump) {
    
        int numOfTrump = 0;
        for (int i = 0; i < int(hand.size()); ++i) {
            if (hand[i].is_trump(trump) == true) {
                numOfTrump += 1;
            }
        }
    
        if (numOfTrump != int(hand.size())) {
            Card c = highestCardNotIncludingTrump(hand, trump);
            int indexOfHighest = 0;
            for (int i = 0; i < int(hand.size()); ++i) {
                if (c == hand[i]) {
                    indexOfHighest = i;
                }
            }
            hand.erase(hand.begin() + indexOfHighest);
            cout << c << " led by " << get_name() << endl;

            return c;
        }
        else {
            Card c = highestCardIncludingTrump(hand, trump);
            int indexOfHighest = 0;
            for (int i = 0; i < int(hand.size()); ++i) {
                if (c == hand[i]) {
                    indexOfHighest = i;
                }
            }
            hand.erase(hand.begin() + indexOfHighest);
            cout << c << " led by " << get_name() << endl;
        
            return c;
        }
    }

2nd code:

virtual Card play_card(const Card &led_card, const std::string &trump) {
        int numLedSuitCards = 0;
        string ledCardSuit = led_card.get_suit();
    
        if (led_card.is_trump(trump) || led_card.is_left_bower(trump)) {
            for (int i = 0; i < int(hand.size()); ++i) {
                if (hand[i].is_trump(trump) == true) {
                    numLedSuitCards += 1;
                }
            }
        }
        else {
            for (int i = 0; i < int(hand.size()); ++i) {
                if (hand[i].get_suit() == ledCardSuit && !(hand[i].is_left_bower(trump))) {
                    numLedSuitCards += 1;
                };
            }
        }
    
        if (numLedSuitCards > 0) {
            Card c = highestCardFollowingSuit(hand, led_card, trump);
            int indexOfHighest = 0;
            for (int i = 0; i < int(hand.size()); ++i) {
                if (c == hand[i]) {
                    indexOfHighest = i;
                }
            }
            hand.erase(hand.begin() + indexOfHighest);
            cout << c << " played by " << get_name() << endl;
        
            return c;
        }
        else {
            Card c = lowestCardIncludingTrump(hand, trump);
            int indexOfLowest = 0;
            for (int i = 0; i < int(hand.size()); ++i) {
                if (c == hand[i]) {
                    indexOfLowest = i;
                }
            }
            hand.erase(hand.begin() + indexOfLowest);
            cout << c << " played by " << get_name() << endl;

            return c;
        }

Solutions

Expert Solution

This can be templatised as follows:

template<typename T>
Card lead_card(const T& trump) {

int numOfTrump = 0;
for (int i = 0; i < int(hand.size()); ++i) {
if (hand[i].is_trump(trump) == true) {
numOfTrump += 1;
}
}

if (numOfTrump != int(hand.size())) {
Card c = highestCardNotIncludingTrump(hand, trump);
int indexOfHighest = 0;
for (int i = 0; i < int(hand.size()); ++i) {
if (c == hand[i]) {
indexOfHighest = i;
}
}
hand.erase(hand.begin() + indexOfHighest);
cout << c << " led by " << get_name() << endl;

return c;
}
else {
Card c = highestCardIncludingTrump(hand, trump);
int indexOfHighest = 0;
for (int i = 0; i < int(hand.size()); ++i) {
if (c == hand[i]) {
indexOfHighest = i;
}
}
hand.erase(hand.begin() + indexOfHighest);
cout << c << " led by " << get_name() << endl;

return c;
}
}


template<typename T>
Card play_card(const Card & led_card, const T& trump) {
int numLedSuitCards = 0;
string ledCardSuit = led_card.get_suit();

if (led_card.is_trump(trump) || led_card.is_left_bower(trump)) {
for (int i = 0; i < int(hand.size()); ++i) {
if (hand[i].is_trump(trump) == true) {
numLedSuitCards += 1;
}
}
}
else {
for (int i = 0; i < int(hand.size()); ++i) {
if (hand[i].get_suit() == ledCardSuit && !(hand[i].is_left_bower(trump))) {
numLedSuitCards += 1;
};
}
}

if (numLedSuitCards > 0) {
Card c = highestCardFollowingSuit(hand, led_card, trump);
int indexOfHighest = 0;
for (int i = 0; i < int(hand.size()); ++i) {
if (c == hand[i]) {
indexOfHighest = i;
}
}
hand.erase(hand.begin() + indexOfHighest);
cout << c << " played by " << get_name() << endl;

return c;
}
else {
Card c = lowestCardIncludingTrump(hand, trump);
int indexOfLowest = 0;
for (int i = 0; i < int(hand.size()); ++i) {
if (c == hand[i]) {
indexOfLowest = i;
}
}
hand.erase(hand.begin() + indexOfLowest);
cout << c << " played by " << get_name() << endl;

return c;
}

Here the type of the trump can be any thing not needed to be string and corresponding adaptation has to be made in the private functions called within the above functions.


Related Solutions

I am trying to make a new code that uses functions to make it. My functions...
I am trying to make a new code that uses functions to make it. My functions are below the code. <?php */ $input; $TenBills = 1000; $FiveBills = 500; $OneBills = 100; $Quarters = 25; $Dimes = 10; $Nickels = 5; $Pennies = 1; $YourChange = 0; $input = readline("Hello, please enter your amount of cents:\n"); if(ctype_digit($input)) { $dollars =(int)($input/100); $cents = $input%100;    $input >= $TenBills; $YourChange = (int)($input/$TenBills); $input -= $TenBills * $YourChange; print "Change for $dollars dollars...
PDCA template and how to do it for financial. have to make a template of our...
PDCA template and how to do it for financial. have to make a template of our own thing. i was gonna do financial.
How do I make this code print the st variable rounded to 2 decimal places? Everything...
How do I make this code print the st variable rounded to 2 decimal places? Everything I have tried gives me an error. print('Enter output filename') name=input() print('Enter principal amount') p=float(input()) print('Enter term length (month)') n=int(input()) print('Enter annual interest') i=float(input()) j=i/12 m=p*j/(1-(1+j)**-n) file = open(name, "w") title = ["Month, ", "Total Accured interest, ", "Loan Balance \n"] file.writelines(title) first_row=["0",",","$","0.00",",","$",p," \n"] s1=' '.join([str(elem) for elem in first_row]) file.writelines(s1) t=0 for j in range(n): tai=(p*i/12) t=t+tai p=(p-m)+tai st="" ls=[j+1,",","$",t,",","$",p,"\n"] st=''.join([str(elem) for elem...
C++ Hello .I need to convert this code into template and then test the template with...
C++ Hello .I need to convert this code into template and then test the template with dynamic array of strings also if you can help me move the function out of the class that would be great.also There is a bug where the memory was being freed without using new operator. I cant seem to find it thanks in advance #include using namespace std; class DynamicStringArray {    private:        string *dynamicArray;        int size;    public:   ...
How do I make the series graph
How do I make the series graph
C++ Please write a exmaple of class template RedBlackTree.h.(It must be template!). I do not mind...
C++ Please write a exmaple of class template RedBlackTree.h.(It must be template!). I do not mind about details but please include the basic functions that are necessary for a RedBlackTree.
Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
How would I make it so that when I run my code it does not ask...
How would I make it so that when I run my code it does not ask for input (not having to enter after the statement and enter 0 for example) after ROXY (Forever ROXY Enterprises) appears? Like it would tell me the second statement right away along with the Roxy phrase. This is in C++. My code: #include / #include using std::endl; int main() {    void readAndConvert();    unsigned int stockSymbol;    unsigned int confNum;    std::cout << "ROXY...
do you think there is a way to prevent a gene from expressing the code for...
do you think there is a way to prevent a gene from expressing the code for the cancer or are we doom to have cancer since we can’t prevent it
How can I edit this C code to make sure that the letter P and L...
How can I edit this C code to make sure that the letter P and L would show up separately one at a time on an interval of one second on a raspberry pi? 1 #include <stdio.h> 2 #include <unistd.h> 3 #include "sense.h" 4 5 #define WHITE 0xFFFF 6 7 int main(void) { 8     // getFrameBuffer should only get called once/program 9     pi_framebuffer_t *fb=getFrameBuffer(); 10     sense_fb_bitmap_t *bm=fb->bitmap; 11 12      bm->pixel[0][0]=WHITE; 13      bm->pixel[0][1]=WHITE; 14      bm->pixel[0][2]=WHITE; 15      bm->pixel[0][3]=WHITE; 16      bm->pixel[0][4]=WHITE; 17      bm->pixel[0][5]=WHITE;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT