Ejemplo n.º 1
0
int main(int argc, const char *argv[]) {
  int **grid;
  int n;
  int i;
  int j;
  int element;

  n = 4;

  grid = (int**) malloc(sizeof(int*) * n);

  element = 1;
  for (i = 0; i < n; i++) {
    grid[i] = (int*) malloc(sizeof(int) * n);
    for (j = 0; j < n; j++) {
      grid[i][j] = element;
      element++;
    }
  }

  print_grid(grid, n);
  rotate_90 (grid, n);
  printf("\n\n");
  print_grid(grid, n);

  return 0;
}
int main()
{
  int **grid;
  int i, a, b;

  printf("First example:\n");

  a = 5;
  b = 20;

  grid = alloc_grid(a, b);
  print_grid(grid, a, b);
  
  for (i = 0; i < a; i++)
    free(grid[i]);
  free(grid);

  printf("Second example:\n");

  grid = alloc_grid(5, 5);
  print_grid(grid, 5, 5);
  printf("\n");
  grid[2][3] = 98;
  grid[4][4] = 402;
  print_grid(grid, 5, 5);
  return (0);
}
Ejemplo n.º 3
0
/* read an image and generate a result */
int main(int argc, char **argv) {
    int rows=0;
    int cols=0;
    int iterations=0;
    int i;
    int **grid = NULL;
    int **neighbors = NULL;

    if (argc<2 || !(grid=read_grid(stdin,&rows,&cols))
            || (iterations=atoi(argv[1]))<0) {
        fprintf(stderr,"life usage:  life iterations <inputfile\n");
        exit(1);
    }
#ifdef DEBUG
    printf("input:\n");
    print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    neighbors = make_grid(rows,cols);
    for (i=0; i<iterations; i++) {
        next(grid, neighbors, rows, cols);
#ifdef DEBUG
        printf("next\n");
        print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    }
    print_grid(stdout,grid,rows,cols);
    free_grid(grid,rows);
    free_grid(neighbors,rows);
}
Ejemplo n.º 4
0
// main entry point for the program; initializes parameters, reads input file name argument if provided,
// declares two 2-dimensional arrays used as buffers to simulate the evolution of the cellular automaton
// grid, loads initial generation from input file into grid, runs automaton for 30 generations, prints
// results of evolution silently to file "output.txt" using a grid of 48 rows by 64 columns, (not including
// the additional frame which is printed at the perimeter of the grid), and prints error messages and exits
// if any part of this process fails;
int main( int argc, char ** argv )
{
    char even_grid[ROWS][COLUMNS];  // for double-buffering the grid, used for even-numbered generations
    char odd_grid[ROWS][COLUMNS];   // other buffer, used for odd-numbered generations
    int g, r, c;                    // indices
    char * input_filename;                 // "input.txt" if user does not provide a different file
    char * output_filename = "output.txt"; // hardwired to always create or overwrite same output file
    FILE * output_file_pointer;            // used to print results to file as they are generated

    for ( r = 0; r < ROWS; r++ ) {         // initialize buffers so they are full of dead cells (spaces)
        for ( c = 0; c < COLUMNS; c++ ) {
            even_grid[r][c] = ' ';
            odd_grid[r][c] = ' ';
        }
    }

    // allow user to specify input file as command line argument to program
    if ( 1 < argc ) {   // if arguments are given, assume first is the name of input file
        input_filename = argv[1];
    } else {            // no input filename provided, so use default name, "input.txt"
        input_filename = "input.txt";
    }

    if ( !load_input( input_filename, even_grid ) ) {
        fprintf( stderr, "usage: %s [ input_file ]\n", argv[0] );
        fprintf( stderr, "       quitting...\n" );
        exit( EXIT_FAILURE );
    }

    if ( NULL == ( output_file_pointer = fopen( output_filename, "w" ) ) ) {
        fprintf( stderr, "error: in 'main()', call to 'fopen(%s, 'w')' failed\n", output_filename );
        perror( "     " );
        fprintf( stderr, "usage: %s [ input_file ]\n", argv[0] );
        fprintf( stderr, "       quitting...\n" );
        exit( EXIT_FAILURE );
    }

    // run the 'Game of Life' on the provided input;
    for ( g = 0; g < GENERATIONS; g++ ) {   // iterate automaton for hardwired number of times;
        if ( 0 == g % 2 ) {                 // modulo for double-buffering; even generations use even_grid;
            print_grid( even_grid, g, output_file_pointer );   // once it's loaded or computed, print it;
            generate_grid( even_grid, odd_grid );             // use even_grid to compute new odd_grid;
        } else {                            // odd generations use odd grid
            print_grid( odd_grid, g, output_file_pointer );    // once it's computed, print it;
            generate_grid( odd_grid, even_grid );             // use odd_grid to compute new even_grid;
        }
    }

    if ( EOF == fclose( output_file_pointer ) ) {
        fprintf( stderr, "error: in 'main()', call to 'fclose(%s)' failed\n", output_filename );
        perror( "     " );
        fprintf( stderr, "usage: %s [ input_file ]\n", argv[0] );
        fprintf( stderr, "       quitting...\n" );
        exit( EXIT_FAILURE );
    }

    exit( EXIT_SUCCESS );
}
int main()
{
  int **grid;

  grid = alloc_grid(5, 5);
  print_grid(grid, 5, 5);
  printf("\n");
  grid[2][3] = 98;
  grid[4][4] = 402;
  print_grid(grid, 5, 5);
  return (0);
}
Ejemplo n.º 6
0
gmx_bool print_forcefield(FILE *fp, real ener[], int natoms, rvec f[], rvec fshake[],
                          rvec x[], t_block *mols, real mass[], tensor pres)
{
    real msf1;

    if (ga)
    {
        msf1 = msf(natoms, f, fshake);
        if (debug)
        {
            fprintf(fp, "Pressure: %12g, RMSF: %12g, Energy-Epot: %12g, cost: %12g\n",
                    ener[F_PRES], sqrt(msf1), ener[F_EPOT]/ff.nmol-ff.epot,
                    cost(pres, msf1, ener[F_EPOT]/ff.nmol));
        }
        if (print_ga(fp, ga, msf1, pres, scale, (ener[F_EPOT]/ff.nmol), range, ff.tol))
        {
            return TRUE;
        }
        fflush(fp);
    }
    else
    {
        print_grid(fp, ener, natoms, f, fshake, x, mols, mass, pres);
    }
    return FALSE;
}
Ejemplo n.º 7
0
void	init(int policy, int prot)
{
	allegro_init();
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, XMAX, YMAX, 0, 0);
	clear_to_color(screen, BGC);
	install_keyboard();
	print_grid(policy, prot);
	
	if (prot == PIP) ptask_init(policy, GLOBAL, PRIO_INHERITANCE);
	else if (prot == PCP) ptask_init(policy, GLOBAL, PRIO_CEILING);
	else {
	  allegro_exit();
	  ptask_syserror("pcp.c", "Wrong protocol");
	}

	if (prot == PIP) { 
	  pmux_create_pi(&mxa);
	  pmux_create_pi(&muxA);
	  pmux_create_pi(&muxB);
	}
	else if (prot == PCP) {
	  pmux_create_pc(&mxa, prio[1]);
	  pmux_create_pc(&muxA, prio[1]);
	  pmux_create_pc(&muxB, prio[1]);
	}
}
Ejemplo n.º 8
0
int find_best_move(grid_t grid)
{
    int direction, best_direction = -1;
    float best_score = 0.0f, score;
    
    print_grid(grid);
    std::printf("Current scores   | real: %.0f, heuristic: %.3lf", score_real(grid), score_heuristic(grid));
    std::cout << std::endl;
    
    for (direction = 0; direction < 4; direction++) {
        score = score_move(grid, direction);
        
        if (score > best_score) {
            best_score = score;
            best_direction = direction;
        } else if (score == best_score && best_score > 0.0f) {
            // coin flip to break a tie
            if (std::floor(rand() % 2) == 2) {
                best_direction = direction;
            }
        }
    }
    
    if (best_direction != -1) {
        std::printf("Move %s", GRID_MOVES[best_direction]);
        std::cout << std::endl;
    } else {
        std::cout << "No move found" << std::endl;
    }
    
    return best_direction;
}
Ejemplo n.º 9
0
int		main(int argc, char **argv)
{
	char **grid;

	if (error_check(argc, argv))
	{
		print_error();
		return (0);
	}
	grid = set_grid_parameters(argv);
	if (grid == NULL)
		print_error();
	sudoku(grid);
	if (grid[9] == ERROR)
		print_error();
	else
	{
		grid[9] = UNIQUE;
		if (sudoku(grid) && check_solution(grid))
			print_grid(grid);
		else
			print_error();
	}
	free(grid);
	return (0);
}
Ejemplo n.º 10
0
dir play_move(strategy s, grid g)
{
    // If precedent move was right, we put all left again
    /*if(((memory)(s->mem))->nbStages > 0 && (((((memory)(s->mem))->container)[((memory)(s->mem))->nbStages])->decision) == RIGHT && can_move(g, LEFT))
      {
        printf("test\n");
        save_stage(s->mem, g, LEFT);
        print_grid(g);
        return LEFT;
        }*/

    if(((memory)(s->mem))->nbStages >=0)
    {
        //int temp = ((memory)(s->mem))->nbStages;
        //printf("Test : [%d]%p\n", temp, (((memory)(s->mem))->container[5]));
        printf("Base memory adress : %p.\n", (memory)(s->mem));
        printf("Base container adress : %p.\n", ((memory)(s->mem))->container);
        printf("Element at [%d] : %p.\n", ((memory)(s->mem))->nbStages, (((memory)(s->mem))->container)[(int)(((memory)(s->mem))->nbStages)]);
    }
    //printf("Test 2 : %d\n", ((memory)(s->mem))->nbStages);

    if(can_move(g, DOWN))
    {
        save_stage(s->mem, g, DOWN);
        print_grid(g);
        return DOWN;
    }
    if(can_move(g, LEFT))
    {
        save_stage(s->mem, g, LEFT);
        print_grid(g);
        return LEFT;
    }
    if(can_move(g, RIGHT))
    {
        save_stage(s->mem, g, RIGHT);
        print_grid(g);
        return RIGHT;
    }
    if(can_move(g, UP))
    {
        save_stage(s->mem, g, UP);
        print_grid(g);
        return UP;
    }
}
Ejemplo n.º 11
0
void handle_input() {
	char command;
	int x, y;
	char input_buffer[20];
	/* Lees het commando van de gebruiker in */
	fgets(input_buffer, 20, stdin);
	sscanf(input_buffer, "%c %i %i", &command, &x, &y);

  switch (command) {
	case 'F': // Flag
   if (((x < 0) || (x > WIDTH) || (y < 0) || (y > HEIGHT))){ // Chack voor geldige input.
    printf("Invalid input.\n");
    }
    else {
		flag_coordinate(x, y);
    }
		break;
	case 'R': // Reveal
   if (((x < 0) || (x > WIDTH) || (y < 0) || (y > HEIGHT))){ // Chack voor geldige input.
    printf("Invalid input.\n");
    }
    else {
		reveal_coordinate(x, y);
    }
		break;
	case 'P': // Print
		print_grid();
    draw_grid(); // DEBUG
		break;
  case 'E': // Exit
    update_stats();
    deallocate_grid(WIDTH, HEIGHT);
    exit(0); // Programma wordt afgesloten met code 0 = succes.
    break;
  case 'B': // Boem! Alle mijnen ontploffen
    printf("BOEM! \n");
    dead = 1;
    print_grid();
    break;
	default:
		/* De speler gaf een commando in dat niet begrepen werd door deze functie: probeer opnieuw. */
		printf("Command '%c' not understood, please try again.\n", command);
		handle_input();
	}
}
Ejemplo n.º 12
0
int main(){

    grid board = hard_sudoku();

    print_grid(board);

    solve(board, 0, 0);

    return 0;
}
Ejemplo n.º 13
0
/*  read an image and generate a result */ 
int main(int argc, char **argv) { 
   FILE *f; 
   int rows=0; int cols=0; int iterations=0; 
   int i; 
   if (argc>1 || !(grid=read_rle(stdin,&rows,&cols))) { 
	fprintf(stderr,"translate usage: translate <inputfile\n"); 
	exit(1); 
   } 
   print_grid(stdout,grid,rows,cols); 
   free_grid(grid,rows); 
} 
int main(int argc, char **argv) {
    TreeNode *root = new TreeNode(3);
    root->left = new TreeNode(9);
    root->left->left = new TreeNode(15);
    root->right = new TreeNode(20);
    root->right->right = new TreeNode(7);

    Solution s;
    print_grid(s.levelOrder(root));
    return 0;
}
Ejemplo n.º 15
0
void		preparation(t_map **map)
{
	char	**grid;

	grid = NULL;
	g_size = size_min_square(*map);
	init_grid(&grid);
	while (backtrack(grid, *map) != 0)
		create_grid(&grid);
	print_grid(grid);
	delete_tab(&grid);
}
Ejemplo n.º 16
0
/*
 * Initialize cells based on input file, otherwise all cells
 * are DEAD.
 */
void init_grids (struct life_t * life) 
{
	FILE * fd;
	int i,j;

	if (life->infile != NULL) {
		if ((fd = fopen(life->infile, "r")) == NULL) {
			perror("Failed to open file for input");
			exit(EXIT_FAILURE);
		}

		if (fscanf(fd, "%d %d\n", &life->nrows, &life->tcols) == EOF) {
			printf("File must at least define grid dimensions!\nExiting.\n");
			exit(EXIT_FAILURE);
		}
	}

	// resize so each process is in charge of a vertical slice of the whole board
	life->ubound = (((life->rank + 1) * life->tcols / life->size) - 1); // we want 1 col of (overlap?)
	life->lbound = life->rank * life->tcols / life->size;
	life->ncols = (life->ubound - life->lbound) + 1;

	printf("[Process %d] lower bound is %d upper bound is %d width is %d random seed is %d.\n", life->rank, life->lbound, life->ubound, life->ncols, life->randseed);

	allocate_grids(life);

	for (i = 0; i < life->nrows+2; i++) {
		for (j = 0; j < life->ncols+2; j++) {
			life->grid[i][j]      = DEAD;
			life->next_grid[i][j] = DEAD;
		}
	}

	if (life->infile != NULL) {
		while (fscanf(fd, "%d %d\n", &i, &j) != EOF) {
			if (j <= life->ubound && j >= life->lbound){
				fprintf(stderr, "[Process %d] %d %d -> %d %d.\n", life->rank, i, j, i, j - life->lbound);
				life->grid[i+1][j - life->lbound + 1]      = ALIVE;
				life->next_grid[i+1][j- life->lbound + 1] = ALIVE;
			}
		}
		
		fclose(fd);
	} else {
		randomize_grid(life, INIT_PROB);
	}

	if (life->print){
		printf("[Host %d] printing initial slice.\n", life->rank);
		print_grid (life);
	}
}
Ejemplo n.º 17
0
int
main(int argc, char **argv)
{
    char *err;
    struct game g = { 0 };
    long w, h, p;

    if (argc != 4 && argc != 5) {
        fprintf(stderr, "Usage: boxes height width playercount [filename]\n");
        exit(1);
    }

    h = strtol(argv[1], &err, 10);
    if (*err != '\0' || h < 2 || h > 999) {
        fprintf(stderr, "Invalid grid dimensions\n");
        exit(2);
    }

    w = strtol(argv[2], &err, 10);
    if (*err != '\0' || w < 2 || w > 999) {
        fprintf(stderr, "Invalid grid dimensions\n");
        exit(2);
    }

    p = strtol(argv[3], &err, 10);
    if (*err != '\0' || p < 2 || p > 100) {
        fprintf(stderr, "Invalid player count\n");
        exit(3);
    }

    g.width = w;
    g.height = h;
    g.num_players = p;
    g.possible_closures = w * h;

    allocate_empty_grid(&g);

    if (argc == 5) {
        read_grid_file(argv[4], &g);
    }

    while (1) {
        print_grid(stdout, &g);
        if (g.close_count == g.possible_closures) {
            pick_winner(&g);
        }
        while (try_move(&g));
        g.current_player = (g.current_player + 1) % g.num_players;
    }

    return 0;
}
Ejemplo n.º 18
0
main()
{
    int t;

    scanf("%d",&t);
    while (t--)
    {
        read_grid();
        init();
        solve();
        print_grid();
    }
    return 0;
}
Ejemplo n.º 19
0
/* remove random values from printed grid 
 * for solving by us apes
 */
static void remove_values(int* matrix)
{
	puts("remove values...");

	/* number of removed numbers */
	int nr = DIFFICULTY;
	int r;

    // for each latin square, distribute evenly the number of cells
    // to hide
	for (int j=0; j<9; j++)
	{
        int result[9];
        return_square(j, result);
	}


	// for 0 to 81, assign blanks to cells to present puzzle
	for (int j=0; j<81; j++)
	{		
		puzzle_matrix[j] = puzzle_solution[j];

		if (nr>0)
		{
			/* TODO: This has to change, the distribution
			 * of removed values has to be spread across all
			 * latin squares, as it stands now, it will tend
			 * to only remove values from the beginning sequence
			 * of values. ie. the first few rows and first 3
			 * latin squares. Amateur.
			 */
#ifdef JSW_RANDOM
			r = jsw_rand() % 2;
#else
			r = rand() % 2;
#endif
			/* printf("%d\n", r); */
			if (r)
			{
				puzzle_matrix[j] = 0;
				--nr;
			}
		}
		
	}

	print_grid(puzzle_matrix);
}
Ejemplo n.º 20
0
void reveal_coordinate(int x, int y) {
/* Als een cel een mijn bevat, dan is de speler dood*/
if (get_cell(x, y)->is_mine == 1 )
{
    printf("/+/+/+/ MINE EXPLODED /+/+/+/ \n");
    printf("\n");
    dead = 1;
    print_grid();
    printf("Spel wordt afgesloten...\n");


    draw_grid();
    update_stats();
    show_stats();
    sleep(2);
    deallocate_grid(WIDTH, HEIGHT);
    exit(0);
}

/* Als de cel geen mijn is, verander dan zijn staat van covered naar uncovered. */
else {
    // Zet de status van het vakje op UNCOVERED.
    get_cell(x, y)->state = UNCOVERED;

  // Test of het vakje geen naburige mijnen heeft.
  if (get_cell(x, y)->neighbouring_mines == 0)
  {

    // Als het 0 naburige vakjes heeft, moeten al zijn buren bekeken worden of zij een mijn in de buurt hebben.

    for (int i = -1; i < 2; i++) // Begin bij de cel aan de linkse kant (vandaar de -1).
      {
        for (int j = -1; j < 2; j++) // Begin bij de cel aan de rechtse kant.
        {
          if ((x + i) < WIDTH && (x + i)  >= 0 && (y + j) < HEIGHT && (y + j) >= 0) // Controle of een buurcel van de mijn zich niet buiten de randen van het veld bevindt.
          {
            if (get_cell(x + i, y + j)->state == COVERED)
            {
          reveal_coordinate(x + i, y + j); // Recursieve oproep op de naburige cellen.
            }
          }
        }
      }
    }
  }
}
Ejemplo n.º 21
0
int main(void) {

    int ret = 0, nc;
    int c;
    int key = 0;
    int part = PARTITIONED; // PARTITIONED, GLOBAL
    int sched = SCHED_FIFO;

    get_data();
    init();
    ret = select_prot();
    if (ret == -1) {
        allegro_exit();
        return 0;
    }

    print_grid(ret);
    ptask_init(sched, part, ret);
    t_start = ptask_gettime(MILLI);
    set_sem_sezC(ret);

    nc = ptask_getnumcores();
    textprintf_ex(screen, font, 480, 10, 7, BGC, "(NumCores = %d)", nc);

    int gen_id = ptask_create_prio(gen, 100, 30, NOW);
    if (gen_id < 0) {
        printf("Could not create task gen\n");
        exit(-1);
    }

    while (key != KEY_ESC) {

        if (keypressed()) {
            c = readkey();
            key = c >> 8;
        }
    }

    pmux_destroy(&mx_sezNorm);
    pmux_destroy(&mx_sezA);
    pmux_destroy(&mx_sezB);

    allegro_exit();
    return 0;
}
Ejemplo n.º 22
0
/* randomly swap out values, by num_itr,
 * number of iterations, of known solved puzzle;
 * should result in a new (completed) random puzzle
 */
static int build_puzzle(int* puzzle, int* matrix)
{
    int num_itr = 0, x = 0, y = 0;
    puts("generating sudoku puzzle ...");

	/* There is a stdlib call "rand"; this function is tuned primarily for speed
	 * and distribution, not for unpredictability. Almost all built-in random 
	 * functions for various languages and frameworks use this function by 
	 * default. There are also "cryptographic" random number generators that are
	 * much less predictable, but run much slower. These should be used in any sort
	 * of security-related application. - tylerl
	 * http://stackoverflow.com/questions/822323/how-to-generate-a-random-number-in-c
	 */

#ifdef JSW_RANDOM
    puts("using jsw_srand()");
    jsw_seed(time(NULL));
    num_itr = (jsw_rand() % 1000000);
#else
    puts("using srand()");
    srand(time(NULL));
    num_itr = (rand() % 1000000);
#endif
    
    printf("number iterations: %d\n", num_itr);

    for (int i = 0; i<num_itr; i++) 
    {
#ifdef JSW_RANDOM
        x = (jsw_rand() % 9);
        y = (jsw_rand() % 9);
#else
        x = (rand() % 9);
        y = (rand() % 9);
#endif
        x++;
        y++;
        /* printf("x = %d, y = %d\n", x, y); */
        swap_numbers(puzzle, x, y);
    }

    print_grid(puzzle_solution);
    remove_values(matrix);
    return 0;
}
Ejemplo n.º 23
0
/*
 * Deze functie wordt aangeroepen als de gebruiker een vlag wil plaatsten op het vakje met positie (x,y)
 * in het veld.
 */
void flag_coordinate(int x, int y){


// UNFLAG //
if (get_cell(x, y)->state == FLAGGED) { // Is vakje gevlagd?
  get_cell(x, y)->state = COVERED; // Zet status van vakje terug op covered.
  nr_of_flags++; // Verhoog aantal vlaggen.

  if (get_cell (x, y)->is_mine == 1){ // Als het onderliggend vakje een mijn was, dan wordt nr_of_flagged_mines verminderd.
  nr_of_flagged_mines--;
    }
  }

  // FLAG //
  else if (nr_of_flags != 0){ // Als de vlaggen niet op zijn, kan de cel van status veranderen.
  get_cell(x, y)->state = FLAGGED;  // Verader de status van de cel naar FLAGGED (= 2)
  nr_of_flags--; // Verminder het aantal vlaggen dat de speler ter beschikking nog heeft

  if (get_cell(x, y)->is_mine == 1){
    nr_of_flagged_mines++; // Verminder het aantal flagged mines.
    }

    if (nr_of_flagged_mines == NR_OF_MINES){
      printf("/+/+/+/ YOU WON! /+/+/+/\n");
      printf("\n");
      print_grid();
      draw_grid();
      printf("Spel wordt afgesloten...\n");

      update_stats();
      show_stats();
      sleep(2);
      deallocate_grid(WIDTH, HEIGHT);
      exit(0); // Programma wordt afgesloten met code 0 = succes.
    }

  }

  // Het aantal vlaggen is op
  else
  {
    printf("NO MORE FLAGS\n"); // Komt op het scherm al er geen vlggen meer zijn.
  }
}
Ejemplo n.º 24
0
int main()
{
	initscr();
	noecho();	

	// position 
	int* ptr_x;
	int* ptr_y;
	ptr_x = malloc(sizeof(int));
	ptr_y = malloc(sizeof(int));

	*ptr_x = *ptr_y = 0;

	int  moved = 1;


///	for (int i = 0; i < 10; i++ )
	while(moved != 'q')
	{
		//moved = movement(ptr_x, ptr_y);
		
		clear();
	//	printf("\e[2J\e[1;1H");
		printw("Location is: (%d,%d)\n", *ptr_x, *ptr_y);

		print_grid(ptr_x, ptr_y);

		refresh();
		moved = movement(ptr_x,ptr_y);
		
	}

	// grid array
	//int grid[GRIDMAX][GRIDMAX];

	free(ptr_x);
	free(ptr_y);

	endwin();

	return 0;
}
Ejemplo n.º 25
0
/* For printing the Queens and Placing them in Grid */
void nqueens(int n)
{
    int x[20];
    int count=0;
    int k=1;
 
    x[k]=0;
 
    while(k!=0)
    {
 
        x[k]=x[k]+1;
        while((x[k]<=n)&&(!safetoplace(x,k)))
        {
 
            x[k]=x[k]+1;
        }
        if(x[k]<=n)
        {
            if(k==n)
            {
                count++;
                printf("\n\tPlacement %d  is : \n\n\n",count);
                print_grid(n,x);
                getch();
 
            }
            else
            {
                k++;
                x[k]=0;
                 }
        }
        else
        {
            k--;
        }
    }
    return;
}
Ejemplo n.º 26
0
int solve(grid board, int i, int j){

    if(i==9){
        printf("\n");
        printf("Solved!\n\n");
        print_grid(board);
        return 1;
    }

    if(board.array[i][j]){
        if (j == 8) {
            if(solve(board, i+1, 0)){
                return 1;
            }
        }else{
            if(solve(board, i, j+1)){
                return 1;
            }
        }
    }

    for (int possible = 1; possible < 10; possible++) {
        if (validate(board, possible, i, j)) {
            board.array[i][j] = possible;
            if (j == 8) {
                if(solve(board, i+1, 0)){
                    return 1;
                }
            }else{
                if(solve(board, i, j+1)){
                    return 1;
                }
            }
        }
    }
    board.array[i][j] = 0;
    return 0;
}
Ejemplo n.º 27
0
gmx_bool pme_load_balance(pme_load_balancing_t       pme_lb,
                          t_commrec                 *cr,
                          FILE                      *fp_err,
                          FILE                      *fp_log,
                          t_inputrec                *ir,
                          t_state                   *state,
                          double                     cycles,
                          interaction_const_t       *ic,
                          struct nonbonded_verlet_t *nbv,
                          struct gmx_pme_t **        pmedata,
                          gmx_int64_t                step)
{
    gmx_bool     OK;
    pme_setup_t *set;
    double       cycles_fast;
    char         buf[STRLEN], sbuf[22];
    real         rtab;
    gmx_bool     bUsesSimpleTables = TRUE;

    if (pme_lb->stage == pme_lb->nstage)
    {
        return FALSE;
    }

    if (PAR(cr))
    {
        gmx_sumd(1, &cycles, cr);
        cycles /= cr->nnodes;
    }

    set = &pme_lb->setup[pme_lb->cur];
    set->count++;

    rtab = ir->rlistlong + ir->tabext;

    if (set->count % 2 == 1)
    {
        /* Skip the first cycle, because the first step after a switch
         * is much slower due to allocation and/or caching effects.
         */
        return TRUE;
    }

    sprintf(buf, "step %4s: ", gmx_step_str(step, sbuf));
    print_grid(fp_err, fp_log, buf, "timed with", set, cycles);

    if (set->count <= 2)
    {
        set->cycles = cycles;
    }
    else
    {
        if (cycles*PME_LB_ACCEL_TOL < set->cycles &&
            pme_lb->stage == pme_lb->nstage - 1)
        {
            /* The performance went up a lot (due to e.g. DD load balancing).
             * Add a stage, keep the minima, but rescan all setups.
             */
            pme_lb->nstage++;

            if (debug)
            {
                fprintf(debug, "The performance for grid %d %d %d went from %.3f to %.1f M-cycles, this is more than %f\n"
                        "Increased the number stages to %d"
                        " and ignoring the previous performance\n",
                        set->grid[XX], set->grid[YY], set->grid[ZZ],
                        cycles*1e-6, set->cycles*1e-6, PME_LB_ACCEL_TOL,
                        pme_lb->nstage);
            }
        }
        set->cycles = min(set->cycles, cycles);
    }

    if (set->cycles < pme_lb->setup[pme_lb->fastest].cycles)
    {
        pme_lb->fastest = pme_lb->cur;

        if (DOMAINDECOMP(cr))
        {
            /* We found a new fastest setting, ensure that with subsequent
             * shorter cut-off's the dynamic load balancing does not make
             * the use of the current cut-off impossible. This solution is
             * a trade-off, as the PME load balancing and DD domain size
             * load balancing can interact in complex ways.
             * With the Verlet kernels, DD load imbalance will usually be
             * mainly due to bonded interaction imbalance, which will often
             * quickly push the domain boundaries beyond the limit for the
             * optimal, PME load balanced, cut-off. But it could be that
             * better overal performance can be obtained with a slightly
             * shorter cut-off and better DD load balancing.
             */
            change_dd_dlb_cutoff_limit(cr);
        }
    }
    cycles_fast = pme_lb->setup[pme_lb->fastest].cycles;

    /* Check in stage 0 if we should stop scanning grids.
     * Stop when the time is more than SLOW_FAC longer than the fastest.
     */
    if (pme_lb->stage == 0 && pme_lb->cur > 0 &&
        cycles > pme_lb->setup[pme_lb->fastest].cycles*PME_LB_SLOW_FAC)
    {
        pme_lb->n = pme_lb->cur + 1;
        /* Done with scanning, go to stage 1 */
        switch_to_stage1(pme_lb);
    }

    if (pme_lb->stage == 0)
    {
        int gridsize_start;

        gridsize_start = set->grid[XX]*set->grid[YY]*set->grid[ZZ];

        do
        {
            if (pme_lb->cur+1 < pme_lb->n)
            {
                /* We had already generated the next setup */
                OK = TRUE;
            }
            else
            {
                /* Find the next setup */
                OK = pme_loadbal_increase_cutoff(pme_lb, ir->pme_order, cr->dd);

                if (!OK)
                {
                    pme_lb->elimited = epmelblimPMEGRID;
                }
            }

            if (OK && ir->ePBC != epbcNONE)
            {
                OK = (sqr(pme_lb->setup[pme_lb->cur+1].rlistlong)
                      <= max_cutoff2(ir->ePBC, state->box));
                if (!OK)
                {
                    pme_lb->elimited = epmelblimBOX;
                }
            }

            if (OK)
            {
                pme_lb->cur++;

                if (DOMAINDECOMP(cr))
                {
                    OK = change_dd_cutoff(cr, state, ir,
                                          pme_lb->setup[pme_lb->cur].rlistlong);
                    if (!OK)
                    {
                        /* Failed: do not use this setup */
                        pme_lb->cur--;
                        pme_lb->elimited = epmelblimDD;
                    }
                }
            }
            if (!OK)
            {
                /* We hit the upper limit for the cut-off,
                 * the setup should not go further than cur.
                 */
                pme_lb->n = pme_lb->cur + 1;
                print_loadbal_limited(fp_err, fp_log, step, pme_lb);
                /* Switch to the next stage */
                switch_to_stage1(pme_lb);
            }
        }
        while (OK &&
               !(pme_lb->setup[pme_lb->cur].grid[XX]*
                 pme_lb->setup[pme_lb->cur].grid[YY]*
                 pme_lb->setup[pme_lb->cur].grid[ZZ] <
                 gridsize_start*PME_LB_GRID_SCALE_FAC
                 &&
                 pme_lb->setup[pme_lb->cur].grid_efficiency <
                 pme_lb->setup[pme_lb->cur-1].grid_efficiency*PME_LB_GRID_EFFICIENCY_REL_FAC));
    }

    if (pme_lb->stage > 0 && pme_lb->end == 1)
    {
        pme_lb->cur   = 0;
        pme_lb->stage = pme_lb->nstage;
    }
    else if (pme_lb->stage > 0 && pme_lb->end > 1)
    {
        /* If stage = nstage-1:
         *   scan over all setups, rerunning only those setups
         *   which are not much slower than the fastest
         * else:
         *   use the next setup
         */
        do
        {
            pme_lb->cur++;
            if (pme_lb->cur == pme_lb->end)
            {
                pme_lb->stage++;
                pme_lb->cur = pme_lb->start;
            }
        }
        while (pme_lb->stage == pme_lb->nstage - 1 &&
               pme_lb->setup[pme_lb->cur].count > 0 &&
               pme_lb->setup[pme_lb->cur].cycles > cycles_fast*PME_LB_SLOW_FAC);

        if (pme_lb->stage == pme_lb->nstage)
        {
            /* We are done optimizing, use the fastest setup we found */
            pme_lb->cur = pme_lb->fastest;
        }
    }

    if (DOMAINDECOMP(cr) && pme_lb->stage > 0)
    {
        OK = change_dd_cutoff(cr, state, ir, pme_lb->setup[pme_lb->cur].rlistlong);
        if (!OK)
        {
            /* Failsafe solution */
            if (pme_lb->cur > 1 && pme_lb->stage == pme_lb->nstage)
            {
                pme_lb->stage--;
            }
            pme_lb->fastest  = 0;
            pme_lb->start    = 0;
            pme_lb->end      = pme_lb->cur;
            pme_lb->cur      = pme_lb->start;
            pme_lb->elimited = epmelblimDD;
            print_loadbal_limited(fp_err, fp_log, step, pme_lb);
        }
    }

    /* Change the Coulomb cut-off and the PME grid */

    set = &pme_lb->setup[pme_lb->cur];

    ic->rcoulomb     = set->rcut_coulomb;
    ic->rlist        = set->rlist;
    ic->rlistlong    = set->rlistlong;
    ir->nstcalclr    = set->nstcalclr;
    ic->ewaldcoeff_q = set->ewaldcoeff_q;
    /* TODO: centralize the code that sets the potentials shifts */
    if (ic->coulomb_modifier == eintmodPOTSHIFT)
    {
        ic->sh_ewald = gmx_erfc(ic->ewaldcoeff_q*ic->rcoulomb);
    }
    if (EVDW_PME(ic->vdwtype))
    {
        /* We have PME for both Coulomb and VdW, set rvdw equal to rcoulomb */
        ic->rvdw            = set->rcut_coulomb;
        ic->ewaldcoeff_lj   = set->ewaldcoeff_lj;
        if (ic->vdw_modifier == eintmodPOTSHIFT)
        {
            real crc2;

            ic->dispersion_shift.cpot = -pow(ic->rvdw, -6.0);
            ic->repulsion_shift.cpot  = -pow(ic->rvdw, -12.0);
            ic->sh_invrc6             = -ic->dispersion_shift.cpot;
            crc2                      = sqr(ic->ewaldcoeff_lj*ic->rvdw);
            ic->sh_lj_ewald           = (exp(-crc2)*(1 + crc2 + 0.5*crc2*crc2) - 1)*pow(ic->rvdw, -6.0);
        }
    }

    bUsesSimpleTables = uses_simple_tables(ir->cutoff_scheme, nbv, 0);
    nbnxn_gpu_pme_loadbal_update_param(nbv, ic);

    /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
     * also sharing texture references. To keep the code simple, we don't
     * treat texture references as shared resources, but this means that
     * the coulomb_tab texture ref will get updated by multiple threads.
     * Hence, to ensure that the non-bonded kernels don't start before all
     * texture binding operations are finished, we need to wait for all ranks
     * to arrive here before continuing.
     *
     * Note that we could omit this barrier if GPUs are not shared (or
     * texture objects are used), but as this is initialization code, there
     * is not point in complicating things.
     */
#ifdef GMX_THREAD_MPI
    if (PAR(cr) && use_GPU(nbv))
    {
        gmx_barrier(cr);
    }
#endif  /* GMX_THREAD_MPI */

    /* Usually we won't need the simple tables with GPUs.
     * But we do with hybrid acceleration and with free energy.
     * To avoid bugs, we always re-initialize the simple tables here.
     */
    init_interaction_const_tables(NULL, ic, bUsesSimpleTables, rtab);

    if (cr->duty & DUTY_PME)
    {
        if (pme_lb->setup[pme_lb->cur].pmedata == NULL)
        {
            /* Generate a new PME data structure,
             * copying part of the old pointers.
             */
            gmx_pme_reinit(&set->pmedata,
                           cr, pme_lb->setup[0].pmedata, ir,
                           set->grid);
        }
        *pmedata = set->pmedata;
    }
    else
    {
        /* Tell our PME-only node to switch grid */
        gmx_pme_send_switchgrid(cr, set->grid, set->ewaldcoeff_q, set->ewaldcoeff_lj);
    }

    if (debug)
    {
        print_grid(NULL, debug, "", "switched to", set, -1);
    }

    if (pme_lb->stage == pme_lb->nstage)
    {
        print_grid(fp_err, fp_log, "", "optimal", set, -1);
    }

    return TRUE;
}
Ejemplo n.º 28
0
/* Print the user statement of the host code to "p".
 *
 * The host code may contain original user statements, kernel launches,
 * statements that copy data to/from the device and statements
 * the initialize or clear the device.
 * The original user statements and the kernel launches have
 * an associated annotation, while the other statements do not.
 * The latter are handled by print_device_node.
 * The annotation on the user statements is called "user".
 *
 * In case of a kernel launch, print a block of statements that
 * defines the grid and the block and then launches the kernel.
 */
static __isl_give isl_printer *print_host_user(__isl_take isl_printer *p,
	__isl_take isl_ast_print_options *print_options,
	__isl_keep isl_ast_node *node, void *user)
{
	isl_id *id;
	int is_user;
	struct ppcg_kernel *kernel;
	struct ppcg_kernel_stmt *stmt;
	struct print_host_user_data *data;

	isl_ast_print_options_free(print_options);

	data = (struct print_host_user_data *) user;

	id = isl_ast_node_get_annotation(node);
	if (!id)
	{
		//p = isl_printer_print_str(p,"marker_NO_ID_CASE");
		return print_device_node(p, node, data->prog);
	}	
	is_user = !strcmp(isl_id_get_name(id), "user");
	kernel = is_user ? NULL : isl_id_get_user(id);
	stmt = is_user ? isl_id_get_user(id) : NULL;
	isl_id_free(id);

	if (is_user)
		return ppcg_kernel_print_domain(p, stmt);

	p = ppcg_start_block(p);

	p = isl_printer_start_line(p);
	p = isl_printer_print_str(p, "dim3 k");
	p = isl_printer_print_int(p, kernel->id);
	p = isl_printer_print_str(p, "_dimBlock");
	print_reverse_list(isl_printer_get_file(p),
				kernel->n_block, kernel->block_dim);
	p = isl_printer_print_str(p, ";");
	p = isl_printer_end_line(p);

	p = print_grid(p, kernel);

	p = isl_printer_start_line(p);
	p = isl_printer_print_str(p, "kernel");
	p = isl_printer_print_int(p, kernel->id);
	p = isl_printer_print_str(p, " <<<k");
	p = isl_printer_print_int(p, kernel->id);
	p = isl_printer_print_str(p, "_dimGrid, k");
	p = isl_printer_print_int(p, kernel->id);
	p = isl_printer_print_str(p, "_dimBlock>>> (");
	p = print_kernel_arguments(p, data->prog, kernel, 0);
	p = isl_printer_print_str(p, ");");
	p = isl_printer_end_line(p);

	p = isl_printer_start_line(p);
	p = isl_printer_print_str(p, "cudaCheckKernel();");
	p = isl_printer_end_line(p);

	p = ppcg_end_block(p);

	p = isl_printer_start_line(p);
	p = isl_printer_end_line(p);

	p = copy_data_from_device_to_device(p,kernel); 

	printf("printing kernel");

	print_kernel(data->prog, kernel, data->cuda);

	printf("printing kernel done");

	return p;
}
Ejemplo n.º 29
0
void show_grid() {
    print_grid(gridP);
}
Ejemplo n.º 30
0
static void print_prompt(FILE *fp, const game_t *game)
{
	print_grid(fp, game);
	xprintf(fp, "Player %c> ", game->current_player);
}