格雷码生成(分治法)

 1 #include<stdio.h>
 2 #include<math.h>
 3 #include<stdlib.h>
 4 #define SIZE_OF_NUM 1025  //格雷码总数 
 5 #define SIZE_OF_BIT 11   //格雷码的二进制位数 
 6 void get_Gray_code(int a[SIZE_OF_NUM][SIZE_OF_BIT],int mid,int n,int b,int reverse_or_not);
 7 int main()
 8 {
 9     FILE *fp=NULL;
10     fp=fopen("input.txt","r");
11     if(fp==NULL)
12     {
13         printf("Failed to open file!\n");
14         exit(0);
15     }
16     int GrayCode[SIZE_OF_NUM][SIZE_OF_BIT];
17     int b,n;
18     printf("input b: ");
19 //    scanf("%d",&b);
20     fscanf(fp,"%d",&b);
21     fprintf(stdout,"%d\n",b);
22     fclose(fp);
23     fp=fopen("output.txt","w");
24     if(fp==NULL)
25     {
26         printf("Failed to open file!\n");
27         exit(0);
28     }
29     n=pow(2,b);
30     get_Gray_code(GrayCode,n/2,n,1,0);
31     for(int i=1;i<=n;i++)
32     {
33         for(int j=1;j<=b;j++)
34         {
35 //            printf("%d\t",GrayCode[i][j]);
36             fprintf(fp,"%d\t",GrayCode[i][j]);
37             fprintf(stdout,"%d\t",GrayCode[i][j]);
38         }
39 //        printf("\n");
40         fprintf(fp,"\n");
41         fprintf(stdout,"\n");
42     }
43     fclose(fp);
44     return 0;
45 }
46 
47 void get_Gray_code(int a[SIZE_OF_NUM][SIZE_OF_BIT],int mid,int n,int b,int reverse_or_not)
48 //SIZE_OF_NUM格雷码个数    SIZE_OF_BIT 格雷码位数
49 //mid 中间点序号          n 本次操作格雷码个数   b格雷码位数   reverse_or_not 为0则下一位为01  ,为1则下一位为10      
50 {
51     if(n==1)
52         return;
53     else
54     {
55         for(int i=mid-n/2+1;i<=mid;i++)
56         {
57             a[i][b]=reverse_or_not;
58         }
59         for(int j=mid+1;j<mid+n/2+1;j++)
60         {
61             a[j][b]=1-reverse_or_not;
62         }
63 //        if(n>=1)
64         {
65         get_Gray_code(a,mid-n/4,n/2,b+1,0);
66         get_Gray_code(a,mid+n/4,n/2,b+1,1);
67         }
68     }
69 }

 

题目要求:

从文件中输入一个数字,输出对应位数的格雷码,例如:

//input.txt
3
//output.txt
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0

 

posted @ 2019-03-09 16:05  shadowgully  阅读(2073)  评论(0编辑  收藏  举报