Exemplo n.º 1
0
int main(int argc, char* argv[])
{
	if(argc == 1)
	{
		printf("Please give a filename for the puzzle.\n");
		return 1;
	}

	char* filename = argv[1];

	int** puzzle = read_file(filename);
	printf("\ninput puzzle\n");
	print_solution(puzzle);

	Sudoku solver(N);
	solver.Solve(puzzle);
	int** solution = solver.get_puzzle();
	printf("\nsolution\n");
	print_solution(solution);

	for(int row = 0; row < N; row++)
	{
		delete[] puzzle[row];
	}
	delete[] puzzle;

	return 0;
}
Exemplo n.º 2
0
Solution *Solver::solve(){

	std::ofstream out_file (file_out.c_str());
	if (!out_file.is_open()) {
		std::cout << "Unable to open file";
	}

	init();
	// ------ print solution -------
	print_solution(current_solution);
	//print_file_solution(0, current_solution, out_file);
	// ------ print solution -------

   clock_t start, end, total;

	start = clock();


	for(unsigned int i=0;i<max_iterations;i++){

		iter_cost_time = 0;

		std::cout << "----- iteration "<< i << " ------" << std::endl;

		local_search();

		// ------ print solution -------
		std::cout << "local search  ";
		print_solution(current_solution);
		print_file_solution(i, current_solution, out_file);
		// ------ print solution -------

		global_search();

		// ------ print solution -------
		std::cout << "global search ";
		print_solution(current_solution);
		//print_file_solution(i, current_solution, out_file);
		// ------ print solution -------

		tabu_list->update_tabu();

	    total_cost_time += iter_cost_time;

		if(global_best_cost == 0)
			break;
	}

	end = clock();
	total = end - start;

    printf("\nTotal OpenCL Kernel time in milliseconds = %0.3f ms\n", (total_cost_time / 1000000.0) );
    printf("Total CPU time in milliseconds = %0.3f ms\n", total /1000.0);

	return global_best;
}
Exemplo n.º 3
0
static ERL_NIF_TERM recombine_solutions(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){

    // long diff;
    // struct timespec start, end;
    // clock_gettime(CLOCK_MONOTONIC, &start);

    ERL_NIF_TERM terms[2];
    ErlNifResourceType* sol_type;
    Solution *sols[2], *new_sols[2]; // arrays of two pointers of type Solution*
    unsigned int i;
    unsigned int len;

    CHECK(env, argc == 2)

    sol_type = (ErlNifResourceType*) enif_priv_data(env);
    CHECK(env, sol_type)

    // read parent solutions
    for (i=0; i<2; i++){
        CHECK(env, enif_get_resource(env, argv[i], sol_type, (void**) &sols[i]))
    }

    #ifdef DEBUG
    print_solution(sols[0],"Genotype1");
    print_solution(sols[1],"Genotype2");
    #endif
    
    // allocate 2 child solution structures
    len = sols[0]->len;
    for (i=0; i<2; i++){
        new_sols[i] = (Solution*) enif_alloc_resource(sol_type, sizeof(Solution));
        CHECK(env, new_sols[i])
        
        terms[i] = enif_make_resource(env, new_sols[i]);
        CHECK(env,terms[i])
        enif_release_resource(new_sols[i]);

        new_sols[i]->len = len;
        new_sols[i]->genotype = (double*) malloc(sizeof(double)*len);
    }


    recombine(sols, new_sols);

    #ifdef DEBUG
    print_solution(new_sols[0],"RecombinedGenotype1");
    print_solution(new_sols[1],"RecombinedGenotype2");
    #endif
    
    // clock_gettime(CLOCK_MONOTONIC, &end);
    // diff = CLOCKS_PER_SEC * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
    // printf("reco=%llu\n", (long long unsigned int) diff);


    return enif_make_tuple2(env, terms[0], terms[1]);
}
Exemplo n.º 4
0
void print_solution(string &x, string &y, M<info>&L,int i, int j)
{
	if(i=0||j==0)return; 
	else
		if(L(i,j).dir==DIA){
			cout<<x[j]<<" "; 
			print_solution(x,y,L,i-1,j-1);
		}else{
			if(L(i,j).dir==SUP)
				print_solution(x,y,L,i-1,j);
			else
				print_solution(x,y,L,i,j-1);
		}
}
void DoubletSolver::solve_helper(std::string str) {
	std::string consider = priority_queue->peek();
	priority_queue->remove();
	closed_list.insert(consider);
	// std::cout << consider << " ";
	if (consider == goal_word) {
		parent_of[consider] = str;
		print_solution(consider);

		std::cout << "\nexpansion = " << expansions << std::endl;
		return;
	}

	expansions++;

	for (std::vector<std::string>::iterator neighbor = dictionary.begin(); neighbor != dictionary.end(); ++neighbor)
	{
		if (differs_by_one(*neighbor, consider) && (closed_list.count(*neighbor) == 0)) {
			if (priority_queue->is_in_heap(*neighbor)) {
				if (g_value[*neighbor] > (g_value[consider] + 1) ) {
					g_value[*neighbor] = g_value[consider] + 1;
					parent_of[*neighbor] = consider;
					priority_queue->update(*neighbor, get_priority(g_value[*neighbor], get_h_value(*neighbor)));
				}
			}
			else {
				g_value[*neighbor] = g_value[consider] + 1;
				parent_of[*neighbor] = consider;
				priority_queue->add(*neighbor, get_priority(g_value[*neighbor], get_h_value(*neighbor)));
			}
		}
	}
	solve_helper(consider);
}
Exemplo n.º 6
0
/* retorna TRUE cuando encuentra una solucion valida */
int backtrack(int a[], int n, int k) {
    if (n == k) {
        if (is_valid_solution(a, n)) {
            print_solution(a, n);
            return TRUE;
        }
        else
            return FALSE;
    }
    else {
        int nr_candidates;
        int candidates[N];
        find_candidates(a, n, k, candidates, &nr_candidates);
        int found;

        int i;
        for (i = 0; i < nr_candidates; ++i) {
            a[k] = candidates[i];
            found = backtrack(a, n, k + 1);
            if (found)
                return TRUE;
        }
        return FALSE;
    }
}
Exemplo n.º 7
0
int main()
{
    pthread_t threads[NUM_WORKER_THREADS+1];
    long i = 0;
    int rc = 0;

    initialize_cond_objects();

    for (i = 0; i < NUM_WORKER_THREADS; i++) {
        rc = pthread_create(&threads[i], NULL, worker, (void *)i);
        if (rc) {
            perror("pthread_create");
            return 1;
        }
    }
    rc = pthread_create(&threads[NUM_WORKER_THREADS], NULL,
                        resource_generator, NULL);
    if (rc) {
        perror("pthread_create");
        return 1;
    }

    for (i = 0; i < NUM_WORKER_THREADS + 1; i++) {
        rc = pthread_join(threads[i], NULL);
        if (rc) {
            perror("pthread_join");
            return 1;
        }
    }

    destroy_cond_objects();
    print_solution();
    return 0;
}
Exemplo n.º 8
0
void queens(int i)
{
char resp;
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
printf ("\nType any letter to get another solution (Q for Quit):  \n");
scanf (" %c",&resp);
if (resp== 'Q') exit(0);
//getch();
//exit(0);
//getch();
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
Exemplo n.º 9
0
static ERL_NIF_TERM evaluate_solution(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){

    // long diff;
    // struct timespec start, end;
    // clock_gettime(CLOCK_MONOTONIC, &start);

    ErlNifResourceType* sol_type;
    Solution* sol;
    double fitness;

    CHECK(env, argc == 1)

    sol_type = (ErlNifResourceType*) enif_priv_data(env);
    CHECK(env, sol_type)

    CHECK(env, enif_get_resource(env, argv[0], sol_type, (void**) &sol))

    #ifdef DEBUG
    print_solution(sol,"Genotype");
    #endif

    fitness = fitness_rastrigin(sol);

    // clock_gettime(CLOCK_MONOTONIC, &end);
    // diff = CLOCKS_PER_SEC * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
    // printf("eval=%llu\n", (long long unsigned int) diff);


    return enif_make_double(env, fitness);

}
Exemplo n.º 10
0
// input form of SAT expression: 2,1 -2,3,-4
int main(int argc, char** argv) {
  int* num_vars_ptr = new int;
  std::vector <std::vector<int> > expr = parse(argc, argv, num_vars_ptr); // assume this is initialized
  int num_vars = *num_vars_ptr;

  // contains current clause true/false values
  std::vector<int> sat_vals;
  for (int i = 0; i < num_vars; i++) {
    sat_vals.push_back(-1);
  }

  for (int rep_num = 0; rep_num < pow(2, num_vars); rep_num++) {
    int rep_temp = rep_num;
    // fill in the SAT expr with a brute force attempt
    for (int i = 0; i < num_vars; i++) {
      int bit = rep_temp & 0x1;
      sat_vals.at(i) = bit;
      rep_temp >>= 1;
    }

    // check to see if the current SAT expression is satisfiable
    if (is_satisfiable(expr, sat_vals)) {
      printf("Solution found!\n");
      print_solution(sat_vals);
      delete num_vars_ptr;
      return 0;
    }
  }

  printf("No solution found.\n");
  delete num_vars_ptr;
  return 1;
}
int main(int argc, char *argv[])
{
    double p[4];
    double x0[2], x[2], xderivs[7][2];
    double t, tmin, tmax;
    int numsamples;
    int i;

    /*
     *  Set the pendulum parameters.
     */
    p[0] = 9.81;   /*  g  */
    p[1] = 0.25;   /*  b  */
    p[2] = 1.0;    /*  L  */
    p[3] = 1.0;    /*  m  */

    /*
     *  x0 holds the point where we will do the Taylor expansion.
     */  
    x0[0] =  1.0;      /* theta(0) */
    x0[1] =  1.5;      /* v(0)     */

    pendulum_derivs7(xderivs, x0, p);

    tmin =  0.0;
    tmax =  1.0;
    numsamples = 101;

    for (i = 0; i < numsamples; ++i) {
        t = tmin + i*(tmax - tmin)/(numsamples - 1);
        pendulum_evaltaylor7(x, t, x0, xderivs);
        print_solution(t, x);
    }
}
Exemplo n.º 12
0
Arquivo: windll.c Projeto: ks6g10/CA
/* Print the solution */
void __declspec(dllexport) WINAPI _print_solution(lprec *lp)
 {
  if (lp != NULL) {
   freebuferror();
   print_solution(lp);
  }
 }
Exemplo n.º 13
0
int main(void) {
    int i1 = 1, j1 = 2, k1 = 2;
    /* Give i1, j1 and k1 all possible values with 0 < i1 < j1 < k1 < 9. */
    while (create_partition(&i1, &j1, &k1)) {
        int numbers1[4];
        /* Store in numbers1 the number consisting
         * of the first i1 digits in digits[],
         * then the number consisting of the j1 - i1 next digits in digits[],
         * then the number consisting of the k1 - j1 next digits in digits[],
         * and eventually the number consisting
         * of the remaining digits in digits[],
         * with at least 2 of those remaining digits.*/
        generate_numbers(i1, j1, k1, numbers1);
        int i2 = i1;
        int j2 = j1;
        int k2 = k1;
        /* Give i2, j2 and k2 all possible values with 0 < i2 < j2 < k2 < 9
         * and (i1, j1, k1) < (i2, j2, k2). */
        while (create_partition(&i2, &j2, &k2)) {
            int numbers2[4];
            /* Store in numbers2 the number consisting
             * of the first i2 digits in digits[],
             * then the number consisting of the j2 - i2 next digits in digits[],
             * then the number consisting of the k2 - j2 next digits in digits[],
             * and eventually the number consisting
             * of the remaining digits in digits[],
             * with at least 2 of those remaining digits.*/
            generate_numbers(i2, j2, k2, numbers2);
            int product = numbers1[0] * numbers1[1] * numbers1[2] * numbers1[3];
            if (numbers2[0] * numbers2[1] * numbers2[2] * numbers2[3] == product)
                print_solution(numbers1, numbers2, product);
        }
    }
    return EXIT_SUCCESS;
}
Exemplo n.º 14
0
int main()
{
clrscr();
queens(1);
print_solution();
getch();
return(0);
}
Exemplo n.º 15
0
static ERL_NIF_TERM mutate_solution(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){

    // struct timespec start, end;
    // long diff;
    // clock_gettime(CLOCK_MONOTONIC, &start);

    ERL_NIF_TERM term;
    ErlNifResourceType* sol_type;
    Solution *sol, *mut_sol;
    // unsigned int i;
    double range, rate;

    CHECK(env, argc == 3)

    sol_type = (ErlNifResourceType*) enif_priv_data(env);
    CHECK(env, sol_type)

    CHECK(env, enif_get_resource(env, argv[0], sol_type, (void**) &sol))
    CHECK(env, enif_get_double(env, argv[1], &range))
    CHECK(env, enif_get_double(env, argv[2], &rate))

    mut_sol = (Solution*) enif_alloc_resource(sol_type, sizeof(Solution));
    CHECK(env, mut_sol)
    
    term = enif_make_resource(env, mut_sol);
    CHECK(env,term)
    enif_release_resource(mut_sol);

    mut_sol->len = sol->len;
    mut_sol->genotype = (double*) malloc(sizeof(double)*sol->len);

    mutate(sol, mut_sol, range, rate);

    #ifdef DEBUG
    print_solution(sol, "Genotype");
    print_solution(mut_sol, "MutatedGenotype");
    #endif

    // clock_gettime(CLOCK_MONOTONIC, &end);
    // diff = CLOCKS_PER_SEC * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
    // printf("mut=%llu\n", (long long unsigned int) diff);

    return term;

}
Exemplo n.º 16
0
void		solve(t_tetab tetrimini, t_i const length)
{
	t_i side;

	side = guess_what(length);
	while (!back_track(tetrimini, length, side, 0))
		side++;
	print_solution(tetrimini, length, side);
}
Exemplo n.º 17
0
int main(void){
	int n,i,j,flag;
	float **a,*b,*x,sum,*temp;
	printf("ENTER THE NUMBER OF SIMULTANEOUS EQUATIONS TO BE SOLVED: \n");
	scanf("%d",&n);                                     // Number of equations
	a=(float**)malloc(n*sizeof(float*));
	for(i=1;i<=n;i++){
		a[i]=(float*)malloc(n*sizeof(float));
	}
	b=(float*)malloc(n*sizeof(float));
	x=(float*)malloc(n*sizeof(float));
	temp=(float*)malloc(n*sizeof(float));
	printf("ENTER THE COEFICIENT MATRIX : \n");
	for(i=1;i<=n;i++){
		for(j=1;j<=n;j++){
			a[i][j]=input();                              // Coefficient Matrix
		}
	}
	printf("ENTER THE RIGHT HAND SIDE OF THE MATRIX : \n");
	for(i=1;i<=n;i++){
		scanf("%f",&b[i]);
	}
	for(i=1;i<=n;i++){
		x[i]=0;
	}
	printf("Iteration    x[1]         x[1]          x[2]\n");
	int count=0;
	do{
		flag=0;
		for(i=1;i<=n;i++){
			x[i]=temp[i];               //      Copying it into the temporary matrix for error calculation and updating x only once
		}
	    printf("    %d     %0.5f       %0.5f       %0.5f\n",++count,temp[1],temp[2],temp[3]);
	    for(i=1;i<=n;i++){
		    sum=0;
		    for(j=1;j<=n;j++){
			    if(i!=j){
				    sum+=a[i][j]*x[j];      // Solving for the x ith term with respect to the rest x i's
			    }
		    }
		    temp[i]=(b[i]-sum)/a[i][i];
	    }
	    /*for(i=1;i<=n;i++){
		    if(fabs(temp[i]-x[i])>=0.000001){
			    flag=1;                        
			    break;
		    }
        } */
        flag=error_check(temp,x,n);
        if(flag==1)
            break;
 
	}while(flag==1);
	print_solution(temp,n);
	
}
Exemplo n.º 18
0
long bip_enumerate(const bip bip, bool with_output)
{
        assert(is_initialized(bip));
        clock_t start = clock();
        long long     solus = 0;
        long long     count = 0;
    if (with_output)printf("The solution vectors are: \n");
        for(unsigned long long bitvec = 0; bitvec < (1uL << bip.columns); bitvec++)
           {
              unsigned long long mask = 1;  // long long because long is 32 bit on 32 bit computers
                   int    x[bip.columns];
            
                assert(sizeof(bitvec) * 8 > bip.columns); //lint !e506
                  for(int j = 0; j < bip.columns; j++, mask <<= 1)
                          x[j] = (bitvec & mask) ? 1.0 : 0.0;
               if (bip.ordin==eq) {
                   if (is_Solution_eq(bip, x)){
                       if (with_output)
                           print_solution(x, bip.columns);
                       
                       solus++;
                   }
               }else{
                   if (is_Solution(bip, x)) //lint !e772
                   {
                       if (with_output)
                           print_solution(x, bip.columns);
                       
                       solus++;
                   }
               }
               
                  count++;
            }
       assert((unsigned)count == (1u << bip.columns));
    
        double elapsed = GET_SEC(start, clock());
    
        printf(" %lld vectors were tested in %.3f s = %.3f kvecs/s\n",
                    count, elapsed, count / elapsed / 1000.0);
    
        return solus;
     }
Exemplo n.º 19
0
int 
main(int argc, char** argv)
{

     int ncpu = (int)sysconf(_SC_NPROCESSORS_ONLN);
#ifdef DEBUG
     printf ("Configured for %d CPU\n",ncpu);
#endif     


     Graph *graph = graph_new (1024);
     if (argc > 0){
	  read_case_file (graph, argv [1]);
     }

     int num_threads = ncpu + 1;

     nodes = graph_get_nodes (graph);
     num_nodes = graph_get_num_nodes (graph);

     int i;
     for (i = 0;i<num_nodes;i++){
	  qsort (&nodes[i]->edges[0], nodes[i]->num_edges, sizeof (GraphEdge*), cmp_edges_by_weight);
     }


     int elem_per_thread = (num_nodes / num_threads) + 1;

     int **arr = malloc (sizeof (int*) * num_threads); 
     for (i = 0; i < num_threads; i++){
	  arr[i] = malloc (sizeof (int) * (elem_per_thread + 2));
	  arr[i][0] = i;
	  arr[i][1] = 0;
     }

     for (i = 0; i < num_nodes; i++){
	  int y = i % num_threads;
	  int x = arr[y][1] + 2;
	  arr[y][x] = i;
	  arr[y][1] = arr[y][1] + 1;
     }


     pthread_t tids[num_threads];
     for (i = 0; i < num_threads;i++){
	  pthread_create (&tids[i], NULL, &pthread_main, arr[i]);
     }
     for (i = 0; i < num_threads; i++){
	  pthread_join (tids[i], NULL);
     }

     if (best_found_path)
	  print_solution (best_found_path);
     return 0;
}
Exemplo n.º 20
0
main()
{
	tsp_instance t;			/* tsp points */
	tsp_solution s;			/* tsp solution */
	double initCost, finCost;

	read_tsp(&t);
	initialize_solution(t.n, &s);
	initCost=solution_cost(&s,&t);
	printf("solution_cost = %7.1f\n",initCost);
	print_solution(&s);


	solution_count=0;
	repeated_annealing(&t,5,&s);
	finCost = solution_cost(&s,&t);
	printf("repeated annealing %d iterations, cost = %7.1f    improvement %%%2.0f\n", solution_count, finCost, (finCost/initCost)*100);
	print_solution(&s);

}
Exemplo n.º 21
0
int LoadBalancing::lp_solve_model() {
	//Returns 0 when an optimal solution is found,
	//returns 1 if the solution is suboptimal due to an overlap constraint, and we should use fewer nodes
	//returns 2 when a suboptimal solution is found (solver timed out)
	//returns 3 if another error occurred

	int ret;
	int Ncol=3*num_using_nodes_+(num_using_nodes_-1)*(num_quantiles_+2);
	REAL *vars = (REAL*)malloc(Ncol*sizeof(REAL));

	set_verbose(lp, IMPORTANT);
	set_timeout(lp, solver_timeout_);
	default_basis(lp);

	ret = solve(lp);
	if(ret==1){
		fprintf(stderr, "lp_solve: Suboptimal solution (solver timed out)\n");
		return 2;
	}
	if(ret!=0 && ret!=1){
		fprintf(stderr, "lp_solve: Solution not found\n");
		return 3;
	}

	print_solution(lp, 3);
	get_variables(lp, vars);

	//Cutvector:
	optimal_cutvector_.resize(num_using_nodes_);
	for(int i=0;i<num_using_nodes_;i++){
		optimal_cutvector_.at(i)=round(width_*vars[i]);
	}
	//Estimated completion time:
	est_completion_time_=(float)vars[num_using_nodes_];

/*	printf("\nOptimal cutvector:\n");
	for(int i=0;i<num_using_nodes_;i++){
		printf("%d\n", optimal_cutvector_.at(i));
	}

	printf("Estimated completion time: %f\n", est_completion_time_);
*/

	//If the first cut is 0, that would be an indication that the cutvector we obtained is suboptimal,
	//due to the overlap constraint.
	//We should most likely use fewer nodes.
	if(optimal_cutvector_.front()==0){
		fprintf(stderr, "lp_solve: Suboptimal solution (first cut was 0), we should use fewer processing nodes\n");
		return 1;
	}

	free(vars);
	return ret;
}
Exemplo n.º 22
0
int main(void) {
  read_input();
  
  int solved = solver();
  if(solved)
    print_solution();
  else
    printf("Sorry, a solution could not be found!\n");
  
  return(0);
}
Exemplo n.º 23
0
int			go(tetrimini, length, side)
{
	char	map[side * side];

	if (back_track(tetrimini, length, side, map, 0))
	{
		print_solution(map, side);
		return (1);
	}
	return (0);
}
Exemplo n.º 24
0
Arquivo: tsp.c Projeto: LihuaWu/recipe
main()
{
	tsp_instance t;			/* tsp points */
	tsp_solution s;			/* tsp solution */
	int i;				/* counter*/
	double solution_cost();

	read_tsp(&t);
	/*print_tsp(&t);*/

	read_solution(&s);
	printf("OPTIMAL SOLUTION COST = %7.1f\n",solution_cost(&s,&t));
        print_solution(&s);


	initialize_solution(t.n, &s);
	printf("solution_cost = %7.1f\n",solution_cost(&s,&t));
	print_solution(&s);

	
/*
	solution_count=0;
	random_sampling(&t,1500000,&s);
        printf("random sampling %d iterations, cost = %7.1f\n",
			solution_count,solution_cost(&s,&t));
       	print_solution(&s);

	solution_count=0;
        repeated_hill_climbing(&t,195,&s);
        printf("repeated hill climbing %d iterations, cost = %7.1f\n",
                        solution_count,solution_cost(&s,&t));
        print_solution(&s);
*/

	solution_count=0;
	repeated_annealing(&t,3,&s);
	printf("repeated annealing %d iterations, cost = %7.1f\n",
                        solution_count,solution_cost(&s,&t));
	print_solution(&s);

}
Exemplo n.º 25
0
void tsp (int hops, int len, uint64_t vpres, tsp_path_t path, long long int *cuts, tsp_path_t sol, int *sol_len)
{
    if (len + cutprefix[(nb_towns-hops)] >= minimum) {
      (*cuts)++ ;
      return;
    }

    /* calcul de l'arbre couvrant comme borne inférieure */
    if ((nb_towns - hops) > 6 &&
	lower_bound_using_hk(path, hops, len, vpres) >= minimum) {
      (*cuts)++;
      return;
    }


    /* un rayon de coupure à 15, pour ne pas lancer la programmation
       linéaire pour les petits arbres, plus rapide à calculer sans */
    if ((nb_towns - hops) > 22
	&& lower_bound_using_lp(path, hops, len, vpres) >= minimum) {
      (*cuts)++;
      return;
    }

  
    if (hops == nb_towns) {
	    int me = path [hops - 1];
	    int dist = tsp_distance[me][0]; // retourner en 0
            if ( len + dist < minimum ) {
			pthread_mutex_lock(&minimum_mutex);
            if ( len + dist < minimum ) {
				minimum = len + dist;
				*sol_len = len + dist;
				memcpy(sol, path, nb_towns*sizeof(int));
				if (!quiet)
				  print_solution (path, len+dist);
			}
			pthread_mutex_unlock(&minimum_mutex);
	    }
    } else {
        int me = path [hops - 1];        
        for (int i = 0; i < nb_towns; i++) {
	  if (!present (i, hops, path, vpres)) {
                path[hops] = i;
		vpres |= (1<<i);
                int dist = tsp_distance[me][i];
                tsp (hops + 1, len + dist, vpres, path, cuts, sol, sol_len);
		vpres &= (~(1<<i));
            }
        }
    }
}
Exemplo n.º 26
0
int main(void) {
    /* For each of the 8 digits 2, 3,..., 9, say d, generate one of 3 numbers:
     * - 1 causes d to become the rightmost digit of the number being built;
     * - 0 causes
     *     . the number being built to be considered fully built
     *       and subtracted or added to the running sum,
     *     . the next number to be built to begin with d and eventually
     *       be subtracted to the running sum;
     * - 2 causes
     *     . the number being built to be considered fully built
     *       and subtracted or added to the running sum,
     *     . the next number to be built to begin with d and eventually
     *       be added to the running sum. */
    for (int i = 0; i < pow(3, 8); ++i) {
        /* Let the first number be of the form 1... */
        if (test(1, i))
            print_solution(1, i);
        /* Let the first number be of the form -1... */
        if (test(-1, i))
            print_solution(-1, i);
    }
    return EXIT_SUCCESS;
}
Exemplo n.º 27
0
/*
 * 简单暴力实现法
 */
void circle_play(void)
{
	int i, j;
	int flag;

	for (i = 1, j = 1; i <= BOARD_SIZE;) {
		flag = 0;
		for (; j <= BOARD_SIZE; ++j) {
			printf("start_i = %d, start_j = %d\n", i, j);
			if (check_pos(i, j)) {
				/* 符合规则,放棋 */
				printf("set chess [%d][%d]\n", i, j);
				flag = 1;
				CHESS[i] = j;
				set_attack_area(i, j);
				break;
			}
			/* 如果当前列不符合,则继续检查下一列 */
		}
		if (flag == 0) {
			/* 回溯,设置上一层棋子的位置 */
			--i; // 返回上一层
			if (i <= 0)
				break; // end
			j = CHESS[i] + 1; // 要向右移一格
			printf("return to level [%d], column [%d]\n", i, j);
			/* 要把上一层设置的棋子位置和攻击区域清除 */
			CHESS[i] = 0;
			reset_attack_area();
		} else {
			/* 下一层 */
			++i;

			/* 如果最后一层处理完,说明求出一个解了,
			 * 继续往下求,直到回溯时i为0 */
			if (i > BOARD_SIZE) {
				print_solution();
				--i;
				++j;
				/* 把位置和攻击区域清除 */
				CHESS[i] = 0;
				reset_attack_area();
			} else {
				/* 下一层从第一列开始 */
				j = 1;
			}
		}
	}
}
Exemplo n.º 28
0
void queens(int i)
{
    for(t[i]=1;t[i]<=N;t[i]++)
    {
        if(empty(i))
       {
            if(i==N)
             {
                 print_solution();
                 //exit(0);
             }
            else
               queens(i+1);
        }
    }
}
Exemplo n.º 29
0
int main(const int argc, const char** argv) {
	if (argc <= 1) {
		throw("No param\n");
	}
	
	int numberfunc;
	char var2, var1;
	std::string truth_table;

	vSet vertexList;
	BoolVertexEdge_list main_table;
	SlnTable solution;

	std::ifstream in(argv[1]);
	std::ofstream out(argv[2]);	
	 
	in >> numberfunc;
	
	for (int i = 0; i < numberfunc; i++) {
		in >> var1 >> var2 >> truth_table;
		func tempfunction(var1, var2, truth_table);

		BoolVertexEdge_list temp = get_edges_BoolVertex(tempfunction);

		for (const Edge &v: temp) {
			if (main_table.find(v) == main_table.end()) {
				main_table.insert(v);
			}
			vertexList.insert(v.first);
			vertexList.insert(v.second);
		}
	}

	Graph< BoolVertex, AreBoolVerticesConnected > g(vertexList.begin(), vertexList.end(), main_table.begin(), main_table.end());
	std::vector< std::set< BoolVertex > > cond = g.build_condensation();
		
	if (!SolutionExists(cond.begin(), cond.end())) {
		std::cout << "No solution\n";
		return 0;
	}

	solution = MarkingBoolVertex(main_table, cond);		   
	print_solution(out, solution.begin(), solution.end());

	return 0;
}
Exemplo n.º 30
0
void combine (int *combination, int curr_idx) {
    int aux[SIZE];

    if (curr_idx < 0)
        return;

    memcpy (aux, combination, sizeof(int)*SIZE);
    while (curr_idx >= 0) {
        do {
            print_solution (aux);
            aux[curr_idx]++;
        } while (aux[curr_idx] < MAX_CHARS);

        combine (aux, curr_idx-1);
        curr_idx--;
    }
}