Esempio n. 1
0
void backtrack(int a[], int k, Graph *graph){     
	int ncandidatos, i, c[graph->numero_vertices];
	if ( is_solution(a, k, graph) ){
        
        int solucao_encontrada = distancia_total(a, k, graph);
        
        if(solucao_atual == 0 || solucao_atual > solucao_encontrada){
            solucao_atual = solucao_encontrada;
            printf("\nNova solucao Melhor: %d\n", solucao_atual);
            imprimir_rota(a, k, graph);
        }
        return;
	}
	else {
		k=k+1;

        if(k > (graph->numero_vertices +1)) {
             return;
        }
    	construct_candidate(a, k, graph, c, &ncandidatos);
    	
    	for ( i=0; i < ncandidatos; i++){
    		a[k] = c[i];
    		backtrack(a, k, graph);
            undo_move(a, k, graph);
    	}
	}
}
Esempio n. 2
0
int	game(char *code, char *pion, int tentative, int slot)
{
  int	win;
  int	round;
  char	buffer[24];
  int	len;

  if (check_game(code, pion, slot, tentative) == 1)
    return (1);
  my_putstr("Trouverez-vous le code secret ?\n");
  round = 1;
  win = 0;
  while (tentative >= round && win != 1)
    {
      my_putstr("---\n");
      write(1, "Round ", 6);
      my_putnbr(round);
      write(1, "\n>", 1);
      len = read(0, buffer, 23);
      buffer[len - 1] = 0;
      win = is_solution(code, buffer, pion, slot);
      round++;
    }
  win_msg(round - 1, win, code);
  free(code);
  free(pion);
  return (0);
}
Esempio n. 3
0
 void dfs(int n, int row, int &sum, vector<int>& tmp)
 {
     if(n == row)
     {
         sum++;
         return;
     }
     else
     {
         for(int i = 0; i < n; ++i)
         {
             tmp[row] = i;
             if(is_solution(row, tmp))
             {
                 dfs(n, row+1, sum, tmp);
             }
         }
     }
 }
Esempio n. 4
0
static void epd_test_file(const char file_name[]) {

   FILE * file;
   int hit, tot;
   char epd[StringSize];
   char am[StringSize], bm[StringSize], id[StringSize];
   board_t board[1];
   char string[StringSize];
   int move;
   char pv_string[StringSize];
   bool correct;
   double depth_tot, time_tot, node_tot;

   ASSERT(file_name!=NULL);

   // init

   file = fopen(file_name,"r");
   if (file == NULL) my_fatal("epd_test_file(): can't open file \"%s\": %s\n",file_name,strerror(errno));

   hit = 0;
   tot = 0;

   depth_tot = 0.0;
   time_tot = 0.0;
   node_tot = 0.0;

   // loop

   while (my_file_read_line(file,epd,StringSize)) {

      if (UseTrace) printf("%s\n",epd);

      if (!epd_get_op(epd,"am",am,StringSize)) strcpy(am,"");
      if (!epd_get_op(epd,"bm",bm,StringSize)) strcpy(bm,"");
      if (!epd_get_op(epd,"id",id,StringSize)) strcpy(id,"");

      if (my_string_empty(am) && my_string_empty(bm)) {
         my_fatal("epd_test(): no am or bm field in EPD\n");
      }

      // init

      uci_send_ucinewgame(Uci);
      uci_send_isready_sync(Uci);

      ASSERT(!Uci->searching);

      // position

      if (!board_from_fen(board,epd)) ASSERT(false);
      if (!board_to_fen(board,string,StringSize)) ASSERT(false);

      engine_send(Engine,"position fen %s",string);

      // search

      engine_send(Engine,"go movetime %.0f depth %d",MaxTime*1000.0,MaxDepth);
      // engine_send(Engine,"go infinite");

      // engine data

      board_copy(Uci->board,board);

      uci_clear(Uci);
      Uci->searching = true;
      Uci->pending_nb++;

      FirstMove = MoveNone;
      FirstDepth = 0;
      FirstSelDepth = 0;
      FirstScore = 0;
      FirstTime = 0.0;
      FirstNodeNb = 0;
      line_clear(FirstPV);

      LastMove = MoveNone;
      LastDepth = 0;
      LastSelDepth = 0;
      LastScore = 0;
      LastTime = 0.0;
      LastNodeNb = 0;
      line_clear(LastPV);

      // parse engine output

      while (engine_step()) {

         // stop search?

         if (Uci->depth > MaxDepth
          || Uci->time >= MaxTime
          || (Uci->depth - FirstDepth >= DepthDelta
           && Uci->depth > MinDepth
           && Uci->time >= MinTime
           && is_solution(FirstMove,board,bm,am))) {
            engine_send(Engine,"stop");
         }
      }

      move = FirstMove;
      correct = is_solution(move,board,bm,am);

      if (correct) hit++;
      tot++;

      if (correct) {
         depth_tot += double(FirstDepth);
         time_tot += FirstTime;
         node_tot += double(FirstNodeNb);
      }

      printf("%s %d %4d %4d",id,correct,hit,tot);

      if (!line_to_san(LastPV,Uci->board,pv_string,StringSize)) ASSERT(false);
      printf(" - %2d %6.2f %9lld %+6.2f %s\n",FirstDepth,FirstTime,FirstNodeNb,double(LastScore)/100.0,pv_string);
   }

   printf("%d/%d",hit,tot);

   if (hit != 0) {

      depth_tot /= double(hit);
      time_tot /= double(hit);
      node_tot /= double(hit);

      printf(" - %.1f %.2f %.0f",depth_tot,time_tot,node_tot);
   }

   printf("\n");

   fclose(file);
}
int main(int argc, char *argv[])
{

    int verbose=2;
    std::string srcFileName="-";
    int maxTries=INT_MAX;
    std::string name="perfect";
    //std::string writeCpp="";
    std::string method="default";
    int wV=0;
    unsigned maxHash=0;

    double maxTime=600;
    double maxMem=4000;

    double solveTime=0.0;
    std::string csvLogDst;

    urng.seed(time(0));

    try {
        int ia = 1;
        while (ia < argc) {
            if (!strcmp(argv[ia], "--verbose")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --verbose");
                verbose = atoi(argv[ia + 1]);
                ia += 2;
            } else if (!strcmp(argv[ia], "--input")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --input");
                srcFileName = argv[ia + 1];
                ia += 2;
            } else if (!strcmp(argv[ia], "--csv-log")) {
                if ((argc - ia) < 3) throw std::runtime_error("No argument to --csv-dst");
                csvLogPrefix = argv[ia + 1];
                csvLogDst = argv[ia + 2];
                ia += 3;
            } else if (!strcmp(argv[ia], "--wa")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --wa");
                wA = atoi(argv[ia + 1]);
                if (wA < 1) throw std::runtime_error("Can't have wa < 1");
                if (wA > 12) throw std::runtime_error("wa > 12 is unexpectedly large (edit code if you are sure).");
                ia += 2;
            } else if (!strcmp(argv[ia], "--wo")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --wo");
                wO = atoi(argv[ia + 1]);
                if (wO < 1) throw std::runtime_error("Can't have wo < 1");
                if (wO > 16) throw std::runtime_error("wo > 16 is unexpectedly large (edit code if you are sure).");
                ia += 2;
            } else if (!strcmp(argv[ia], "--wv")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --wv");
                wV = atoi(argv[ia + 1]);
                if (wV < 0) throw std::runtime_error("Can't have wv < 0");
                ia += 2;
            } else if (!strcmp(argv[ia], "--wi")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --wi");
                wI = atoi(argv[ia + 1]);
                if (wI < 1) throw std::runtime_error("Can't have wi < 1");
                if (wI > 32) throw std::runtime_error("wo > 32 is unexpectedly large (edit code if you are sure).");
                ia += 2;
            } else if (!strcmp(argv[ia], "--max-time")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-time");
                maxTime = strtod(argv[ia + 1], 0);
                ia += 2;
            } else if (!strcmp(argv[ia], "--max-mem")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-mem");
                maxMem = strtod(argv[ia + 1], 0);
                ia += 2;
            } else if (!strcmp(argv[ia], "--method")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --method");
                method = argv[ia + 1];
                ia += 2;
            } else if (!strcmp(argv[ia], "--max-hash")) {
                if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-hash");
                maxHash = atoi(argv[ia + 1]);
                ia += 2;
            } else if (!strcmp(argv[ia], "--minimal")) {
                if ((argc - ia) < 1) throw std::runtime_error("No argument to --minimal");
                maxHash=UINT_MAX;
                ia += 1;
            /*} else if (!strcmp(argv[ia], "--write-cpp")) {
                if ((argc - ia) < 2) throw std::runtime_error("Not enough arguments to --write-cpp");
                writeCpp = argv[ia + 1];
                ia += 2;*/
            } else {
                throw std::runtime_error(std::string("Didn't understand argument ") + argv[ia]);
            }
        }

        if(!csvLogDst.empty()){
            if(csvLogDst=="-"){
                pCsvDst = &std::cout;
            }else{
                csvLogFile.open(csvLogDst);
                if(!csvLogFile.is_open()){
                    throw std::runtime_error("Couldn't open csv log destination.");
                }
                pCsvDst=&csvLogFile;
            }

        }

        if(verbose>0){
            fprintf(stderr, "Setting limits of %f seconds CPU time and %f MB of memory.\n", maxTime, maxMem);
            setTimeAndSpaceLimit(maxTime, maxMem);
        }

        if (method == "default") {
            if (verbose > 0) {
                method = "minisat_weighted";
                std::cerr << "Selecting default method = " << method << "\n";
            }
        }


        if (verbose > 0) {
            std::cerr << "Loading input from " << (srcFileName == "-" ? "<stdin>" : srcFileName) << ".\n";
        }

        key_value_set problem;

        if (srcFileName == "-") {
            problem = parse_key_value_set(std::cin);
        } else {
            std::ifstream srcFile(srcFileName);
            if (!srcFile.is_open())
                throw std::runtime_error("Couldn't open source file " + srcFileName);
            problem = parse_key_value_set(srcFile);
        }

        if (verbose > 1) {
            std::cerr << "Input key value pairs:\n";
            problem.print(std::cerr, "  ");
            std::cerr << "nKeys = " << problem.size() << "\n";
            std::cerr << "wKey = " << problem.getKeyWidth() << "\n";
            std::cerr << "wValue = " << problem.getValueWidth() << "\n";
        }

        if(maxHash==UINT_MAX){
            if(verbose>0){
                std::cerr << " Building minimal hash.\n";
            }
            problem.setMaxHash(maxHash);
        }else if(maxHash>0){
            if(verbose>0){
                std::cerr << " Setting maxHash="<<maxHash<<"\n";
            }
            problem.setMaxHash(maxHash);
        }

        if (wI == -1) {
            wI = problem.getKeyWidth();
            if (verbose > 0) {
                std::cerr << "Auto-selecting wI = " << wI << "\n";
            }
        } else {
            if (wI < (int) problem.getKeyWidth()) {
                throw std::runtime_error("Specified key width does not cover all keys.");
            }
        }

        if (wO == -1) {
            unsigned nKeys = problem.keys_size();
            wO = (unsigned) ceil(log(nKeys) / log(2.0));
            if (verbose > 0) {
                std::cerr << "Auto-selecting wO = " << wO << " based on nKeys = " << nKeys << "\n";
            }
        } else {
            if ((1u << wO) < problem.keys_size()) {
                throw std::runtime_error("Specified output width cannot span number of keys.");
            }
        }
        if (verbose > 0) {
            std::cerr << "Group load factor is 2^wO / nKeyGroups = " << problem.keys_size() << " / " << (1 << wO) <<
            " = " << problem.keys_size() / (double) (1 << wO) << "\n";
            std::cerr << "True load factor is 2^wO / nKeysDistinct = " << problem.keys_size_distinct() << " / " <<
            (1 << wO) << " = " << problem.keys_size_distinct() / (double) (1 << wO) << "\n";
        }

        BitHash result;

        startTime=cpuTime();

        tries = 1;
        bool success = false;
        while (tries < maxTries) {
            if (verbose > 0) {
                std::cerr << "  Attempt " << tries << "\n";
            }
            if (verbose > 0) {
                std::cerr << "  Creating bit hash...\n";
            }
            auto bh = (method == "minisat_weighted") ? makeWeightedBitHash(urng, problem, wO, wI, wA) : makeBitHash(
                    urng, wO, wI, wA);
            if (verbose > 0) {
                std::cerr << "  Converting to CNF...\n";
            }
            cnf_problem prob;
            to_cnf(bh, problem.keys(), prob, problem.getMaxHash());
            if (verbose > 0) {
                std::cerr << "  Solving problem with minisat...\n";
            }
            auto sol = minisat_solve(prob, verbose);

            if (sol.empty()) {
                if (verbose > 0) {
                    std::cerr << "  No solution\n";
                }
            } else {
                if (verbose > 0) {
                    std::cerr << "  Checking raw...\n";
                }

                if (verbose > 0) {
                    std::cerr << "  Substituting...\n";
                }
                auto back = substitute(bh, prob, sol);

                if (verbose > 0) {
                    std::cerr << "  checking...\n";
                }
                if (!back.is_solution(problem))
                    throw std::runtime_error("Failed post substitution check.");

                success = true;
                result = back;
                break;
            }
            tries++;
        }

        double finishTime=cpuTime();
        solveTime=finishTime-startTime;

        if(pCsvDst){
            (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<(success?"Success":"OutOfAttempts")<<"\n";
        }

        if (!success) {
            if(pCsvDst) {
                exit(0);
            }else{
                exit(1);
            }
        }
        if(verbose>1){
            for(const auto &kv : problem){
                auto key = *kv.first.variants_begin();

                std::cerr<<"  "<<key<<" -> "<<result(key)<<"\n";
            }
        }

        // Print the two back to back
        result.print(std::cout);
        problem.print(std::cout);

    }catch(Minisat::OutOfMemoryException &e){

        if(pCsvDst){
            (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<"OutOfMemory"<<"\n";
	    pCsvDst->flush();
        }

        std::cerr<<"Memory limit exceeded.";
        _exit(pCsvDst ? 0 : 1);
    }catch(std::exception &e){
        if(pCsvDst){
            (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<"Exception"<<"\n";
	    pCsvDst->flush();
        }

        std::cerr<<"Caught exception : ";
        print_exception(e);
	std::cerr.flush();
        _exit(pCsvDst ? 0 : 1);
    }

    return 0;
}