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.
 
 
 

60 lines
1.5 KiB

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define POSSIBLE_SPAWN_AGES 9
unsigned long countFish(unsigned long *fishCount){
unsigned long count = 0;
for( unsigned int i = 0; i < POSSIBLE_SPAWN_AGES; i++ ){
count += fishCount[i];
}
return count;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
unsigned int no;
char ch;
// I realised that the ordering of the fish doesn't matter. What matters is how many of them are of each age.
// This array will contain the number of fish of age 1 in fishCount[1] and so on.
unsigned long fishCount[POSSIBLE_SPAWN_AGES] = {0};
while ( fscanf( fp, "%i%c", &no, &ch ) ){
fishCount[no]++;
if ( ch == '\n' ) break;
}
for ( unsigned int i = 0; i < 256; i++ ){
// "backup" the number of fish of age 0 as the memmove will loose this
unsigned long age0 = fishCount[0];
memmove( &fishCount[0], &fishCount[1], sizeof(unsigned long) * (POSSIBLE_SPAWN_AGES - 1) );
// All the fish that had a spawn_age of 0 will now have a spawn age of 6
fishCount[6] += age0;
// They will also all have a new fish with age of 8
fishCount[8] = age0;
//printf("\nDay %i:\n", i+1);
//for( unsigned int j = 0; j < POSSIBLE_SPAWN_AGES; j++){
// printf("Fish with spawn age %i: %lu\n", j, fishCount[j]);
//}
}
printf("There are %lu Fish.\n",countFish(fishCount));
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}