Skip to content

Commit

Permalink
Gray code
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 1, 2017
1 parent 07ba441 commit df56917
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 089_gray_code/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test gray_code.c
38 changes: 38 additions & 0 deletions 089_gray_code/gray_code.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <stdio.h>
#include <stdlib.h>

/**
** Return an array of size *returnSize.
** Note: The returned array must be malloced, assume caller calls free().
**/
int* grayCode(int n, int* returnSize) {
if (n < 0) {
return NULL;
}

int i, count = 1 << n;
int *codes = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
codes[i] = (i >> 1) ^ i;
}

*returnSize = 1 << n;
return codes;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}

int i, count;
int *list = grayCode(atoi(argv[1]), &count);
for (i = 0; i < count; i++) {
printf("%d ", list[i]);
}
printf("\n");

return 0;
}

0 comments on commit df56917

Please sign in to comment.