HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Probabilistic matchmaking simulation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
probabilisticmatchmakingsimulation

Problem

The following is a problem I found on this wiki. What can I do to optimize my algorithm, and make this code more C++11?


Write a program to discover the answer to this puzzle:"Let's say men
and women are paid equally (from the same uniform distribution). If
women date randomly and marry the first man with a higher salary, what
fraction of the population will get married?"

#include 
#include 
#include 
#include 
//#include 

using std::cin;
using std::cout;
using std::endl;
using std::random_shuffle;

const int MIN = 1;
const int MAX = 1000000;
const int MALES = 100;
const int FEMALES = 100;

class Female{
public:
    Female(){isMarried = false;}

    bool isMarried;
    int salary;
};

class Male{
public:
    Male(){isMarried = false;}

    bool isMarried;
    int salary;
};

void marriageTest(std::vector &results){

    double count = 0;
    bool done = false;

    Male male[MALES];
    Female female[FEMALES];

    //Fill array of Females and Males with random salaries ranging from 1 to 10
    for(int i=0; i maxMen && !male[i].isMarried)
                maxMen = male[i].salary;
        }

        //Check for Minimum Female Salary
        int minWomen = MAX;
        for(int i=0; i &results){

    for(int i=0; i &results){

    double final = 0;
    int trials = 0;
    for(auto i : results){
        final += i;
        ++trials;
    }

    return final/trials;
}

int main()
{
    int num_trials;
    std::vector results;

    srand(time(NULL));

    cout > num_trials;

    runTrials(num_trials,results);

    double final = Percentage(results);

    cout << "Percentage: " << final << endl;

    return 0;
}

Solution

-
There doesn't seem to be a need for separate Male and Female structures as they hold the same exact data. Instead, just have one named Person and create male and female instances of it.

You also don't need classes if you're not going to have any private data; just use structs.

struct Person
{
    bool isMarried;
    int salary;

    Person() : isMarried(false) {}
};


Person males[MALES];
Person females[FEMALES];


-
Regarding the use of C++11, you can start by removing both std::srand() and std::rand() and replacing them with functionality from the ` library, particularly std::shuffle()`.

Code Snippets

struct Person
{
    bool isMarried;
    int salary;

    Person() : isMarried(false) {}
};
Person males[MALES];
Person females[FEMALES];

Context

StackExchange Code Review Q#65051, answer score: 8

Revisions (0)

No revisions yet.