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.

91 lines
1.9 KiB

3 years ago
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX(a, b) ((a) < (b) ? (b) : (a))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
void printGrid(unsigned int maxx, unsigned int maxy, unsigned int grid[maxx+1][maxy+1]){
for( unsigned int y = 0; y <= maxy; y++ ){
for( unsigned int x = 0; x <= maxx; x++ ){
printf("%3i", grid[x][y]);
}
printf("\n");
}
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
unsigned int maxx=0, maxy=0;
while (!feof (fp)){
int x1=0,x2=0,y1=0,y2=0;
fscanf(fp, "%i,%i -> %i,%i\n", &x1,&y1,&x2,&y2);
maxx= MAX( maxx, MAX( x1, x2 ) );
maxy= MAX( maxy, MAX( y1, y2 ) );
}
unsigned int grid[maxx+1][maxy+1];
memset( &grid, 0, (maxx+1)*(maxy+1)*sizeof(int) );
rewind(fp);
unsigned int cellsWithOverlap=0;
unsigned int iteration = 0;
while (!feof (fp)){
int x1=0,x2=0,y1=0,y2=0;
fscanf(fp, "%i,%i -> %i,%i\n", &x1,&y1,&x2,&y2);
//printf("Iteration: %i\n", iteration);
if ( x1 == x2 ){ // Virtical lines
for( unsigned int y = MIN(y1,y2); y<=MAX(y1,y2); y++ )
if ( 1 == grid[x1][y]++) cellsWithOverlap++;
} else if ( y1 == y2 ){ // Horisontal lines
for( unsigned int x = MIN(x1,x2); x<=MAX(x1,x2); x++ )
if ( 1 == grid[x][y1]++) cellsWithOverlap++;
} else { // Diaganal lines
// Since we know all diagonals are 45 deg we only need to worry about if this is 1 or -1
int dx = (x2 - x1) / abs(x2 - x1);
int dy = (y2 - y1) / abs(y2 - y1);
for (unsigned int i = 0; i <= MAX(x1,x2) - MIN(x1,x2); i++){
unsigned int x = x1 + ( dx * i );
unsigned int y = y1 + ( dy * i );
if ( 1 == grid[x][y]++) cellsWithOverlap++;
}
}
iteration++;
}
printf("%i cells with overlap\n", cellsWithOverlap);
//printGrid(maxx, maxy, grid);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}