56 lines
1 KiB
C
56 lines
1 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
|
|
int main( int argc, char *argv[] ){
|
|
if( argc == 2 ) {
|
|
|
|
unsigned int gamma = 0;
|
|
unsigned int epsilon = 0;
|
|
unsigned int lineLength = 0;
|
|
unsigned int noOfLines = 0;
|
|
|
|
// Read the values into an array
|
|
FILE *fp=fopen(argv[1], "r");
|
|
char ch = fgetc(fp);
|
|
while ( ch != '\n' ){
|
|
lineLength++;
|
|
ch = fgetc(fp);
|
|
}
|
|
|
|
rewind(fp);
|
|
|
|
unsigned int digitCount[lineLength];
|
|
memset( &digitCount, 0, lineLength*sizeof(unsigned int) );
|
|
|
|
|
|
for ( int i = 0; !feof(fp); i++){
|
|
ch=fgetc(fp);
|
|
switch (ch) {
|
|
case '\n':
|
|
// I will be incremented at the end of the iteration
|
|
i=-1;
|
|
noOfLines++;
|
|
break;
|
|
case '1':
|
|
digitCount[i]++;
|
|
break;
|
|
}
|
|
}
|
|
|
|
for (unsigned int i=0; i < lineLength; i++ ){
|
|
if ( digitCount[i] > ( (double)noOfLines ) / 2 ){
|
|
gamma = gamma | 1 << (lineLength - i - 1);
|
|
} else {
|
|
epsilon = epsilon | 1 << (lineLength - i - 1);
|
|
}
|
|
}
|
|
|
|
printf("Answer: %d", gamma * epsilon);
|
|
|
|
return 0;
|
|
} else {
|
|
printf("You need to provide a file\n");
|
|
return 1;
|
|
}
|
|
}
|