77 lines
1.6 KiB
C
77 lines
1.6 KiB
C
|
#include "stdio.h"
|
||
|
#include "stdlib.h"
|
||
|
#include "string.h"
|
||
|
|
||
|
int compare(const void* a, const void* b) {
|
||
|
return (*(int*)a - *(int*)b);
|
||
|
}
|
||
|
|
||
|
int main(int argc, char* argv[]) {
|
||
|
int size = 0;
|
||
|
int lines = 0;
|
||
|
int sum = 0;
|
||
|
int* list1 = NULL;
|
||
|
int* list2 = NULL;
|
||
|
|
||
|
if(argc < 2) {
|
||
|
fprintf(stderr, "Filename required\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
FILE* file = fopen(argv[1], "r");
|
||
|
if(file == NULL) {
|
||
|
fprintf(stderr, "Could not open %s\n", argv[1]);
|
||
|
return 2;
|
||
|
}
|
||
|
|
||
|
char* line = NULL;
|
||
|
size_t line_size = 0;
|
||
|
while(getline(&line, &line_size, file) > 0) {
|
||
|
lines += 1;
|
||
|
}
|
||
|
|
||
|
rewind(file);
|
||
|
list1 = malloc(sizeof(int)*lines);
|
||
|
list2 = malloc(sizeof(int)*lines);
|
||
|
|
||
|
for(int i = 0; i < lines; i++) {
|
||
|
char* line_save = NULL;
|
||
|
getline(&line, &line_size, file);
|
||
|
char* num1 = strtok_r(line, " ", &line_save);
|
||
|
char* num2 = strtok_r(NULL, " ", &line_save);
|
||
|
if(num1 == NULL || num2 == NULL) continue;
|
||
|
|
||
|
list1[i] = atoi(num1);
|
||
|
list2[i] = atoi(num2);
|
||
|
size += 1;
|
||
|
}
|
||
|
free(line);
|
||
|
|
||
|
qsort(list1, size, sizeof(int), compare);
|
||
|
qsort(list2, size, sizeof(int), compare);
|
||
|
|
||
|
for(int i = 0; i < size; i++) {
|
||
|
sum += abs(list1[i] - list2[i]);
|
||
|
}
|
||
|
|
||
|
fprintf(stdout, "Sum: %d\n", sum);
|
||
|
|
||
|
int similarity = 0;
|
||
|
int* counts = malloc(sizeof(int)*size);
|
||
|
memset(counts, 0, sizeof(int)*size);
|
||
|
|
||
|
for(int i = 0; i < size; i++) {
|
||
|
for(int j = 0; j < size; j++) {
|
||
|
if(list1[i] == list2[j]) counts[i] += 1;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for(int i = 0; i < size; i++){
|
||
|
similarity += list1[i] * counts[i];
|
||
|
}
|
||
|
|
||
|
fprintf(stdout, "Similarity: %d\n", similarity);
|
||
|
|
||
|
return 0;
|
||
|
}
|