コード例 #1
0
int main() {
	std::string line;

	Events events;

	while (std::getline(std::cin, line)) {
		std::vector<std::string> elements;
		boost::split(elements, line, boost::is_any_of("/"));
		if (elements.size() != 4) {
			std::cerr << "Warning: elements.size() != 4" << std::endl;
			continue;
		}
		Event e;
		e.player = elements[0];
		e.map = elements[1];
		e.lapTime = parseLapTime(elements[2]);
		e.date = parseDate(elements[3]);

		events.push_back(e);
	}

	std::cout << "Number of events: " << events.size() << std::endl;

	std::sort(events.begin(), events.end());

	std::cout << "Last event: " << events.back() << std::endl;

	Ranking ranking = getRankings(events, boost::posix_time::time_from_string("2014-01-03 22:00:00.000"));
	for ( unsigned i = 0; i < 20 && i < ranking.size(); ++i ) {
		std::cout << i+1 << ".: " << ranking[i].getPlayer() << ", Time: " << ranking[i].getTotalLapTime() << std::endl;
	}

	std::cout << "Current leader = " << ranking[0].getTotalLapTime() << std::endl;
}
コード例 #2
0
ファイル: MOCHC.cpp プロジェクト: cristianzambrano/jMetalCpp
SolutionSet *MOCHC::rankingAndCrowdingSelection(SolutionSet * pop, int size) {


    SolutionSet *result = new SolutionSet(size);
    // Ranking the union
    Ranking * ranking = new Ranking(pop);    
    Distance * distance = new Distance();
    int remain = size;
    int index = 0;
    SolutionSet * front = NULL;

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());

      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        result->add(new Solution(front->get(k)));
      } // for

      //Decrement remain
      remain = remain - front->size();

      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
      
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        result->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete distance;

    return result;	
}
コード例 #3
0
ファイル: Principal.cpp プロジェクト: alex2992/granota
int main()
{
	char opcio;
	int punts;
	int posicio = -1;
	char nivell = '1';
	Ranking ranking = Ranking();
	Jugador nouJugador;
	int filaGotoXY=9;

	do
	{
		mostraMenuPrincipal();
		opcio = _getch(); // Llegeix tecla apretada
		switch (opcio)
		{
			case OPCIO_JUGAR:
			
				punts = juga(nivell-'0'); // COMPTE!: aquí hi ha una conversió de char a int
				nouJugador = Jugador(punts);
				if (ranking.afegirJugador(nouJugador))
					cout << "\n Enhorabona!!! Has entrat al ranking dels " << MAX_JUGADORS << "millors jugadors!!\n";
				else
					cout << "\n Llàstima! No has pogut entrar al ranking dels " << MAX_JUGADORS << "millors jugadors. \n";
				break;
			case OPCIO_CONFIGURAR:
				do
				{
					mostraMenuNivellDificultat();
					nivell = _getch(); // Llegeix tecla apretada
					if ((nivell != '1') && (nivell != '2') && (nivell != '3')) // Comprova si tecla es valida
					{
						cout << "Opcio incorrecta.\n"; // Mostra text
						
					}
				} while ((nivell != '1') && (nivell != '2') && (nivell != '3')); // Repeteix mentre tecla no valida
				break;
			case OPCIO_PUNTUACIO:
				ranking.mostrar();
				cout << "Prem una tecla per tornar al menu principal";
				_getch(); // Llegeix tecla apretada
				break;
		}
	} while (opcio != OPCIO_SORTIR);
	
	return 1;
}
コード例 #4
0
ファイル: ValidatorAPI.cpp プロジェクト: KCL-Planning/ROSPlan
void executePlan (std::stringstream& plan_to_validate, TypeChecker & tc, const DerivationRules * derivRules, double tolerance, bool lengthDefault, bool giveAdvice)
{
	Ranking rnk;
	Ranking rnkInv;
	vector<string> failed;
	vector<string> queries;

	std::string name = "The master plan";

	plan * the_plan = getPlan (plan_to_validate, tc, failed, name);
	if (the_plan == 0) return;

	plan * copythe_plan = new plan (*the_plan);
	plan * planNoTimedLits = new plan();
	vector<plan_step *> timedInitialLiteralActions = getTimedInitialLiteralActions();
	double deadLine = 101;

	//add timed initial literals to the plan from the problem spec
	for (vector<plan_step *>::iterator ps = timedInitialLiteralActions.begin(); ps != timedInitialLiteralActions.end(); ++ps)
	{
		the_plan->push_back (*ps);
	};

	//add actions that are not to be moved to the timed intitial literals otherwise to the plan to be repaired
	//i.e. pretend these actions are timed initial literals
	for (pc_list<plan_step*>::const_iterator i = copythe_plan->begin(); i != copythe_plan->end(); ++i)
	{
		planNoTimedLits->push_back (*i);
	};

	copythe_plan->clear(); delete copythe_plan;

	PlanRepair pr (timedInitialLiteralActions, deadLine, derivRules, tolerance, tc, an_analysis.the_domain->ops,
	               an_analysis.the_problem->initial_state,
	               the_plan, planNoTimedLits, an_analysis.the_problem->metric, lengthDefault,
	               an_analysis.the_domain->isDurative(), an_analysis.the_problem->the_goal, current_analysis);

	if (Verbose)
		pr.getValidator().displayPlan();



	try
	{

		if (pr.getValidator().execute())
		{
			if (!Silent) cout << "Plan executed successfully - checking goal\n";

			if (pr.getValidator().checkGoal (an_analysis.the_problem->the_goal))

			{
				if (! (pr.getValidator().hasInvariantWarnings()))
				{
					rnk[pr.getValidator().finalValue() ].push_back (name);
					if (!Silent) *report << "Plan valid\n";
					if (!Silent) *report << "Final value: " << pr.getValidator().finalValue() << "\n";
				}
				else
				{
					rnkInv[pr.getValidator().finalValue() ].push_back (name);
					if (!Silent) *report << "Plan valid (subject to further invariant checks)\n";
					if (!Silent) *report << "Final value: " << pr.getValidator().finalValue();
				};
				if (Verbose)
				{
					pr.getValidator().reportViolations();
				};
			}
			else
			{
				failed.push_back (name);
				*report << "Goal not satisfied\n";

				*report << "Plan invalid\n";
				++errorCount;
			};

		}
		else
		{
			failed.push_back (name);
			++errorCount;
			if (ContinueAnyway)
			{
				cout << "\nPlan failed to execute - checking goal\n";

				if (!pr.getValidator().checkGoal (an_analysis.the_problem->the_goal)) *report << "\nGoal not satisfied\n";

			}

			else *report << "\nPlan failed to execute\n";


		};

		if (pr.getValidator().hasInvariantWarnings())
		{
			cout << "\n\n";
			*report << "This plan has the following further condition(s) to check:";
			cout << "\n\n";

			pr.getValidator().displayInvariantWarnings();
		};
	}
	catch (exception & e)
	{
		cout << "Error occurred in validation attempt:\n  " << e.what() << "\n";
		queries.push_back (name);

	};

	//display error report and plan repair advice
	if (giveAdvice && (Verbose || ErrorReport))
	{
		pr.firstPlanAdvice();
	};

	planNoTimedLits->clear(); delete planNoTimedLits;
	delete the_plan;

	if (!rnk.empty())
	{
		if (!Silent) cout << "\nSuccessful plans:";


		if (an_analysis.the_problem->metric &&
		    an_analysis.the_problem->metric->opt == E_MINIMIZE)
		{
			if (!Silent) for_each (rnk.begin(), rnk.end(), showList());

		}
		else
		{
			if (!Silent) for_each (rnk.rbegin(), rnk.rend(), showList());
		};



		*report << "\n";
	};

	if (!rnkInv.empty())
	{
		if (!Silent) cout << "\nSuccessful Plans Subject To Further Invariant Checks:";


		if (an_analysis.the_problem->metric &&
		    an_analysis.the_problem->metric->opt == E_MINIMIZE)
		{
			for_each (rnkInv.begin(), rnkInv.end(), showList());
		}
		else
		{
			for_each (rnkInv.rbegin(), rnkInv.rend(), showList());
		};



		*report << "\n";
	};

	if (!failed.empty())
	{
		cout << "\n\nFailed plans:\n ";
		copy (failed.begin(), failed.end(), ostream_iterator<string> (cout, " "));
		*report << "\n";
	};

	if (!queries.empty())
	{
		cout << "\n\nQueries (validator failed):\n ";
		copy (queries.begin(), queries.end(), ostream_iterator<string> (cout, " "));
		*report << "\n";
	};

};
コード例 #5
0
ファイル: PlanRec.cpp プロジェクト: Dunes/janitor
//execute all the plans in the usual manner without robustness checking
void executePlans(int & argc,char * argv[],int & argcount,TypeChecker & tc,const DerivationRules * derivRules,double tolerance,bool lengthDefault,bool giveAdvice)
{
  Ranking rnk;
  Ranking rnkInv;
  vector<string> failed;
  vector<string> queries;

	while(argcount < argc)
	{       
      string name(argv[argcount]);

      plan * the_plan = getPlan(argc,argv,argcount,tc,failed,name);
      if(the_plan == 0) continue;     

      plan * copythe_plan = new plan(*the_plan);
      plan * planNoTimedLits = new plan();
      vector<plan_step *> timedInitialLiteralActions = getTimedInitialLiteralActions();
      double deadLine = 101;

        //add timed initial literals to the plan from the problem spec
       for(vector<plan_step *>::iterator ps = timedInitialLiteralActions.begin(); ps != timedInitialLiteralActions.end(); ++ps)
       {
          the_plan->push_back(*ps);
       };

       //add actions that are not to be moved to the timed intitial literals otherwise to the plan to be repaired
       //i.e. pretend these actions are timed initial literals
       for(pc_list<plan_step*>::const_iterator i = copythe_plan->begin(); i != copythe_plan->end(); ++i)
       {
              planNoTimedLits->push_back(*i);
       };

       copythe_plan->clear(); delete copythe_plan;
       
       PlanRepair pr(timedInitialLiteralActions,deadLine,derivRules,tolerance,tc,current_analysis->the_domain->ops,
	    			current_analysis->the_problem->initial_state,
	    			the_plan,planNoTimedLits,current_analysis->the_problem->metric,lengthDefault,
	    			current_analysis->the_domain->isDurative(),current_analysis->the_problem->the_goal,current_analysis);

		PlanExecutionTracker pet(State(&(pr.getValidator()),current_analysis->the_problem->initial_state),&(pr.getValidator()));
		State::addObserver(&pet);
			
		if(LaTeX)
		{
			latex.LaTeXPlanReport(&(pr.getValidator()),the_plan);
		}
		else if(Verbose)
			pr.getValidator().displayPlan();



	    bool showGraphs = false;


	    try {

		    if(pr.getValidator().execute())
		    {
		    	if(LaTeX)
		    		*report << "Plan executed successfully - checking goal\\\\\n";
		    	else
		    		if(!Silent) cout << "Plan executed successfully - checking goal\n";

		    	if(pr.getValidator().checkGoal(current_analysis->the_problem->the_goal))

		    	{
		    		if(!(pr.getValidator().hasInvariantWarnings()))
		    		{
		    			rnk[pr.getValidator().finalValue()].push_back(name);
		    			if(!Silent && !LaTeX) *report << "Plan valid\n";
		    			if(LaTeX) *report << "\\\\\n";
		    			if(!Silent && !LaTeX) *report << "Final value: " << pr.getValidator().finalValue() << "\n";
		    		}
		    		else
		    		{
						rnkInv[pr.getValidator().finalValue()].push_back(name);
		    			if(!Silent && !LaTeX) *report << "Plan valid (subject to further invariant checks)\n";
		    			if(LaTeX) *report << "\\\\\n";
		    			if(!Silent && !LaTeX) *report << "Final value: " << pr.getValidator().finalValue();
		          };
		          	if(Verbose)
		          	{
		          		pr.getValidator().reportViolations();
		          	};
		    	}
		    	else
		    	{
		    		failed.push_back(name);
		    		*report << "Goal not satisfied\n";

		    		if(LaTeX) *report << "\\\\\n";
		    		*report << "Plan invalid\n";
				++errorCount;
			};

		    }
		    else
		    {
		    	failed.push_back(name);
			++errorCount;
         		    	if(ContinueAnyway)
                  {
                     if(LaTeX) *report << "\nPlan failed to execute - checking goal\\\\\n";
                     else cout << "\nPlan failed to execute - checking goal\n";

                     if(!pr.getValidator().checkGoal(current_analysis->the_problem->the_goal)) *report << "\nGoal not satisfied\n";

         		    }

                 else *report << "\nPlan failed to execute\n";


        };

              if(pr.getValidator().hasInvariantWarnings())
              {
						if(LaTeX)
							*report << "\\\\\n\\\\\n";
						else
							cout << "\n\n";


		    			*report << "This plan has the following further condition(s) to check:";

						if(LaTeX)
							*report << "\\\\\n\\\\\n";
						else
							cout << "\n\n";

						pr.getValidator().displayInvariantWarnings();
		    		};

		    if(pr.getValidator().graphsToShow()) showGraphs = true;
		    cout << pet;
		}
		catch(exception & e)
		{
			if(LaTeX)
			{
				*report << "\\error \\\\\n";
				*report << "\\end{tabbing}\n";
				*report << "Error occurred in validation attempt:\\\\\n  " << e.what() << "\n";
			}
			else
				cout << "Error occurred in validation attempt:\n  " << e.what() << "\n";

			queries.push_back(name);

		};

    //display error report and plan repair advice
      if(giveAdvice && (Verbose || ErrorReport))
     {
            pr.firstPlanAdvice();
      };

      //display LaTeX graphs of PNEs
    		if(LaTeX && showGraphs)
		{
			latex.LaTeXGraphs(&(pr.getValidator()));
		};

    //display gantt chart of plan
		if(LaTeX)
		{
			latex.LaTeXGantt(&(pr.getValidator()));

		};

    planNoTimedLits->clear(); delete planNoTimedLits;
    delete the_plan;
	};

	if(!rnk.empty())
	{
		if(LaTeX)
		{
			*report << "\\section{Successful Plans}\n";


		}
		else
			if(!Silent) cout << "\nSuccessful plans:";


		if(current_analysis->the_problem->metric &&
				current_analysis->the_problem->metric->opt == E_MINIMIZE)
		{
			if(LaTeX)
			{
				*report << "\\begin{tabbing}\n";
				*report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n";
			};


			if(!Silent && !LaTeX) for_each(rnk.begin(),rnk.end(),showList());

			if(LaTeX) *report << "\\end{tabbing}\n";

		}
		else
		{
			if(LaTeX)
			{
				*report << "\\begin{tabbing}\n";
				*report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n";
			};


			if(!Silent && !LaTeX) for_each(rnk.rbegin(),rnk.rend(),showList());



			if(LaTeX) *report << "\\end{tabbing}\n";
		};



		*report << "\n";
	};

	if(!rnkInv.empty())
	{
		if(LaTeX)
		{
			*report << "\\section{Successful Plans Subject To Further Checks}\n";

		}
		else

			if(!Silent) cout << "\nSuccessful Plans Subject To Further Invariant Checks:";


		if(current_analysis->the_problem->metric &&
				current_analysis->the_problem->metric->opt == E_MINIMIZE)
		{
			if(LaTeX)
			{
				*report << "\\begin{tabbing}\n";
				*report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n";
			};

			for_each(rnkInv.begin(),rnkInv.end(),showList());

			if(LaTeX) *report << "\\end{tabbing}\n";
		}
		else
		{
			if(LaTeX)
			{
				*report << "\\begin{tabbing}\n";
				*report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n";
			};

			for_each(rnkInv.rbegin(),rnkInv.rend(),showList());

			if(LaTeX) *report << "\\end{tabbing}\n";
		};



		*report << "\n";
	};

	if(!failed.empty())
	{
		if(LaTeX)
		{
			*report << "\\section{Failed Plans}\n";

		}
		else
			cout << "\n\nFailed plans:\n ";

		if(LaTeX)
			displayFailedLaTeXList(failed);
		else
			copy(failed.begin(),failed.end(),ostream_iterator<string>(cout," "));



		*report << "\n";
	};

	if(!queries.empty())
	{
		if(LaTeX)
		{
			*report << "\\section{Queries (validator failed)}\n";

		}
		else
			cout << "\n\nQueries (validator failed):\n ";

		if(LaTeX)
			displayFailedLaTeXList(queries);
		else
			copy(queries.begin(),queries.end(),ostream_iterator<string>(cout," "));



		*report << "\n";
	};

};
コード例 #6
0
/*
 * Runs the ssNSGA-II algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * ssNSGAII::execute() {

  int populationSize;
  int maxEvaluations;
  int evaluations;
  
  int IntervalOptSubsModel;

  // TODO: QualityIndicator indicators; // QualityIndicator object
  int requiredEvaluations; // Use in the example of use of the
                           // indicators object (see below)

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * mutationOperator;
  Operator * crossoverOperator;
  Operator * selectionOperator;

  Distance * distance = new Distance();

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  IntervalOptSubsModel = *(int *) getInputParameter("intervalupdateparameters");
  // TODO: indicators = (QualityIndicator) getInputParameter("indicators");

  //Initialize the variables
  population = new SolutionSet(populationSize);
  evaluations = 0;

  requiredEvaluations = 0;

  //Read the operators
  mutationOperator = operators_["mutation"];
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];
  
  ApplicationTools::displayTask("Initial Population", true);
  
  // Create the initial solutionSet
  Solution * newSolution;
  Phylogeny * p = (Phylogeny *) problem_;
  
  
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    
    if(p->StartingOptRamas){
        p->BranchLengthOptimization(newSolution,p->StartingMetodoOptRamas,p->StartingNumIterOptRamas,p->StartingTolerenciaOptRamas);
    }
    
    if(p->OptimizacionSubstModel)
        p->OptimizarParamModeloSust(newSolution);
       
    
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for
   ApplicationTools::displayTaskDone();
   
   
  // Generations
  while (evaluations < maxEvaluations) {
    
    // Create the offSpring solutionSet
    offspringPopulation = new SolutionSet(populationSize);
    Solution ** parents = new Solution*[2];
    
     if(evaluations%100==0){ 
         cout << "Evaluating  " <<  evaluations << endl;
     }
     
     
    //obtain parents
    parents[0] = (Solution *) (selectionOperator->execute(population));
    parents[1] = (Solution *) (selectionOperator->execute(population));
    
    // crossover
    Solution ** offSpring = (Solution **) (crossoverOperator->execute(parents));
    
    // mutation
    mutationOperator->execute(offSpring[0]);
    
    ((Phylogeny *)problem_)->Optimization(offSpring[0]); //Optimize and update the scores (Evaluate OffSpring)
    
    // evaluation
    //problem_->evaluate(offSpring[0]);
    //problem_->evaluateConstraints(offSpring[0]);
    
    // insert child into the offspring population
    offspringPopulation->add(offSpring[0]);
    
    evaluations ++;
    delete[] offSpring;
    delete[] parents;
    
    // Create the solutionSet union of solutionSet and offSpring
    unionSolution = population->join(offspringPopulation);
    delete offspringPopulation;

    // Ranking the union
    Ranking * ranking = new Ranking(unionSolution);

    int remain = populationSize;
    int index = 0;
    SolutionSet * front = NULL;
    for (int i=0;i<population->size();i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      } // for
      
      //Decrement remain
      remain = remain - front->size();
      
      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        population->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete unionSolution;

       //Update Interval
    if(evaluations%IntervalOptSubsModel==0 and IntervalOptSubsModel > 0){ 
        Solution * sol;  double Lk;
        Phylogeny * p = (Phylogeny*) problem_;
        //cout << "Updating and Optimizing Parameters.." << endl;
        for(int i=0; i<population->size(); i++){
            sol =  population->get(i);
            Lk=  p->BranchLengthOptimization(sol,p->OptimizationMetodoOptRamas,p->OptimizationNumIterOptRamas,p->OptimizationTolerenciaOptRamas);
            sol->setObjective(1,Lk*-1);
        }
        //cout << "Update Interval Done!!" << endl;
    }
    
    // This piece of code shows how to use the indicator object into the code
    // of NSGA-II. In particular, it finds the number of evaluations required
    // by the algorithm to obtain a Pareto front with a hypervolume higher
    // than the hypervolume of the true Pareto front.
// TODO:
//    if ((indicators != NULL) &&
//      (requiredEvaluations == 0)) {
//      double HV = indicators.getHypervolume(population);
//      if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) {
//        requiredEvaluations = evaluations;
//      } // if
//    } // if

  } // while

  delete distance;

  // Return as output parameter the required evaluations
  // TODO:
  //setOutputParameter("evaluations", requiredEvaluations);

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute
コード例 #7
0
ファイル: ssNSGAII.cpp プロジェクト: ajnebro/MO-Phylogenetics
/*
 * Runs the ssNSGA-II algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * ssNSGAII::execute() {

  int populationSize;
  int maxEvaluations;
  int evaluations;

  // TODO: QualityIndicator indicators; // QualityIndicator object
  int requiredEvaluations; // Use in the example of use of the
                           // indicators object (see below)

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * mutationOperator;
  Operator * crossoverOperator;
  Operator * selectionOperator;

  Distance * distance = new Distance();

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  // TODO: indicators = (QualityIndicator) getInputParameter("indicators");

  //Initialize the variables
  population = new SolutionSet(populationSize);
  evaluations = 0;

  requiredEvaluations = 0;

  //Read the operators
  mutationOperator = operators_["mutation"];
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];
  
  // Create the initial solutionSet
  Solution * newSolution;
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for
  
  // Generations
  while (evaluations < maxEvaluations) {
    
    // Create the offSpring solutionSet
    offspringPopulation = new SolutionSet(populationSize);
    Solution ** parents = new Solution*[2];
    
    //obtain parents
    parents[0] = (Solution *) (selectionOperator->execute(population));
    parents[1] = (Solution *) (selectionOperator->execute(population));
    
    // crossover
    Solution ** offSpring = (Solution **) (crossoverOperator->execute(parents));
    
    // mutation
    mutationOperator->execute(offSpring[0]);
    
    // evaluation
    problem_->evaluate(offSpring[0]);
    problem_->evaluateConstraints(offSpring[0]);
    
    // insert child into the offspring population
    offspringPopulation->add(offSpring[0]);
    
    evaluations ++;
    delete[] offSpring;
    delete[] parents;
    
    // Create the solutionSet union of solutionSet and offSpring
    unionSolution = population->join(offspringPopulation);
    delete offspringPopulation;

    // Ranking the union
    Ranking * ranking = new Ranking(unionSolution);

    int remain = populationSize;
    int index = 0;
    SolutionSet * front = NULL;
    for (int i=0;i<population->size();i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      } // for
      
      //Decrement remain
      remain = remain - front->size();
      
      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        population->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete unionSolution;

    // This piece of code shows how to use the indicator object into the code
    // of NSGA-II. In particular, it finds the number of evaluations required
    // by the algorithm to obtain a Pareto front with a hypervolume higher
    // than the hypervolume of the true Pareto front.
// TODO:
//    if ((indicators != NULL) &&
//      (requiredEvaluations == 0)) {
//      double HV = indicators.getHypervolume(population);
//      if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) {
//        requiredEvaluations = evaluations;
//      } // if
//    } // if

  } // while

  delete distance;

  // Return as output parameter the required evaluations
  // TODO:
  //setOutputParameter("evaluations", requiredEvaluations);

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute
コード例 #8
0
ファイル: main.cpp プロジェクト: alan23273850/Chinese_Ten
int main () {

    cout << "==========================Welcome to Chinese Ten!!!!========================\n\n";
    cout << "Loading";
    for(int i=5; i>0; i--){
        Sleep(200*i);
        cout << '.';
    }

    MENU:
    Deck Main, Layout;
    vector<Player> players;
    vector<Player> player_buffer;
    vector<int> order;
    string name;
    Card card;
    string str;
    stringstream strstream;
    Ranking ranking;
    Score score;
    int random, temp;
    int finish = 0;
    int out_of_range=0;
    int player_num=0;
    int computer_num=0;
    int player_index=-1;
    int tie_score=0;
    int check_people=0;
    char menu=0;

    //Initialize
    players.clear();
    players.resize(4);
    player_buffer.clear();
    player_buffer.resize(4);
    order.clear();
    order.resize(4);
    ranking.Clear();

    system("cls");
    cout << "==================================Main Menu=================================\n\n";  
    cout << "(1)Play the game!\n";
    cout << "(2)Check the ranking table.\n";
    cout << "( )Exit.\n";
    menu = getch();
    switch(menu){

        case '1': break;

        case '2':
            system("cls");
            cout << "===================Ranking Table Menu===================\n\n";
            cout << "(2)Two persons\n";
            cout << "(3)Three persons\n";
            cout << "(4)Four persons\n";
            cout << "( )Go back to main menu.\n";
            check_people = getch()-'0';
            if( !(2<=check_people && check_people<=4) )
                goto MENU;
            system("cls");
            cout << "===================Ranking Table Menu===================\n\n";
            cout << "(1)See top 10.\n";
            cout << "(2)Search for somebody's scores.\n";
            cout << "( )Go back to main menu.\n\n";
            menu = getch();
            switch(menu){
                case '1':
                    ranking.FindTop(check_people,10);
                    ranking.Print(10);
                    cout << "\nPress any key to go back to main menu...\n";
                    getch();
                    break;
                case '2':
                    cout << "I want to see <Name>'s scores. Name = ";
                    cin.sync();
                    getline(cin,name);
                    cout << endl;
                    if( ranking.FindByName(check_people,name)==0 )
                        cout << "There is no any " << name << "\'s record.\n";
                    else
                        ranking.Print();
                    cout << "\nPress any key to go back to main menu...\n";
                    getch();
                    break;
                default: break;
            }
            goto MENU;
            break;

        default: exit(EXIT_SUCCESS);
    }

    //Choose the number of players
    do{
        system("cls");
        cout << "Please choose the number of players ( 2-4 people ): ";
        player_num = getche() - '0';
        cout << endl;
        if( !(2<=player_num && player_num<=4) ){
            out_of_range = 1;
            cout << "Sorry, your input is out of range.\n";
            Sleep(1000);
        }
        else
            out_of_range = 0;
    }while( out_of_range==1 );

    //Choose the number of computer players
    cout << endl;
    do{
        for(int i=0; i<=player_num; i++)
            printf("(%d) %d human player(s), %d computer player(s)\n",i,player_num-i,i);
        cout << "\nMake a choice for the players' property. I want to choose ";
        computer_num = getche()-'0';
        cout << '.' << endl;
        if( !(0<=computer_num && computer_num<=player_num) ){
            out_of_range = 1;
            cout << "Sorry, your input is out of range.\n\n";
        }
        else
            out_of_range = 0;
    }while( out_of_range==1 );

    //Input the names.
    cout << "\nGive the players\' names!!\n\n";
    for(int i=0; i<player_num; i++){
        cout << "PLAYER" << ": ";
        cin.sync();
        name="";
        if( i<computer_num ){
            name = "COMPUTER_";
            name += (i+1+'0');
            cout << name << endl;
            players.at(i).EnableComputer();
        }
        else
            getline(cin,name);
        if( name == "" ){
            name = "PLAYER_";
            name += (i+'A');
        }
        players.at(i).SetName(name);
    }

    //Use clock to initialize the seed.
    srand(time(NULL));

    //Replicate a player to a buffer and set order = {0,1,2,3}.
    for(int i=0; i<player_num; i++){
        order.at(i) = i;
        player_buffer.at(i) = players.at(i);
    }

    //Rearrange(randomize) the array "order."
    for(int i=0; i<player_num; i++){
        random = rand() % player_num;
        temp = order.at(i);
        order.at(i) = order.at(random);
        order.at(random) = temp;
    }

    //Put the players in the buffer into the original player based on the randomized order.
    for(int i=0; i<player_num; i++)
        players.at(i) = player_buffer.at(order.at(i));

    //Print the rearraged player's order.
    system("cls");
    cout << "The playing order is:\n\n";
    for(int i=0; i<player_num; i++)
        cout << "Player" << i+1 << ": " << players.at(i).GetName() << endl;
    cout << "\n### Player1, " << players.at(0).GetName() << " is the so-called dealer. ###\n\n";

    //Waiting
    cout << "Press any key to continue...";
    cin.sync();
    getch();

    //Shuffle the cards.
    Main.Full();
    Main.Shuffle();

    // initial deal
    int init_card_num = 24 / player_num;
    for (int i=0; i<init_card_num; i++) {
        for (int j=0; j<player_num; j++) {
            players.at(j).GetCardToHand(Main.Deal());
        }
    }

    // flip 4 cards and put on table
    for(int i=0; i<4; i++)
        Layout.Add(Main.Deal());

    do{
        //Special-case check for four cards.
        while( Layout.special_check(4)!=static_cast<Card::Rank>(Unknown) ){
            card.set_rank( Layout.special_check(4) );
            system("cls");
            cout << "Now the layout contains four cards of rank \"" << card.rank_name() << "\"." << endl << endl;
            cout << "Layout:\n\n";
            Layout.Print();
            cout << "\nThis is the special case." << endl;
            cout << "The four cards are now being captured by the dealer, " << players.at(0).GetName() << ".\n\n";
            while( Layout.number()>0 )
                players.at(0).GetCardToPile(Layout.Deal());
            cout << "Capturing";
            for(int i=5; i>=0; i--){
                Sleep(500);
                cout <<'.';
            }
            cout << endl << endl;
            cout << "Now " << players.at(0).GetName() << " has captured the four cards:\n\n";
            players.at(0).GetPile().Print();
            for(int i=0; i<4; i++)
                Layout.Add(Main.Deal());
            cout << "\nThe new four cards flipped from the deck are now on the table.\n\nPress any key to continue...";
            cin.sync();

            //Computer Operation
            if( players.at(0).ComputerOn()==true )
                players.at(0).PressAnyKey();
            getch();
        };

        //Special-case check for three cards initially.
        while( Layout.special_check(3)!=static_cast<Card::Rank>(Unknown) ){
            card.set_rank( Layout.special_check(3) );
            for(int i=0; i<player_num && player_index==-1 ; i++)
                for(int j=0; j<players.at(i).GetHand().number() && player_index==-1 ; j++)
                    if( players.at(i).GetHand().card(j).rank_name() == card.rank_name() )
                        player_index = i;

            //If no one has the other card of the same rank now, get out of this while-loop.
            if( player_index==-1 )
                break;

            system("cls");
            cout << "Now the layout contains three cards of rank \"" << card.rank_name() << "\"." << endl << endl;
            cout << "Layout:\n\n";
            Layout.Print();
            cout << "\nThis is the special case." << endl;
            cout << "The three cards are now being captured by the player, " << players.at(player_index).GetName() << ", who has the other card of the same rank.\n\n";
            Layout.Sort();
            if( Layout.card(0).rank_name()==card.rank_name() ){
                for(int i=0; i<3; i++){
                    players.at(player_index).GetCardToPile(Layout.card(0));
                    Layout.Delete(0);
                }
            }
            else if( Layout.card(3).rank_name()==card.rank_name() ){
                for(int i=0; i<3; i++)
                    players.at(player_index).GetCardToPile(Layout.Deal());
            }
            else{

            }
            cout << "Capturing";
            for(int i=5; i>=0; i--){
                Sleep(500);
                cout <<'.';
            }
            cout << endl << endl;
            cout << "Now " << players.at(player_index).GetName() << " has captured the three cards:\n\n";
            players.at(player_index).GetPile().Print();
            for(int i=0; i<3; i++)
                Layout.Add(Main.Deal());
            cout << "\nThe new three cards flipped from the deck are now on the table.\n\nPress any key to continue...";
            cin.sync();
            //Computer Operation
            if( players.at(player_index).ComputerOn()==true )
                players.at(player_index).PressAnyKey();
            getch();
        };
    }while( Layout.special_check(4)!=static_cast<Card::Rank>(Unknown) );

    // play game!
    while ( finish == 0 ) {
        for (int i=0; i<player_num; i++)
            players.at(i).Play(player_num,Main,Layout,card);
        for (int i=0; i<player_num; i++){
            if( players.at(i).GetHand().number()==0 )
                finish = 1;
            else
                finish = 0;
        }
    }

    // count points for each player
    system("cls");
    cout << "========================This game has been finished!!!======================\n\n";
    for (int i=0; i<player_num; i++) {
        cout << players.at(i).GetName() << "\'s cards" << ":" << endl;
        players.at(i).GetPile().Print();
        cout << endl;
    }

    // scoreboard
    switch(player_num){
        case 2: tie_score=105; break;
        case 3: tie_score=80; break;
        case 4: tie_score=70; break;
        default: tie_score=0; break;
    }
    ranking.Clear();
    for(int i=0; i<player_num; i++){
        score.name = players.at(i).GetName();
        score.score = players.at(i).Points(player_num);
        ranking.Push_back(score);
    }
    //Sort the scores right after the game ends.
    ranking.SortByScore();

    cout << "================================Scoreboard==================================\n\n";
    cout << "Player: " << player_num << endl;
    cout << "Tie Score: " << tie_score << " points" << endl << endl;
    cout << "=Rank=|===============Name===============|====Points====|=======Score=======" << endl;
    for (int i=0; i<player_num; i++) {
        printf("  %02d  |",i+1);
        cout << setw(34) << ranking.GetPlayer(i).name << '|';
        cout << setw(5) << ranking.GetPlayer(i).score;
        cout << " point(s)|";
        if( ranking.GetPlayer(i).score>tie_score ){
            printf("  Win ");
            cout << setw(4) << ranking.GetPlayer(i).score-tie_score << " point(s)" << endl;
        }
        else if( ranking.GetPlayer(i).score<tie_score ){
            printf("  Lose");
            cout << setw(4) << tie_score-ranking.GetPlayer(i).score << " point(s)" << endl;
        }
        else if( ranking.GetPlayer(i).score==tie_score ){
            printf("        Tie\n");
        }
        else{
            printf("-------------------\n");
        }
    }
    cout <<  endl;

    //Record the game to a file.
    ranking.Recording(player_num);


    //Go back to main menu.
    cout << "Press any key to go back to main menu...\n";
    getch();
    goto MENU;

    return 0;
}
コード例 #9
0
ファイル: GDE3.cpp プロジェクト: ajnebro/MO-Phylogenetics
/*
 * Runs the GDE3 algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * GDE3::execute() {

  int populationSize;
  int maxIterations;
  int evaluations;
  int iterations;

  SolutionSet * population;
  SolutionSet * offspringPopulation;

  Distance * distance;
  Comparator * dominance;

  Operator * crossoverOperator;
  Operator * selectionOperator;

  distance  = new Distance();
  dominance = new DominanceComparator();

  Solution ** parent;

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxIterations  = *(int *) getInputParameter("maxIterations");

  //Initialize the variables
  population  = new SolutionSet(populationSize);
  evaluations = 0;
  iterations  = 0;

  //Read the operators
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];

  // Create the initial solutionSet
  Solution * newSolution;
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for

  // Generations ...
  while (iterations < maxIterations) {
    // Create the offSpring solutionSet
    offspringPopulation  = new SolutionSet(populationSize * 2);

    for (int i = 0; i < populationSize; i++){
      // Obtain parents. Two parameters are required: the population and the
      //                 index of the current individual
      void ** object1 = new void*[2];
      object1[0] = population;
      object1[1] = &i;
      parent = (Solution **) (selectionOperator->execute(object1));
      delete[] object1;

      Solution * child ;
      // Crossover. Two parameters are required: the current individual and the
      //            array of parents
      void ** object2 = new void*[2];
      object2[0] = population->get(i);
      object2[1] = parent;
      child = (Solution *) (crossoverOperator->execute(object2));
      delete[] object2;
      delete[] parent;

      problem_->evaluate(child) ;
      problem_->evaluateConstraints(child);
      evaluations++ ;

      // Dominance test
      int result  ;
      result = dominance->compare(population->get(i), child) ;
      if (result == -1) { // Solution i dominates child
        offspringPopulation->add(new Solution(population->get(i)));
        delete child;
      } // if
      else if (result == 1) { // child dominates
        offspringPopulation->add(child) ;
      } // else if
      else { // the two solutions are non-dominated
        offspringPopulation->add(child) ;
        offspringPopulation->add(new Solution(population->get(i)));
      } // else
    } // for

    // Ranking the offspring population
    Ranking * ranking = new Ranking(offspringPopulation);

    int remain = populationSize;
    int index  = 0;
    SolutionSet * front = NULL;
    for (int i = 0; i < populationSize; i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())){
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++ ) {
        population->add(new Solution(front->get(k)));
      } // for

      //Decrement remain
      remain = remain - front->size();

      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      while (front->size() > remain) {
         distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives());
         Comparator * crowdingComparator = new CrowdingComparator();
         int indexWorst = front->indexWorst(crowdingComparator);
         delete crowdingComparator;
         delete front->get(indexWorst);
         front->remove(indexWorst);
      }
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      }

      remain = 0;
    } // if

    delete ranking;
    delete offspringPopulation;

    iterations ++ ;
  } // while

  delete dominance;
  delete distance;

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute