vector<vector<string>> findLadders(string start, string end, 
    									unordered_set<string> &dict) {
        map<string, vector<string>> traces; 
        // If A->C and B->C, then traces[C] contains A and B.
        // This is used for recovering the paths.
        vector<unordered_set<string>> level(2);
        int cur = 0;
        int prev = 1;
        level[cur].insert(start);
        dict.insert(end);

        while (true)
        {
            prev = !prev;
            cur = !cur;
            level[cur].clear();

            // remove visited words. IMPORTANT!
            for (unordered_set<string>::iterator it = level[prev].begin(); 
            		it != level[prev].end(); ++it)
                dict.erase(*it);

            for (unordered_set<string>::iterator it = level[prev].begin(); 
            	it != level[prev].end(); ++it)
            {
                string word = *it;
                for (size_t i = 0; i < word.size(); i++) {
                    char before = word[i];
                    for (char c = 'a'; c <= 'z'; c++) {
                        if (c == before)
                            continue;
                        word[i] = c;
                        if (dict.find(word) != dict.end()) {
                            traces[word].push_back(*it);
                            level[cur].insert(word);
                        }
                    }
                    word[i] = before;
                }
            }

            if (level[cur].empty() || level[cur].count(end) > 0)
                break;
        }

        vector<vector<string>> res;
        vector<string> onePath;
        if (!traces.empty())
            buildResult(traces, res, onePath, end);

        return res;
    }
    void buildResult(map<string, vector<string>> &traces, vector<vector<string>> &res, 
    				vector<string> &onePath, string word)
    {
        if (traces.count(word) == 0)
        {
            vector<string> copy(onePath);
            copy.push_back(word);
            reverse(copy.begin(), copy.end());
            res.push_back(copy);
            return;
        }

        const vector<string> &s = traces[word];
        onePath.push_back(word);
        for (vector<string>::const_iterator it = s.begin(); it != s.end(); ++it)
            buildResult(traces, res, onePath, *it);
        onePath.pop_back();
    }
Exemplo n.º 3
0
// main
Result* SPEA2Adapt::launch(QString tempDir)
{
    // init random
    rng.reseed(time(NULL));

    int argc=0;
    char *argv1 = "";
    char **argv = &argv1;

    eoParser parser(argc, argv);  // for user-parameter reading
    eoState state;

    /************************************
 BOUNDS
 ************************************/
    std::vector<eoRealInterval> doubleBounds;
    std::vector<eoIntInterval> intBounds;
    int nbDouble=0,nbInt=0,nbBool=0;
    int nbObj = ((Optimization*)_problem)->objectives()->size();


    EAStdBounds::setBounds((Optimization*)_problem,_subModels,doubleBounds,intBounds,nbDouble,nbInt,nbBool);


    /************************************
    PROGRESS AND CONTINUATOR
    ************************************/
    unsigned initPopSize = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::POPULATIONSIZE),20).toInt();
    unsigned offSpringRate = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::OFFSPRINGRATE),3).toInt();
    unsigned nTotalGen = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::MAXGENERATIONS),100).toInt();
    unsigned nTotalEvals = initPopSize + initPopSize*nTotalGen*offSpringRate;

    OMEAProgress OMEAProgress;
    connect(&OMEAProgress,SIGNAL(newProgress(float)),_problem,SIGNAL(newProgress(float)));
    connect(&OMEAProgress,SIGNAL(newProgress(float,int,int)),_problem,SIGNAL(newProgress(float,int,int)));

    eoGenContinue < EOAdapt > genContinuator(nTotalGen);

    /************************************
    FITNESS EVALUATION
    ************************************/
    moeoEvalFunc < EOAdapt > *plainEval;
    plainEval = new EAStdOptimizationEval<EOAdapt>(_project,(Optimization*)_problem,_subModels,tempDir,
                                                   _modItemsTree);

    OMEAEvalFuncCounter<EOAdapt>* eval = new OMEAEvalFuncCounter<EOAdapt> (* plainEval,&OMEAProgress,nTotalEvals);




    //************************************
    //INITIAL POPULATION
    //************************************/
    SPEA2AdaptInitBounded<EOAdapt> *init = new SPEA2AdaptInitBounded<EOAdapt>(doubleBounds,intBounds,nbBool,initPopSize);
    //state.storeFunctor(init);


    ///************************************
    //CROSSOVER AND MUTATION
    //************************************/
    SBCrossover<EOAdapt> *xover = new SBCrossover <EOAdapt>(_parameters);
    //state.storeFunctor(xover);

    EAAdapt1Mutation<EOAdapt> *mutation = new EAAdapt1Mutation<EOAdapt>(doubleBounds,intBounds,_parameters);
    //state.storeFunctor(mutation);

    eoSequentialOp<EOAdapt> *op = new eoSequentialOp<EOAdapt>;
    //state.storeFunctor(op);
    op -> add(*xover, 1.0);     // always do crossover (probabilities are taken into account inside)
    op -> add(*mutation, 1.0); // and mutation

    /************************************
    POPULATION
    ************************************/
    //eoPop<EOAdapt>& pop = state.takeOwnership(eoPop<EOAdapt>());
    eoPop<EOAdapt> pop;
    bool loadFailed=false;
    bool useStartFile = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::USESTARTFILE),false).toBool();
    QString reloadFilePath = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::STARTFILEPATH)).toString();

    if(useStartFile && (reloadFilePath!="") && QFileInfo(reloadFilePath).exists())
    {

        // create another state for reading
        eoState inState;        // a state for loading - WITHOUT the parser
        // register the rng and the pop in the state, so they can be loaded,
        // and the present run will be the exact continuation of the saved run
        // eventually with different parameters
        inState.registerObject(pop);
        inState.registerObject(rng);


        std::string str = reloadFilePath.toLatin1().data();
        try{
            inState.load(str);
        }
        catch(std::exception &e)
        {
            InfoSender::instance()->send(Info("Loading start file failed :"+QString(e.what()),ListInfo::WARNING2));
            loadFailed = true;
        }
        if(!loadFailed)
        {
            InfoSender::instance()->send(Info("Loading start file success : "+reloadFilePath,ListInfo::NORMAL2));
        }
        bool reinitStdDev= _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::REINITSTDDEV)).toBool();
        if(reinitStdDev)
        {
            EAAdaptReinitStdDev<EOAdapt>::reinitDblStdDev(pop,doubleBounds,initPopSize);
        }
    }

    if(loadFailed)
    {
        pop.clear();
        pop = state.takeOwnership(eoPop<EOAdapt>());
    }


    if(pop.size() < initPopSize)
    {
        pop.append(initPopSize,*init);
    }

    // for future stateSave, register the algorithm into the state
    state.registerObject(parser);
    state.registerObject(pop);
    state.registerObject(rng);


    /************************************
    ARCHIVE
    ************************************/
    moeoUnboundedArchive<EOAdapt> arch;

    /************************************
 STOPPING CRITERIA
 ************************************/
    MyEAEvalContinue<EOAdapt> *evalCont = new MyEAEvalContinue<EOAdapt>(*eval,nTotalEvals,&_stop);
    //state.storeFunctor(evalCont);

    /************************************
    OUTPUT
    ************************************/
    eoCheckPoint<EOAdapt>& checkpoint = createEAStdCheckPoint(parser, state, *eval, *evalCont, pop, arch,_project,_parameters,tempDir,nbObj);

    /************************************
 MONITOR
 ************************************/
    // Create a counter parameter
    eoValueParam<unsigned> generationCounter(0, "Gen.");
    // now some statistics on the population:
    // Best fitness in population

    // the Fitness Distance Correlation
    // need first an object to compute the distances
    //   eoQuadDistance<EOAdapt> dist;
    //// Hamming distance
    //   eoFDCStat<EOAdapt> fdcStat(dist);
    //   // Add them to the checkpoint to get them called at the appropriate time
    //   checkpoint.add(averageStat);
    //   checkpoint.add(fdcStat);


//    //monitor.add(SecondStat);
    //monitor.add(fdcStat);

//    eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(QDir(tempDir).absoluteFilePath("mybest.xg").toLatin1().data(),minimizing_fitness<EOAdapt>());

//     // save and give to checkpoint
//    state.storeFunctor(gnuMonitor);
//    checkpoint.add(*gnuMonitor);
//    gnuMonitor->add(*eval);

//    eoBestFitnessStat<EOAdapt>* bestStat = new eoBestFitnessStat<EOAdapt>;
//    state.storeFunctor(bestStat);
//    gnuMonitor->add(*bestStat);




    ///************************************
    //BUILD SPEAAdapt1
    //************************************/
    double rate = _parameters->value(SPEA2AdaptParameters::str(SPEA2AdaptParameters::OFFSPRINGRATE),3).toDouble();
    SPEA2Algo<EOAdapt> spea2(checkpoint,*eval,*xover,1,*mutation,1,arch,initPopSize,rate,true);

    ///************************************
    //RUN THE ALGO
    //************************************/
    spea2(pop);

    ///************************************
    //GETTING RESULT FROM FINAL ARCHIVE
    //************************************/
    Result* result = buildResult(arch);


    return result;
}
Exemplo n.º 4
0
// main
Result* SPEA2::launch(QString tempDir)
{
    // init random
    rng.reseed(time(NULL));

    int argc=0;
    char *argv1 = "";
    char **argv = &argv1;

    eoParser parser(argc, argv);  // for user-parameter reading
    eoState state;


    /************************************
 BOUNDS
 ************************************/
    std::vector<eoRealInterval> doubleBounds;
    std::vector<eoIntInterval> intBounds;
    int nbDouble=0,nbInt=0,nbBool=0;
    int nbObj = ((Optimization*)_problem)->objectives()->size();

    EAStdBounds::setBounds((Optimization*)_problem,_subModels,doubleBounds,intBounds,nbDouble,nbInt,nbBool);

    /************************************
 PROGRESS
 ************************************/
    OMEAProgress* omEAProgress = new OMEAProgress();
    connect(omEAProgress,SIGNAL(newProgress(float)),_problem,SIGNAL(newProgress(float)));
    connect(omEAProgress,SIGNAL(newProgress(float,int,int)),_problem,SIGNAL(newProgress(float,int,int)));

    int totalEval = _parameters->value(SPEA2Parameters::str(SPEA2Parameters::MAXITERATIONS),50).toInt();



    /************************************
    FITNESS EVALUATION
    ************************************/
    moeoEvalFunc < EOStd > *plainEval;
    plainEval = new EAStdOptimizationEval<EOStd>(_project,(Optimization*)_problem,_subModels,tempDir,
                                                 _modItemsTree);

    OMEAEvalFuncCounter<EOStd>* eval = new OMEAEvalFuncCounter<EOStd> (* plainEval,omEAProgress,totalEval);
    state.storeFunctor(eval);

    //************************************
    //INITIAL POPULATION
    //************************************/
    EAStdInitBounded<EOStd> *init = new EAStdInitBounded<EOStd>(doubleBounds,intBounds,nbBool);
    state.storeFunctor(init);

    ///************************************
    //CROSSOVER AND MUTATION
    //************************************/
    SBCrossover<EOStd> *xover = new SBCrossover<EOStd>(_parameters);
    state.storeFunctor(xover);

    EAStdMutation<EOStd> *mutation = new EAStdMutation<EOStd>(doubleBounds,intBounds,_parameters);
    state.storeFunctor(mutation);

    eoSequentialOp<EOStd> *op = new eoSequentialOp<EOStd>;
    state.storeFunctor(op);
    op -> add(*xover, 1.0);     // always do crossover (probabilities are taken into account inside)
    op -> add(*mutation, 1.0); // and mutation


    /************************************
    POPULATION
    ************************************/
    eoPop<EOStd> pop;
    bool loadFailed=false;
    bool useStartFile = _parameters->value(SPEA2Parameters::str(SPEA2Parameters::USESTARTFILE),false).toBool();
    QString reloadFilePath = _parameters->value(SPEA2Parameters::str(SPEA2Parameters::STARTFILEPATH)).toString();

    if(useStartFile && (reloadFilePath!="") && QFileInfo(reloadFilePath).exists())
    {
        // create another state for reading
        eoState inState;        // a state for loading - WITHOUT the parser
        // register the rng and the pop in the state, so they can be loaded,
        // and the present run will be the exact continuation of the saved run
        // eventually with different parameters
        inState.registerObject(pop);
        inState.registerObject(rng);

        std::string str = reloadFilePath.toLatin1().data();
        try{
            inState.load(str);
        }
        catch(std::exception &e)
        {
            InfoSender::instance()->debug("loading start file failed :"+QString(e.what()));
            loadFailed = true;
        }
        if(!loadFailed)
        {
            InfoSender::instance()->send(Info("Loading start file success : "+reloadFilePath,ListInfo::NORMAL2));
        }
    }


    if(loadFailed)
    {
        pop.clear();
        pop = state.takeOwnership(eoPop<EOStd>());
    }


    int popSize = _parameters->value(SPEA2Parameters::str(SPEA2Parameters::POPULATIONSIZE),20).toInt();
    if(pop.size() < popSize)
    {
        pop.append(popSize-pop.size(),*init);
    }

    // for future stateSave, register the algorithm into the state
    state.registerObject(parser);
    state.registerObject(pop);
    state.registerObject(rng);


    /************************************
     ARCHIVE
    ************************************/
    moeoUnboundedArchive<EOStd> arch;


    /************************************
     STOPPING CRITERIA
     ************************************/
    MyEAEvalContinue<EOStd> *evalCont = new MyEAEvalContinue<EOStd>(*eval,totalEval,&_stop);
    state.storeFunctor(evalCont);


    /************************************
    OUTPUT
    ************************************/
    eoCheckPoint<EOStd>& checkpoint = createEAStdCheckPoint(parser, state, *eval, *evalCont, pop, arch,_project,_parameters,tempDir,nbObj);


    ///************************************
    //BUILD SPEA2
    //************************************/
    SPEA2Algo<EOStd> spea2(checkpoint,*eval,*xover,1,*mutation,1,arch,popSize,1.0,true);

    ///************************************
    //RUN THE ALGO
    //************************************/
    spea2 (pop);

    ///************************************
    //GETTING RESULT FROM FINAL ARCHIVE
    //************************************/
    Result* result = buildResult(arch);


    return result;

}