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.
81 lines
1.4 KiB
81 lines
1.4 KiB
3 years ago
|
#include <stdio.h>
|
||
|
#include <stdarg.h>
|
||
|
#include <stdlib.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++){
|
||
|
totalDistance += abs( (int)target - (int)crabs[i] );
|
||
|
}
|
||
|
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;
|
||
|
}
|
||
|
}
|