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.
 
 
 

95 lines
2.5 KiB

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define MAX(a, b) ((a) < (b) ? (b) : (a))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
void printPaper( unsigned int width, unsigned int height, bool paper[width][height] ){
for ( unsigned int y = 0; y < height; y++ ){
printf("Line %i: ", y);
for ( unsigned int x = 0; x < width; x++ ){
if ( paper[x][y] == true ) printf("#");
else printf(".");
}
printf("\n");
}
}
void foldPaperX( unsigned int width, unsigned int height, unsigned int col, bool paper[width][height], bool newPaper[col][height]){
for ( unsigned int x = 1; x < width - col; x++ )
for ( unsigned int y=0; y < height; y++ )
newPaper[col - x][y] = paper[col - x][y] || paper[col + x][y];
}
void foldPaperY( unsigned int width, unsigned int height, unsigned int row, bool paper[width][height], bool newPaper[width][row]){
for ( unsigned int y=1; y < height - row; y++ )
for ( unsigned int x = 0; x < width; x++ )
newPaper[x][row - y] = ( paper[x][row - y] || paper[x][row + y] );
}
unsigned int countDots( unsigned int width, unsigned int height, bool paper[width][height] ){
unsigned int count=0;
for ( unsigned int y = 0; y < height; y++ )
for ( unsigned int x = 0; x < width; x++ )
if ( paper[x][y] == true ) count++;
return count;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
unsigned int x=0,y=0,maxx=0,maxy=0;
while ( fscanf( fp, "%i,%i\n",&x,&y )){
maxx = MAX(maxx,x);
maxy = MAX(maxy,y);
}
bool paper[maxx+1][maxy+1];
memset(paper,0,sizeof(bool) * (maxx+1) * (maxy+1) );
rewind(fp);
while ( fscanf( fp, "%i,%i\n",&x,&y )){
paper[x][y] = true;
}
printPaper( maxx+1, maxy+1, paper );
printf("\n");
char direction = '\0';
unsigned int position = 0, dots = 0;
fscanf(fp, "fold along %c=%i\n", &direction, &position);
if ( direction == 'x' ){
bool newPaper[position][maxy+1];
foldPaperX(maxx+1,maxy+1,position, paper, newPaper);
printPaper( position, maxy+1, newPaper );
dots=countDots( position, maxy+1, newPaper );
} else {
bool newPaper[maxx+1][position];
foldPaperY(maxx+1,maxy+1,position, paper, newPaper);
printPaper( maxx+1, position, newPaper );
dots=countDots( maxx+1, position, newPaper );
}
printf("\nThere are %i dots\n", dots);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}