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.
 
 
 

86 lines
1.6 KiB

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
#define MAX(a, b) ((a) < (b) ? (b) : (a))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
double average(unsigned int length, unsigned int *list) {
double sum = 0.0;
/* access all the arguments assigned to valist */
for (unsigned int i = 0; i < length; i++) {
sum += list[i];
}
return sum/length;
}
unsigned int totalDistance(unsigned int crabLength, unsigned int *crabs, unsigned int target){
unsigned int totalDistance = 0;
for (unsigned int i = 0; i < crabLength; i++){
unsigned int distance = abs((int)crabs[i] - (int)target);
unsigned int cost = distance * (distance + 1) / 2;
//printf( "Move from %i to %i: %i fuel\n", crabs[i], target, cost );
totalDistance += cost;
}
return totalDistance;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
FILE *fp=fopen(argv[1], "r");
unsigned int count=0;
unsigned int no;
char ch;
// Count the number of crab positions
while ( fscanf( fp, "%i%c", &no, &ch ) ){
count++;
if ( ch == '\n' ) break;
}
rewind(fp);
unsigned int min = ~0;
unsigned int max = 0;
unsigned int crabs[count];
for (unsigned int i= 0; i<count; i++ ){
fscanf( fp, "%i%c", &no, &ch );
crabs[i] = no;
min = MIN( min, no );
max = MAX( max, no );
}
unsigned int smallestCost = ~0;
for ( unsigned int i = 0; i <= max; i++ ){
smallestCost = MIN( smallestCost, totalDistance( count, crabs, i ) );
}
printf("Smallest Cost: %i\n", smallestCost);
fclose(fp);
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}