Introduction
Gray code, a coding scheme proposed by Frank Gray, a scientist at Bell's laboratory decades ago, was mainly used to transmit signals to prevent errors. In addition to applications in communication and hardware design, Gray code is also widely used in computer-related science, such as generating all subsets of a set in order.
Gray Code generates all subsets of the Set in order
This concept is very simple. For example, if our set is {a, B, c}, then the subsets produced in order should be:
Empty set (000) -- 0 (numbers are sorted sequentially from 0)
A (100) -- 1
AB (110) -- 2
ABC (111) -- 3
AC
B
BC
C
So how does Gray Code generate such a sequence?
The idea of Gray code is very clever. We can calculate the number of the generated subset (ranging from 0 ~ 2 ^ N-1), the first child set is an empty set (numbered 0, an even number ). Each subset after it is determined by the previous subset. If the number of the first subset is an even number, the first (from the left) of the previous subset is changed) (0 to 1 or 1 to 0) as the new subset. If the number of the first subset is an odd number, the value (0 to 1 or 1 to 0) next to the first one on the left of the binary of the previous subset is changed to a new subset.
Based on the above Gray Code idea, the number of the first subset (000) is 0 (even) in the example of the set {a, B, c ), calculate that the second subset is generated by the first value of the first number on the left of the first subset, which is 100, that is, a (only 1 character, A is the leftmost character corresponding to 1 in 100 ). According to the number 1 (ODD) of the second subset ), calculate that the third subset is generated by the value of the second subset that changes from the value next to the first 1 in the left number (100-> 110). Then, 110 corresponds to AB. The subsequent subsets can all be generated in order.
Non-Recursive Implementation of Gray code in C Language
The following code is successfully debugged under vs2008:
int sum(int n){ if(1<=n) return n+sum(n-1); else return 0;}void gray(char *ptr){ int len=strlen(ptr); int num=(1<<len);// printf("num=%d \n",num); int i,j,k; int mod,tmp,mask,tmp1,tmp2; mask=1<<len-1; // printf("mask=%d \n",mask); mod=0;//(1<<len)-1; for(i=0;i<num-1;i++) { if(i%2==0) { tmp=mod&mask; // printf("tmp=%d ",tmp); if(0!=tmp) {mod=mod&(~mask);} else {mod=mod|(mask);} } else { tmp1=1<<(len-1); for(j=0;j<len;j++) {// printf(" in else"); if(mod&tmp1) break; tmp1=tmp1>>1; // printf("tmp1=%d ",tmp1); } tmp1=tmp1>>1; // printf(">>1 tmp1=%d ",tmp1); if(tmp1!=0) { tmp=mod&tmp1; if(0!=tmp) {mod=mod&(~tmp1);} else {mod=mod|(tmp1);} } } tmp2=1<<len-1; for(k=0;k<len;k++) { if(mod&tmp2) printf("%c",ptr[k]); tmp2=tmp2>>1; } printf("\n"); }}int main(){// printf(" result=%d ",sum(4)); char *p="abcd"; gray(p); system("pause");}