Skip to content

Instantly share code, notes, and snippets.

@Rushi98
Last active July 2, 2021 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rushi98/6a1103aa64ac351a58225adcbec8dd40 to your computer and use it in GitHub Desktop.
Save Rushi98/6a1103aa64ac351a58225adcbec8dd40 to your computer and use it in GitHub Desktop.
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* grayCode(int n, int* returnSize) {
int size = 1 << n; // 2 ^ n
int *sequence = (int *) calloc(size, sizeof(int));
sequence[0] = 0;
sequence[1] = 1;
for (int bitcount = 2; bitcount <= n; bitcount++) {
int curSeqSize = 1 << bitcount;
int lastSeqSize = curSeqSize / 2;
// first half: i -> (i << 1)
// Ex. bitcount = 2
// 1) 0 -> 00
// 2) 1 -> 10
for (int i = 0; i < lastSeqSize; i++) {
// printf("%d) %d -> ", i + 1, sequence[i]);
sequence[i] <<= 1;
// printf("%d\n", sequence[i]);
}
// second half: i -> (i << 1 + 1) in reverse order
// Ex. bitcount = 2
// 3) 1 -> 10 + 1 -> 11
// 4) 0 -> 00 + 1 -> 01
for (int i = 0; i < lastSeqSize; i++) {
// printf("%d) %d -> ", lastSeqSize + i + 1, sequence[lastSeqSize - i - 1]);
sequence[lastSeqSize + i] = sequence[lastSeqSize - i - 1] + 1;
// printf("%d\n", sequence[lastSeqSize + i]);
}
}
*returnSize = size;
return sequence;
}
@Rushi98
Copy link
Author

Rushi98 commented Jul 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment