格雷码生成(分治法)

 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

 

转载于:https://www.cnblogs.com/sgawscd/p/10500987.html

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值