home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c220 / 4.ddi / DEMOS / GREYCODE.C < prev    next >
Encoding:
C/C++ Source or Header  |  1990-12-16  |  1.2 KB  |  51 lines

  1. /*
  2.    Generate Grey codes -- an enumeration of the integers of N bits so that
  3.    successively listed integers differ in only 1 bit position in their
  4.    binary representation.
  5.    The Grey codes of N bits can be obtained from the Grey codes of N-1 bits
  6.    as follows:
  7.     0 (Grey codes of N-1 bits).
  8.     1 (Grey codes of N-1 bits, in reverse).
  9. */
  10. typedef int Grey_code;
  11. typedef enum{fwd,rev} direction;
  12. void Each_GC(int N, direction D, void Yield(Grey_code)!) {
  13.    if (N == 1)
  14.       if (D == fwd) {
  15.      Yield(0); Yield(1);
  16.      }
  17.       else {
  18.      Yield(1); Yield(0);
  19.      }
  20.    else {
  21.       void P(Grey_code C) {
  22.      Yield( (1 << (N-1)) | C);
  23.      }
  24.       if (D == fwd) {
  25.      Each_GC(N-1,fwd,Yield);
  26.      Each_GC(N-1,rev,P);
  27.      }
  28.       else {
  29.      Each_GC(N-1,fwd,P);
  30.      Each_GC(N-1,rev,Yield);
  31.      }
  32.       }
  33.    }
  34.  
  35. void main() {
  36.    int N;
  37.    for (N = 1; N <= 4; N++) {
  38.       void P(Grey_code C) {
  39.      void Print_binary(int C, int Field_width) {
  40.         if (Field_width > 1) Print_binary(C >> 1, Field_width-1);
  41.         printf("%1d",C&1);
  42.         }
  43.      printf("%*c",8-N,' ');
  44.      Print_binary(C,N);
  45.      printf("\n");
  46.      }
  47.       printf("Grey code of %d bits:\n",N);
  48.       Each_GC(N,fwd,P);
  49.       }
  50.    }
  51.