Last active
November 26, 2017 18:53
-
-
Save lucarinelli/499c3de23aa68ea98480b1e14f4b99df to your computer and use it in GitHub Desktop.
LAIB 8 Exercise 2: Gray Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
char s[]={'0','1'}; | |
int power(int b, int e){ | |
return e!=0?b*power(b,e-1):1; | |
} | |
void gray_r(char **matrix,int n,int shift,int symbol){ | |
if(n==0)return; | |
int i,half=power(2,n)/2; | |
for(i=0;i<half;i++)matrix[0][shift+i]=s[symbol]; | |
for(i=0;i<half;i++)matrix[0][shift+i+half]=s[!symbol]; | |
gray_r(&matrix[1],n-1,shift,symbol); | |
gray_r(&matrix[1],n-1,shift+half,!symbol); | |
} | |
char **makeGray(int n){ | |
int i; | |
char **gray_matrix=(char **)malloc(n*sizeof(char*)); | |
if(gray_matrix==NULL)return NULL; | |
for(i=0;i<n;i++){ | |
gray_matrix[i]=(char*)malloc((power(2,n)+1)*sizeof(char)); | |
if(gray_matrix[i]==NULL){ | |
while(i>0)free(gray_matrix[--i]); | |
free(gray_matrix); | |
return NULL; | |
} | |
gray_matrix[i][power(2,n)]='\0';//Too lazy to print one by one | |
} | |
gray_r(gray_matrix,n,0,0); | |
return gray_matrix; | |
} | |
void printGray(char **gray_matrix,int n){ | |
int i; | |
for(i=0;i<n;i++)printf("%s\n",gray_matrix[i]); | |
} | |
int main(int argc, char **argv){ | |
char **gray_matrix; | |
int i; | |
if(argc<2){ | |
printf("ERROR: Wrong number of arguments, 1 integer needed.\n"); | |
return EXIT_FAILURE; | |
} | |
int n=atoi(argv[1]); | |
gray_matrix=makeGray(n); | |
if(gray_matrix==NULL){ | |
printf("Something dark(er) happened...\n"); | |
return EXIT_FAILURE; | |
} | |
printGray(gray_matrix,n); | |
for(i=0;i<n;i++)free(gray_matrix[i]); | |
free(gray_matrix); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment