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.
 
 
 

102 lines
2.7 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 ){
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");
}
}
bool** foldPaperX( unsigned int width, unsigned int height, unsigned int col, bool **paper){
bool **newPaper=(bool**)malloc( col * sizeof(bool *));
for(unsigned int x=0; x < col;x++) {
newPaper[x]=(bool*)malloc( (height) *sizeof(bool));
memset(newPaper[x], 0, sizeof(bool) * ( 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];
return newPaper;
}
bool** foldPaperY( unsigned int width, unsigned int height, unsigned int row, bool **paper){
bool **newPaper=(bool**)malloc( (width) * sizeof(bool *));
for(unsigned int x=0; x < width; x++) {
newPaper[x]=(bool*)malloc( (row) *sizeof(bool));
memset(newPaper[x], 0, sizeof(bool) * ( 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] );
return newPaper;
}
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);
}
printf("Max x: %i Max y: %i\n", maxx, maxy);
bool **paper=(bool**)malloc( (maxx+1) * sizeof(bool *));
for(unsigned int i=0; i<=maxx;i++)
{
paper[i]=(bool*)malloc( (maxy+1) *sizeof(bool));
memset(paper[i], 0, sizeof(bool) * ( 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;
while (!feof(fp) && fscanf(fp, "fold along %c=%i\n", &direction, &position)){
printf("Trying to fold in %c direction at position %i\n", direction, position);
if ( direction == 'x' ){
paper = foldPaperX(maxx+1, maxy+1, position, paper);
maxx = position - 1;
printPaper( maxx + 1, maxy + 1, paper );
} else {
paper = foldPaperY(maxx+1, maxy+1, position, paper);
maxy = position - 1;
printPaper( maxx+1, maxy+1, paper );
}
}
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}