[C/C++ 演算法]- 格雷碼(Gray Code)
[C/C++ 演算法]- 格雷碼(Gray Code)
剛才找資料時發現一個C/C++的教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。
拷貝來源:
http://openhome.cc/Gossip/AlgorithmGossip/
http://openhome.cc/Gossip/AlgorithmGossip/GrayCode.htm
#include <stdio.h>
#include <stdlib.h>
void doGray(int, void (*)(int*, int));
void init(int*, int);
int firstOneOf(int*, int);
void next(int*, int, int);
int isLast(int*, int);
void print(int*, int);
int main(void) {
int length;
printf("輸入位元數:");
scanf("%d", &length);
doGray(length, print);
return 0;
}
void doGray(int length, void (*take)(int*, int)) {
int* gray = malloc(length * sizeof(int));
init(gray, length);
take(gray, length);
int isOdd = 1;
while(!isLast(gray, length)) {
next(gray, length, isOdd);
isOdd = 1 - isOdd;
take(gray, length);
}
free(gray);
}
void init(int* gray, int length) {
int i;
for(i = 0; i < length; i++) { gray[i] = 0; }
}
int firstOneOf(int* gray, int length) {
int j;
for(j = 0; gray[j] == 0; j++);
return j;
}
void next(int* gray, int length, int isOdd) {
int i = isOdd ? 0 : firstOneOf(gray, length) + 1;
gray[i] = !gray[i];
}
int isLast(int* gray, int length) {
int i;
for(i = 0; i < length - 1; i++) if(gray[i]) { return 0; }
return gray[i];
}
void print(int* gray, int length) {
int j;
for(j = length - 1; j >= 0; j--) { printf("%d", gray[j]); }
printf("\n");
}
|