Midterm Practice Question Solutions

  1. Suppose lst is a vector<string>. Re-write the following code using a C-style for-loop with an index variable:

    for(string& s : lst) {
        cout << s << "\n";
    }
    

    Sample solution:

    for(int i = 0; i < lst.size(); ++i) {
       cout << lst[i] << "\n";
    }
    
  2. Consider the following code fragment:

    void example() {
        vector<float*> nums = {new float(1),
                               new float(2),
                               new float(3)
                              };
    
        // ... code that uses nums ...
    }
    

    Add a fragment of code to example() that ensures there are no memory leaks due to the values nums points to.

    Sample solution:

    for(float* p : nums) {
       delete p;
    }
    
  3. Suppose 4 friends are playing 7-card poker. What is the probability that one of them is dealt a hand with all 4 aces?

    While you could solve this problem purely mathematically, don’t do it that way here. Instead, simulate shuffling a deck of cards and dealing 4 7-card hands, and then check each hand to see if one contains all 4 aces.

    Repeat this, say, a million times, and keep a count of how many times someone gets 4 aces. Divide the final count by a million to get an estimate of the probability of getting four aces.

    Sample solution:

    #include "error.h"
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <ctime>
    
    using namespace std;
    
    // 0, 1, 2, and 3 are the aces
    bool is_ace(int c) {
        return 0 <= c && c <= 3;
    }
    
    // Returns true just when all the aces appear in cards[begin], ...
    // cards[end-1].
    bool has_four_aces(const vector<int>& cards, int begin, int end) {
        int count = 0;
        for(int i = begin; i < end; ++i) {
            if (is_ace(cards[i])) {
                count++;
            }
        }
        return count == 4;
    }
    
    int main() {
        // initialize random number generator based on time
        srand(time(NULL));
    
        // create the deck of cards, values 0 to 51
        vector<int> cards(52);
        for(int i = 0; i < cards.size(); ++i) {
            cards[i] = i;
        }
    
        const int NUM_TRIES = 10000000;
        int count = 0;
        for(int tries = 1; tries <= NUM_TRIES; ++tries) {
            random_shuffle(cards.begin(), cards.end());
            if (has_four_aces(cards, 0, 7)   || has_four_aces(cards, 7, 14) ||
                has_four_aces(cards, 14, 21) || has_four_aces(cards, 21, 28))
            {
                count++;
            }
            if (tries % 1000000 == 0)
                cout << "tries = " << tries
                     << " of " << NUM_TRIES
                     << "\n";
        }
    
        cout << "Probability: "
             << count << " / " << NUM_TRIES << " = "
             << double(count) / NUM_TRIES
             << "\n";
    }