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.

92 lines
1.6 KiB

3 years ago
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
int countRows(FILE *fp){
unsigned int lines=0;
while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp,"%*c")))
++lines;
return lines;
}
int countCols(FILE *fp){
unsigned int lineLength=0;
char ch = fgetc(fp);
while ( ch != '\n' ){
lineLength++;
ch = fgetc(fp);
}
return lineLength;
}
bool isMinimum(int rows, int cols, int grid[rows][cols], int row, int col){
// Check above
if ( row > 0 && grid[row-1][col] <= grid[row][col] ) return false;
//check below
if ( row < rows-1 && grid[row+1][col] <= grid[row][col] ) return false;
// Check left
if ( col > 0 && grid[row][col-1] <= grid[row][col] ) return false;
//check below
if ( col < cols-1 && grid[row][col+1] <= grid[row][col] ) return false;
return true;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
if ( fp == NULL ) {
return 1;
}
unsigned int rows=countRows(fp);
rewind(fp);
unsigned int cols=countCols(fp);
rewind(fp);
int grid[rows][cols];
memset( &grid, 0, rows*cols*sizeof(int) );
unsigned int risk=0;
unsigned int row=0, col=0;
for ( char ch = fgetc(fp); EOF != ch; ch=fgetc(fp)){
if ( ch == '\n' ){
row++;
col=0;
} else {
grid[row][col] = atoi(&ch);
col++;
}
}
for ( unsigned int row = 0; row < rows; row++ ){
for ( unsigned int col = 0; col < cols; col++ ){
if ( isMinimum(rows, cols, grid, row, col) ){
risk+= grid[row][col]+1;
}
}
}
printf("Total risk at lowpoints: %i\n", risk);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}