Пример #1
0
int		try_move(int **tab, int row, int col, int is_reverse)
{
	int i;

	i = 0;
	while (i < 9)
	{
		if (is_valid_move(tab, i + 1, row, col))
		{
			tab[row][col] = i + 1;
			if ((col + 1) < 9)
				if (find_solution(tab, row, col + 1, is_reverse))
					return (1);
				else
					tab[row][col] = 0;
			else if ((row + 1) < 9)
				if (find_solution(tab, row + 1, 0, is_reverse))
					return (1);
				else
					tab[row][col] = 0;
			else
				return (1);
		}
		i++;
	}
	return (0);
}
Пример #2
0
void FlipFlap::setup(int level){						//setup play screen
  initials=name_box->get_string();						//get their initials
  if(initials.size() == 0)							//if none entered, create "---"
        initials = "---";
  detach(*name_box);								//remove input box from screen
  for(int i = 0; i < level_buttons.size(); ++i)					//remove level select buttons from screen
    detach(level_buttons[i]);
  for(int i = 0; i < high_score_list.size(); ++i)				//remove high schores from screen
    detach(high_score_list[i]);
  current_flips = 0;
  current_level = level;
  //draw pancakes
  game_stack = pancake_stack(level);						//initialize stack of ints
  game_stack_p.resize(game_stack.size());					//initialize stack of pancakes
  for(int i = 0; i < game_stack.size(); ++i){
    game_stack_p[i] = new Pancake(game_stack[i],i);
  }
  for(Pancake* pancake : game_stack_p){						//attach stack of pancakes
    attach(*pancake);
  }
  //get min_flips
  vector<int> *solution = find_solution(game_stack);				//calculate minimum needed flips
  min_flips = solution->size();
  //draw buttons
  button_list(level);								//create flip buttons
  //display score
  add_boxes();									//add on screen counters
  redraw();									//draw window
}
Пример #3
0
void run (int height_coordinate, int width_coordinate){

    move *moves_array = create_move_array (MOVES_MAX);
    Node *final_board, *start;
    int move_count = 0, target_found = 0;
    int initial_board [BOARD_HEIGHT][BOARD_WIDTH];

    populate_board (initial_board);
    start = allocate_start_node (initial_board);
    target_found = check_for_target (initial_board, height_coordinate, width_coordinate);

    if (!target_found){
        final_board = find_solution (start, height_coordinate, width_coordinate);
        move_count = populate_moves_array (final_board, moves_array);
        //to copy start board into last element of moves array for printing
        copy_board ((moves_array+(move_count-1))->board, start->board);
        print_moves_SDL (moves_array, move_count);
        // print_moves (moves_array, move_count);
    }

    else {
        print_list_SDL (start);
        printf("Target already on board\n");
    }

    // print_list(start);

    free_list (start);
    free (moves_array);
}
Пример #4
0
	bool find_solution(int n, Square* t)
	{
		for (; n < SIZE && t[n].v != 0; n++) ; //Skips those who already has values.

		if (n == SIZE) //solution found, if compiled with false, it will do all posible combinations.
			return true;

		int brukt = t[n].GetPosibles(); //Find all posible values to try.

		if (brukt == ALL) //If none values is posible, this path cannot be a part of the solution.
			return false;

		for (int i = 1; i < FINAL; i <<= 1)
			if ((brukt & i) == EMPTY) //Checks if value(i) is a posible,
			{                         // EMPTY means that it is not a conflict on x, y or g, and might be a posibility.
				t[n].SetValue(i); //Sets i as a posbile.

				if (find_solution(n + 1, t)) //Tries next position.
					return true;

				t[n].RemoveValue(); //Removes i as a posbile.
			}

		return false; //solution not found, yet.
	}
Пример #5
0
//Calculates user's score
int Pancake_stack::calc_score()
{
	int diff = index.size();
	cout << find_solution(index)->size();
//	int min_flips = find_solution(index);
	int min_flips = 1;
	int score = (100 - (num_flips - (min_flips - 1))) * diff;

	return score;
}
Пример #6
0
/* Create a puzzle with as many empty grids as possible
   by randomly assigning empty grids' positions.*/ 
void create(){ 
  int i,j,k;
  int tmp[SIZE][SIZE][2]; 
  int index_cnt; 
  int n_empty; 
  int s_time;

  //printf("Current biggest number of empty grids.\n");
  for(i=0; i<SIZE; ++i){ 
    for(j=0; j<SIZE; ++j){ 
      tmp[i][j][1]=sudoku[i][j]; 
      tmp[i][j][0]=EMPTY; 
    } 
  }
  for(s_time=0; s_time<S_TIME; ++s_time){
    n_empty=0;
    for(i=0; i<=SIZE/2; ++i){ 
      for(j=0; j<SIZE && !(i==SIZE/2&&j==SIZE/2+1); ++j){ 
	// P(rand_01(m,n)=0)=m/n
	// So expectancy of the number of empty grids 
	// will be max_empty+1
	k=rand_01(max_empty+1,SIZE*SIZE);
	if(i!=SIZE/2||j!=SIZE/2) 
	  n_empty+=2-2*k; 
	else 
	  n_empty+=1-k; 
	sudoku[i][j]=tmp[i][j][k]; 
	sudoku[SIZE-1-i][SIZE-1-j]=tmp[SIZE-1-i][SIZE-1-j][k]; 
      } 
    }
    if(n_empty>=limit_empty-norm && n_empty<=limit_empty && n_empty<54){ 
      find_solution(); 
      if(n_ans==1){
	if(n_empty>max_empty){
	  max_empty=n_empty;
	}
	if(max_empty>=limit_empty){
	  save_result(sudoku);
	  return;
	}
	generate(empty(sudoku));
      } 
    } 
  }

  //printf("DONE\n");  
  for(i=0; i<SIZE; ++i){ 
    for(j=0; j<SIZE; ++j){ 
      sudoku[i][j]=tmp[i][j][1];
    } 
  }
} 
Пример #7
0
int		find_solution(int **tab, int row, int col, int is_reverse)
{
	if (!(row < 9 && col < 9))
		return (1);
	if (tab[row][col] != 0)
	{
		if ((col + 1) < 9)
			return (find_solution(tab, row, col + 1, is_reverse));
		else if ((row + 1) < 9)
			return (find_solution(tab, row + 1, 0, is_reverse));
		else
			return (1);
	}
	else
	{
		if (is_reverse)
			return (try_move_rev(tab, row, col, is_reverse));
		else
			return (try_move(tab, row, col, is_reverse));
	}
	return (0);
}
Пример #8
0
int		main(int argc, char **argv)
{
	int **tab;
	int **tab_rev;

	tab = alloc_tab();
	tab_rev = alloc_tab();
	if (argc != 10)
		return (throw_error());
	if (!populate_tab(tab, argc, argv))
		return (0);
	populate_tab(tab_rev, argc, argv);
	find_solution(tab, 0, 0, 0);
	find_solution(tab_rev, 0, 0, 1);
	if (compare_solution(tab, tab_rev))
		print_tab(tab);
	else
		ft_putstr("Erreur\n");
	free_tab(tab);
	free_tab(tab_rev);
	return (0);
}
Пример #9
0
// Generate more empty grids of puzzles found in simulating process
// Their number of empty grids >= limit_empty-norm
// So the odds of finding a puzzle with limit_empty number of empty grids
// recursively by removing numbers from them are fairly high.
void generate(int n_empty){
  int i,j,k; 
  int row,col; 
  int generate_tmp[SIZE][SIZE][2]; 

  if(max_empty>=limit_empty){
    save_result(sudoku);
    return;
  }

  for(i=0; i<SIZE; ++i){ 
    for(j=0; j<SIZE; ++j){ 
      generate_tmp[i][j][1]=sudoku[i][j]; 
      generate_tmp[i][j][0]=EMPTY; 
    } 
  }
  
  for(i=0; i<=SIZE/2; ++i){ 
    for(j=0; j<SIZE && !(i==SIZE/2&&j==SIZE/2+1); ++j){ 
      if(generate_tmp[i][j][1]!=EMPTY){
	// remove numbers from (i,j) and (SIZE-1-i,SIZE-i-j)
	k=0;
	sudoku[i][j]=generate_tmp[i][j][k]; 
	sudoku[SIZE-1-i][SIZE-1-j]=generate_tmp[SIZE-1-i][SIZE-1-j][k]; 	  
	find_solution(); 
	if(n_ans==1){  
	  // Recursively generate more
	  if(i!=SIZE/2||j!=SIZE/2){
	    if(n_empty+2>max_empty)
	      max_empty=n_empty+2;
	    generate(n_empty+2);
	  }
	  else {
	    if(n_empty+1>max_empty)
	      max_empty=n_empty+1;
	    generate(n_empty+1);
	  }
	  if(max_empty>=limit_empty){
	    save_result(sudoku);
	    return;
	  }
	}
	k=1;
	sudoku[i][j]=generate_tmp[i][j][k]; 
	sudoku[SIZE-1-i][SIZE-1-j]=generate_tmp[SIZE-1-i][SIZE-1-j][k];
      }
    } 
  }
}
Пример #10
0
void
OLCDijkstra::add_edges(DijkstraTaskPoint &dijkstra, const ScanTaskPoint& origin)
{
  ScanTaskPoint destination(origin.first + 1, origin.second);

  find_solution(dijkstra, origin);

  for (; destination.second != n_points; ++destination.second) {
    if (admit_candidate(destination)) {
      const unsigned d = get_weighting(origin.first) *
                         distance(origin, destination);
      dijkstra.link(destination, origin, d);
    }
  }
}
Пример #11
0
	void find_solution(int arr[])
	{
		for (int i = 0; i < WIDTH; i++) //Reset all values in shared static array.
			Square::xa[i] = Square::ya[i] = Square::ga[i] = EMPTY;
		
		Square* b = new Square[SIZE];
		for (int i = 0; i < SIZE; i++) //Convert from value array to Square array.
			b[i].Populate(i, arr[i]); //Populate the array.

		find_solution(0, b);

		for (int i = 0; i < SIZE; i++)	//Set solution from bit stream to 10base values.
			arr[i] = GetUnShifted(b[i].v);

		delete[] b; //Cleanup array.
	}
Пример #12
0
int main(int argc, char *argv[])
{
  GSList *words, *letters, *constraints, *ll;
  GPtrArray *dictionary;
  gchar *grid;
  struct wordvar *w;

  if (argc != 3) {
    printf("usage: %s grid dictionary\n", argv[0]);
    exit (-1);
  }
  
  words = letters = constraints = NULL;

  grid = read_grid(argv[1], &words, &letters, &constraints);
  dictionary = read_words(argv[2]);
  init_vars(words, letters, dictionary);

  printf("%s\n", grid);

  w = words->data;
  printf("Initial %d\n", w->possible_values->len);

  for (ll = constraints; ll != NULL; ll = ll->next) {
    struct constraint *c = ll->data;
    put_constraint_on_queue(c);
  }

  run_constraints();

  printf("First %d\n", w->possible_values->len);

  for (ll = constraints; ll != NULL; ll = ll->next) {
    struct constraint *c = ll->data;
    put_constraint_on_queue(c);
  }


  total = 0;
  find_solution(words, letters, grid, 0);
  printf("total %d\n", total);


  return (0);
}
Пример #13
0
void
ContestDijkstra::add_edges(const ScanTaskPoint& origin)
{
  ScanTaskPoint destination(origin.stage_number + 1, origin.point_index);

  find_solution(origin);

  // only add last point!
  if (is_final(destination)) {
    assert(n_points > 0);
    destination.point_index = n_points - 1;
  }

  for (; destination.point_index != n_points; ++destination.point_index) {
    if (admit_candidate(destination)) {
      const unsigned d = get_weighting(origin.stage_number) *
                         distance(origin, destination);
      dijkstra.link(destination, origin, d);
    }
  }
}
main()

{
    unsigned int    var     = 0;
    char            buf[50] = {'\0'};
    unsigned int    solution[3]  = {'\0'};

    while(fgets(buf,sizeof(buf),stdin)){
        sscanf(buf,"%u",&var);
        find_solution(var,solution,3);
        if(solution[0] == '\0'){
            printf("No Solution found \n");
        }
        else{
            printf("%d coins of 4 asiap each\n",solution[0]);
            printf("%d coins of 1/2 asiap each\n",solution[1]);
            printf("%d coins of 1/4 asiap each\n",solution[2]);
        }
        printf("===\n");
    }
}
Пример #15
0
void find_solution(struct graph *graph, list_node** solutions,
  list_node* current_solution, int size)
{
  _recursion_count += 1;
  if (_recursion_count == 200)
  {
    _recursion_count = 0;

    MPI_Status status;
    mpi_msg *message;
    char buffer[MSG_LENGTH];

    int flag = 0;
    MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);

    while (flag)
    {
      MPI_Recv(&buffer, MSG_LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG,
        MPI_COMM_WORLD, &status);

      switch (status.MPI_TAG)
      {
        case TAG_REQUEST_DATA:
        {
          list_node *new_top = cut_stack(*solutions);
          message = message_serialize_data(new_top);
          MPI_Send(&message->data, message->length, MPI_CHAR, status.MPI_SOURCE,
            TAG_DATA, MPI_COMM_WORLD);
          free(message);
          list_free(new_top);
          break;
        }
        case TAG_DATA:
          printf("find_solution: received data from %d\n", status.MPI_SOURCE);
          break;
        case TAG_ARE_YOU_FINISHED:
          message = message_serialize_state(MSG_NOT_FINSIHED);
          MPI_Send(&message->data, message->length, MPI_CHAR, status.MPI_SOURCE,
            TAG_MY_FINISH_STATUS, MPI_COMM_WORLD);
          free(message);
          break;
        case TAG_FINISH:
          printf("find_solution: received request to finish from %d\n",
            status.MPI_SOURCE);
          break;
        case TAG_BEST_SOLUTION:
        {
          list_node *other_best_solution = message_deserialize_data(graph,
            buffer);
          double other_best_height = log2(list_size(other_best_solution)) + 1;
          if (other_best_height < best_height)
          {
            best_height = other_best_height;
            best_solution = other_best_solution;
          }
          else
          {
            list_free(other_best_solution);
          }
          break;
        }
        default:
          printf("Unhandled switch branch - %d\n", status.MPI_TAG);
      }

      MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
    }
  }

  int current_solution_node_idx = list_size(current_solution) - size;
  list_node *current_solution_node = list_at_index(current_solution,
    current_solution_node_idx);
  graph_node *current_node = current_solution_node->data;

  int i;
  for (i = current_node->neighbors_count - 1; i >= 0 ; i--)
  {
    graph_node *neighbor = current_node->neighbors[i];

    if ((neighbor->visited))
    {
      continue;
    }

    list_node *new_solution = list_copy(current_solution);
    list_enque(&new_solution, neighbor);

    if (list_size(new_solution) == (2 * size))
    {
      *solutions = list_push(*solutions, new_solution);
    }
    else
    {
      if (neighbor->id != DUMMY_NODE_ID)
      {
        neighbor->visited = 1;
      }

      find_solution(graph, solutions, new_solution, size);
      neighbor->visited = 0;
      list_free(new_solution);
    }
  }
}
Пример #16
0
int main(int argc, char *argv[])
{
  double start_time = MPI_Wtime();
  char buffer[MSG_LENGTH];
  MPI_Status status;
  int my_rank, p;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &p);
  _last_asked = my_rank;

  struct graph *graph = graph_new_from_file(argv[1]);
  int ideal_height = ceilf(log2(graph->size)) + 1;

  list_node *solution;
  list_node *solutions;
  int repeat = 1;

  if (my_rank == 0)
  {
    solution = list_push(NULL, graph->root);
    solutions = list_push(NULL, solution);
  }
  else
  {
    MPI_Send(NULL, 0, MPI_CHAR, 0, TAG_REQUEST_DATA, MPI_COMM_WORLD);
    mpi_msg *message;

    int repeat_probe = 1;
    while (repeat_probe)
    {
      MPI_Recv(&buffer, MSG_LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG,
        MPI_COMM_WORLD, &status);

      switch (status.MPI_TAG)
      {
        case TAG_REQUEST_DATA:
          //printf("p %d received data request\n", p);
          message = message_serialize_data(NULL);
          MPI_Send(&message->data, message->length, MPI_CHAR, status.MPI_SOURCE,
            TAG_DATA, MPI_COMM_WORLD);
          free(message);
          break;
        case TAG_DATA:
          solutions = message_deserialize_data(graph, buffer);
          if (solutions == NULL)
          {
            MPI_Send(NULL, 0, MPI_CHAR, last_asked(p, my_rank),
              TAG_REQUEST_DATA, MPI_COMM_WORLD);
          }
          else
          {
            repeat_probe = 0;
          }
          break;
        case TAG_ARE_YOU_FINISHED:
          message = message_serialize_state(MSG_FINSIHED);
          MPI_Send(&message->data, message->length, MPI_CHAR, status.MPI_SOURCE,
            TAG_MY_FINISH_STATUS, MPI_COMM_WORLD);
          free(message);
          break;
        case TAG_FINISH:
          repeat = 0;
          repeat_probe = 0;
          break;
        default:
          printf("Unhandled switch branch - %d\n", status.MPI_TAG);
      }
    }
  }

  while (repeat)
  {
    while (list_size(solutions) > 0)
    {
      list_node *current_solution = list_pop(&solutions);
      mark_nodes_visited(current_solution);
      double height = log2(list_size(current_solution)) + 1;

      if (graph_all_visited(graph))
      {
        // TODO: Inform others about best solution.
        if (height < best_height)
        {
          printf("height: %d, best_height %d\n", height, best_height);
          best_height = height;
          best_solution = current_solution;

          if (height == ideal_height)
          {
            repeat = 0;
            break;
          }

          mpi_msg *message = message_serialize_data(best_solution);
          int i;
          for (i = 0; i < p; i++)
          {
            if (i == my_rank)
            {
              continue;
            }

            MPI_Send(&message->data, message->length, MPI_CHAR, i,
              TAG_BEST_SOLUTION, MPI_COMM_WORLD);
          }
        }
      }
      else if (height < best_height)
      {
        find_solution(graph, &solutions, current_solution,
          list_size(current_solution));
      }

      mark_nodes_unvisited(current_solution);
      list_free(current_solution);
    }

    if (my_rank == 0)
    {
      if (are_others_finished(p))
      {
        repeat = 0;

        int i;
        for (i = 1; i < p; i++)
        {
          MPI_Send(NULL, 0, MPI_CHAR, i, TAG_FINISH, MPI_COMM_WORLD);
        }

        break;
      }
    }
    else
    {
      int flag = 0;
      MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);

      while (flag)
      {
        MPI_Recv(&buffer, MSG_LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG,
            MPI_COMM_WORLD, &status);

        switch (status.MPI_TAG)
        {
          case TAG_REQUEST_DATA:
          {
            mpi_msg *message = message_serialize_data(NULL);
            MPI_Send(&message->data, message->length, MPI_CHAR,
              status.MPI_SOURCE, TAG_DATA, MPI_COMM_WORLD);
            free(message);
            break;
          }
          case TAG_DATA:
            printf("p %d received data from %d\n", my_rank, status.MPI_SOURCE);
            break;
          case TAG_ARE_YOU_FINISHED:
          {
            mpi_msg *message = message_serialize_state(MSG_FINSIHED);
            MPI_Send(&message->data, message->length, MPI_CHAR,
              status.MPI_SOURCE, TAG_MY_FINISH_STATUS, MPI_COMM_WORLD);
            free(message);
            break;
          }
          case TAG_FINISH:
            repeat = 0;
            break;
          case TAG_BEST_SOLUTION:
          {
            list_node *other_best_solution = message_deserialize_data(graph,
              buffer);
            double other_best_height = log2(list_size(other_best_solution)) + 1;
            if (other_best_height < best_height)
            {
              best_height = other_best_height;
              best_solution = other_best_solution;
            }
            else
            {
              list_free(other_best_solution);
            }
            break;
          }
          default:
            printf("Unhandled switch branch - %d\n", status.MPI_TAG);
        }

        MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
      }
    }

    if (!repeat)
    {
      break;
    }

    MPI_Send(NULL, 0, MPI_CHAR, last_asked(p, my_rank), TAG_REQUEST_DATA,
      MPI_COMM_WORLD);
    MPI_Recv(&buffer, MSG_LENGTH, MPI_CHAR, 0, TAG_DATA, MPI_COMM_WORLD,
      &status);
    solutions = message_deserialize_data(graph, buffer);
  }

  if (my_rank == 0)
  {
    dump_solution(best_solution);
    printf("Execution time is %f\n", MPI_Wtime() - start_time);
  }
  graph_free(graph);
  printf("[%d] terminating...\n", my_rank);
  MPI_Finalize();

  return 0;
}
Пример #17
0
int main(const int argc, const char * argv[])
{
    const char * program_short_name,
               * input_name,
               * output_name;
    unsigned int nb_mutations;
    instance data;
    solution sol;
    chrono timer;
    int read_status,
        write_status;

    program_short_name = get_program_short_name(argv[0]);

    if((argc != 3) && (argc != 4))
    {
        printf("Syntaxe pour utiliser ce programme :\t");
        printf("%s  input_name  output_name  nb_mutations\n", program_short_name);
        puts("\tinput_name  \tnom du ficher contenant l'instance (obligatoire)");
        puts("\toutput_name \tnom du ficher dans lequel ecrire la solution (obligatoire)");
        puts("\tnb_mutations\tnombre de mutations a chaque iteration de l'algorithme (optionnel ; valeur par defaut = nombre de jobs dans l'instance)");
        return EXIT_FAILURE;
    }

    input_name = argv[1];
    output_name = argv[2];
    switch(argc)
    {
        case(3):
            nb_mutations = 0;
        break;

        case(4):
            nb_mutations = read_nb_mutations(argv[3]);
            if(nb_mutations == 0)
            {
                printf("Erreur : nombre de mutations incorrect (\"%s\")\n", argv[3]);
                return EXIT_FAILURE;
            }
        break;
    }

    read_status = read_instance(&data, input_name);

    switch(read_status)
    {
        case(INPUT_ERROR_OPEN):
            printf("Erreur : impossible d'ouvrir le fichier \"%s\"\n", input_name);
        return EXIT_FAILURE;

        case(INPUT_ERROR_SYNTAX):
            printf("Erreur : la syntaxe du fichier \"%s\" est incorrecte.\n", input_name);
        return EXIT_FAILURE;

        case(INPUT_SUCCESS):
            puts("Lecture de l'instance : OK");

            timer = chrono_new();
            srand(time(NULL));

            puts("Algorithme : START");
            chrono_start(timer);
            sol = find_solution(data, nb_mutations);
            chrono_stop(timer);
            puts("Algorithme : STOP");

            solution_set_cpu_time(sol, chrono_get_time(timer));
            write_status = write_solution(&sol, output_name);

            solution_delete(sol);
            instance_delete(data);
            chrono_delete(timer);

            switch(write_status)
            {
                case(OUTPUT_ERROR):
                    printf("Erreur : impossible d'ouvrir ou de creer le fichier \"%s\"\n", output_name);
                return EXIT_FAILURE;

                case(OUTPUT_SUCCESS):
                    puts("Ecriture de la solution : OK");
                break; // return EXIT_SUCCESS;
            }
    }

    return EXIT_SUCCESS;
}
Пример #18
0
void
find_solution(GSList *words, GSList *letters, gchar *grid, gint depth)
{
  GSList *ll;
  gchar gridsnap[MAX_GRID*MAX_GRID];
  static gint count = 0;
  static gint maxdepth = 0;

  count++;
    
  if (depth >= maxdepth) {
    printf("depth %d (%d, %d)\n%s\n\n", maxdepth = depth, count, total, grid);
  }

  push_state(words, letters);
  strcpy(gridsnap, grid);
  
  if (run_constraints() == TRUE) {
    gint min = 257;
    struct lettervar *next_to_try = NULL;
    gboolean letters_to_try[256];
    gint i;
    
    // find the most constrained (but still not set) letter
    for (ll = letters; ll != NULL; ll = ll->next) {
      struct lettervar *l = ll->data;
      
      if (l->num_letters_allowed == 1) continue;

      if (l->num_letters_allowed < min) {
        min = l->num_letters_allowed;
        next_to_try = l;
      }
    }


    if (next_to_try == NULL) {
      total++;
      printf("depth %d (%d, %d)\n%s\n\n", depth, count, total, grid);
      pop_state(words, letters);
      strcpy(grid, gridsnap);
      return;
    }

    memcpy(letters_to_try, next_to_try->letters_allowed, sizeof (letters_to_try));
    memset(next_to_try->letters_allowed, 0, sizeof (letters_to_try));

    
    for (i = 0; i < 256; i++) {
      if (letters_to_try[i]) {
        next_to_try->letters_allowed[i] = TRUE;
        next_to_try->num_letters_allowed = 1;
        
        if (depth == 0) {
          *(next_to_try->pos) = i - 'a' + 'A';
        } else {
          *(next_to_try->pos) = i;
        }
        
        put_constraint_on_queue((struct constraint *) next_to_try->constraints[0]);
        put_constraint_on_queue((struct constraint *) next_to_try->constraints[1]);
        find_solution(words, letters, grid, depth + 1);

        next_to_try->letters_allowed[i] = FALSE;
      }
    }
  }

  pop_state(words, letters);
  strcpy(grid, gridsnap);
}
Пример #19
0
bool
RoutePlanner::solve(const AGeoPoint& origin,
                    const AGeoPoint& destination,
                    const RoutePlannerConfig& config,
                    const short h_ceiling)
{
  on_solve(origin, destination);
  rpolars_route.set_config(config, std::max(destination.altitude, origin.altitude),
                           h_ceiling);
  rpolars_reach.set_config(config, std::max(destination.altitude, origin.altitude),
                           h_ceiling);

  m_reach_polar_mode = config.reach_polar_mode;

  {
    const AFlatGeoPoint s_origin(task_projection.project(origin), origin.altitude);
    const AFlatGeoPoint s_destination(task_projection.project(destination), destination.altitude);

    if (!(s_origin == origin_last) || !(s_destination == destination_last))
      dirty = true;

    if (is_trivial())
      return false;

    dirty = false;
    origin_last = s_origin;
    destination_last = s_destination;

    h_min = std::min(s_origin.altitude, s_destination.altitude);
    h_max = rpolars_route.cruise_altitude;
  }

  solution_route.clear();
  solution_route.push_back(origin);
  solution_route.push_back(destination);

  if (!rpolars_route.terrain_enabled() && !rpolars_route.airspace_enabled())
    return false; // trivial

  m_search_hull.clear();
  m_search_hull.push_back(SearchPoint(origin_last, task_projection));

  RoutePoint start = origin_last;
  m_astar_goal = destination_last;

  RouteLink e_test(start, m_astar_goal, task_projection);
  if (e_test.is_short())
    return false;
  if (!rpolars_route.achievable(e_test))
    return false;

  count_dij=0;
  count_airspace=0;
  count_terrain=0;
  count_supressed=0;

  bool retval = false;
  m_planner.restart(start);

  unsigned best_d = UINT_MAX;

  if (verbose) {
    printf("# goal node (%d,%d,%d)\n",
           m_astar_goal.Longitude, m_astar_goal.Latitude, m_astar_goal.altitude);
    printf("# start node (%d,%d,%d)\n",
           start.Longitude, start.Latitude, start.altitude);
  }

  while (!m_planner.empty()) {
    const RoutePoint node = m_planner.pop();

    if (verbose>1) {
      printf("# processing node (%d,%d,%d)  %d,%d  q size %d\n",
             node.Longitude, node.Latitude, node.altitude,
             m_planner.get_node_value(node).g,
             m_planner.get_node_value(node).h,
             m_planner.queue_size());
    }

    h_min = std::min(h_min, node.altitude);
    h_max = std::max(h_max, node.altitude);

    bool is_final = (node == m_astar_goal);
    if (is_final) {
      if (!retval)
        best_d = UINT_MAX;
      retval = true;
    }

    if (is_final) // @todo: allow fallback if failed
    { // copy improving solutions
      Route this_solution;
      unsigned d = find_solution(node, this_solution);
      if (d< best_d) {
        best_d = d;
        solution_route = this_solution;
      }
    }

    if (retval)
      break; // want top solution only

    // shoot for final
    RouteLink e(node, m_astar_goal, task_projection);
    if (set_unique(e))
      add_edges(e);

    while (!m_links.empty()) {
      add_edges(m_links.front());
      m_links.pop();
    }

  }
  count_unique = m_unique.size();

  if (retval && verbose) {
    printf("# solved with %d intermediate points\n", (int)(solution_route.size()-2));
  }

  if (retval) {
    // correct solution for rounding
    assert(solution_route.size()>=2);
    for (unsigned i=0; i< solution_route.size(); ++i) {
      FlatGeoPoint p(task_projection.project(solution_route[i]));
      if (p== origin_last) {
        solution_route[i] = AGeoPoint(origin, solution_route[i].altitude);
      } else if (p== destination_last) {
        solution_route[i] = AGeoPoint(destination, solution_route[i].altitude);
      }
    }

  } else {
    solution_route.clear();
    solution_route.push_back(origin);
    solution_route.push_back(destination);
  }

  m_planner.clear();
  m_unique.clear();
//  m_search_hull.clear();
  return retval;
}