My solutions to the advent of code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

132 lines
2.2 KiB

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
unsigned int getScore(char symbol){
switch (symbol) {
case ')':
return 3;
break;
case ']':
return 57;
break;
case '}':
return 1197;
break;
case '>':
return 25137;
break;
default:
return 0;
break;
}
}
void corruptLine(char expected, char found, FILE *fp){
printf(" Expected %c, but found %c instead.", expected, found);
fscanf(fp, "%*s");
}
int lineLength(FILE *fp){
unsigned int lineLength=0;
char ch = fgetc(fp);
while ( ch != '\n' && ch != EOF ){
lineLength++;
ch = fgetc(fp);
if ( lineLength > 30 ) break;
}
return lineLength;
}
char reverse(char ch){
switch (ch) {
case '[':
return ']';
break;
case ']':
return '[';
break;
case '(':
return ')';
break;
case ')':
return '(';
break;
case '{':
return '}';
break;
case '}':
return '{';
break;
case '<':
return '>';
break;
case '>':
return '<';
break;
}
return 0;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
unsigned int score=0;
char ch = '\0';
while ( !feof(fp) ){
unsigned int lineStart = ftell(fp);
ch = getc(fp);
if ( EOF == ch ) break;
fseek(fp, lineStart, SEEK_SET);
unsigned int length = lineLength(fp);
fseek(fp, lineStart, SEEK_SET);
char line[length+1];
memset(line, '\0', sizeof(char) * (length + 1));
char depthArr[(length+1)/2];
memset(line, 'a', sizeof(char) * (length + 1));
unsigned int depth=0;
memset(line, '\0', sizeof(char) * ( ( length + 1 ) / 2 ));
while (1){
ch = getc(fp);
printf("%c", ch);
// Cant break out of switch and loop at the same time
if ( ch == '\n' ) break;
switch (ch) {
case '[':
case '(':
case '{':
case '<':
depthArr[depth] = ch;
depth++;
break;
case ']':
case ')':
case '}':
case '>':
depth--;
if ( depthArr[depth] != reverse(ch) ){
corruptLine( reverse(depthArr[ depth ]), ch, fp );
score += getScore(ch);
}
break;
}
}
}
printf("Final Score: %i", score);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}