/* * population.cpp * * Created on: Oct 12, 2010 * Author: mike * for use in Yale course CPSC 427a, Fall 2010 */ #include "population.hpp" Population::Population(Algorithm alg, int numPlayers) : alg(alg), numPlayers(numPlayers), numOnes(0) { player = new Player*[numPlayers]; for (int k = 0; k < numPlayers; k++) { switch (alg) { case fickleAlg: player[k] = new FicklePlayer(); break; case crowdAlg: player[k] = new CrowdPlayer(); break; default: fatal("Bad value of p.alg"); } } } Population::~Population() { for (int k = 0; k < numPlayers; k++) { delete player[k]; } delete [] player; } void Population::reset() { numOnes = 0; for (int k = 0; k < numPlayers; k++) { int preference = k & 1; player[k]->setPreference(preference); if (preference == 1) numOnes++; } } // Performs an update for the chosen sender-receiver pair. // Only the receiver can change its choice. // Invariant: numOnes == sum_k player[k].getChoice(). void Population::oneStep(int sender, int receiver) { int msg = player[sender]->getChoice(); int oldChoice = player[receiver]->getChoice(); player[receiver]->receive(msg); int newChoice = player[receiver]->getChoice(); numOnes += newChoice - oldChoice; } ostream& Population::print(ostream& out) const { out << "[Population:\n"; out << " algorithm=" << ((alg == fickleAlg) ? "fickle" : "crowd") << endl; out << " numPlayers=" << numPlayers << "\n"; out << " numOnes=" << numOnes << "\n"; out << "End Population]" << endl; return out; }