• 格雷码生成(分治法)


     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!
    ");
    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
    ",b);
    22     fclose(fp);
    23     fp=fopen("output.txt","w");
    24     if(fp==NULL)
    25     {
    26         printf("Failed to open file!
    ");
    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	",GrayCode[i][j]);
    36             fprintf(fp,"%d	",GrayCode[i][j]);
    37             fprintf(stdout,"%d	",GrayCode[i][j]);
    38         }
    39 //        printf("
    ");
    40         fprintf(fp,"
    ");
    41         fprintf(stdout,"
    ");
    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
  • 相关阅读:
    SQLSERVER 中GO的作用
    工作相关工具介绍
    SQL Server 没有足够的内存继续执行程序 (mscorlib)的解决办法
    glyphicons-halflings-regular.woff2 not found 前台错误修正
    Asp.net MVC Pager分页实现
    金融相关网站
    Excel 函数使用
    C# 使用 Invoke 实现函数的白盒 UT 测试
    反编译工具
    SQL Server 数据库修改后不允许保存
  • 原文地址:https://www.cnblogs.com/sgawscd/p/10500987.html
Copyright © 2020-2023  润新知