Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Alexandru Scvortov

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Strange square

For n = 8, builds
1 1 1 1 1 1 1 0
1 1 1 1 1 1 0 0
1 1 1 1 1 0 1 0
1 1 1 1 0 0 0 0
1 1 1 0 1 1 1 0
1 1 0 0 1 1 0 0
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0

The algorithm, for a n x n matrix is:
1. Split the matrix into 4 matrices of the same size
2. Complete the top-left one with 1
3. Repeat for each of the other 3 matrices.

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  
   5  int n;
   6  int **T;
   7  
   8  void printM() {
   9  	int i,
  10  		j;
  11  	printf("\n");
  12  	for (i = 0; i < n; ++i) {
  13  		for (j = 0; j < n; ++j)
  14  			printf("%d ", T[i][j]);
  15  		printf("\n");
  16  	}
  17  }
  18  
  19  void fill(int x1, int y1, int x2, int y2) {
  20  	printf("%d %d %d %d\n", x1, y1, x2, y2);
  21  	//getchar();
  22  	
  23  	if (x1 == x2) {
  24  		//T[x1][y1] = 1;
  25  		return;
  26  	}
  27  	
  28  	int i,
  29  		j;
  30  	int xm = (x1 + x2) / 2;
  31  	int ym = (y1 + y2) / 2;
  32  	for (i = y1; i <= ym; ++i)
  33  		for (j = x1; j <= xm; ++j)
  34  			T[i][j] = 1;
  35  	
  36  	fill(x1, ym + 1, xm, y2);
  37  	fill(xm + 1, y1, x2, ym);
  38  	fill(xm + 1, ym + 1, x2, y2);
  39  }
  40  
  41  int main(int argc, char *argv[]) {
  42  	n = 8;
  43  	T = (int**)malloc(n * sizeof(int*));
  44  	int i;
  45  	for (i = 0; i < n; ++i)
  46  		T[i] = (int*)malloc(n * sizeof(int));
  47  	
  48  	int j;
  49  	for (i = 0; i < n; ++i)
  50  		for (j = 0; j < n; ++j)
  51  			T[i][j] = 0;
  52  	
  53  	fill(0, 0, n - 1, n - 1);
  54  	printM();
  55  	
  56  	return 0;
  57  }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS