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.
 
 
 

67 lines
1.3 KiB

#include <stdio.h>
#include <string.h>
void printLargest(int length, unsigned long list[length]){
unsigned int sum = 0;
printf("The largest %d are: ", length);
for (int i = 0; i < length; ++i) {
sum += list[i];
printf("%d", list[i] );
if ( i < length-1 ) printf(", ");
}
printf("\nThe total is: %d\n", sum);
}
void addToList(unsigned int length, unsigned long list[length], unsigned int contender){
for ( int i = 0; i < length; ++i ){
if ( contender > list[i] ){
for (int j = length-1; j>i; --j){
list[j] = list[j-1];
}
list[i] = contender;
break;
}
}
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
char buffer[10] = {'\0'};
FILE *fp=fopen(argv[1], "r");
unsigned int value = 0, total=0;
unsigned long largest[3]={0,0,0};
while (!feof (fp)){
buffer[0]='\0';
value=0;
fgets(buffer, 10, fp);
printf( " - %s\n", buffer );
if (strlen(buffer) == 1){
printf("Total %d\n", total);
addToList(3,largest,total);
total=0;
} else {
sscanf(buffer,"%d\n",&value);
total+=value;
}
}
printf("Total %d\n", total);
addToList(3,largest,total);
printLargest(3,largest);
//printf("The largest is %d\n", *largest);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}