feat: Day1_2
This commit is contained in:
parent
04e8802dac
commit
c871af9701
1 changed files with 14 additions and 6 deletions
|
|
@ -17,6 +17,7 @@ int main() {
|
||||||
int *first_numbers = malloc(lines * sizeof(int));
|
int *first_numbers = malloc(lines * sizeof(int));
|
||||||
int *second_numbers = malloc(lines * sizeof(int));
|
int *second_numbers = malloc(lines * sizeof(int));
|
||||||
int current_position = 0;
|
int current_position = 0;
|
||||||
|
int count = 0;
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
|
|
||||||
file = fopen(filename, "r");
|
file = fopen(filename, "r");
|
||||||
|
|
@ -34,9 +35,9 @@ int main() {
|
||||||
current_number_string[strlen(current_number_string) - 1] = '\0';
|
current_number_string[strlen(current_number_string) - 1] = '\0';
|
||||||
}
|
}
|
||||||
if (is_first) {
|
if (is_first) {
|
||||||
first_numbers[current_position] = atoi(current_number_string);
|
first_numbers[current_position] = atoi(current_number_string);
|
||||||
} else {
|
} else {
|
||||||
second_numbers[current_position] = atoi(current_number_string);
|
second_numbers[current_position] = atoi(current_number_string);
|
||||||
}
|
}
|
||||||
is_first ^= 1;
|
is_first ^= 1;
|
||||||
if (line) {
|
if (line) {
|
||||||
|
|
@ -49,8 +50,15 @@ int main() {
|
||||||
qsort(second_numbers, lines, sizeof(int), compare_ints);
|
qsort(second_numbers, lines, sizeof(int), compare_ints);
|
||||||
|
|
||||||
for (int i = 0; i < lines; i++) {
|
for (int i = 0; i < lines; i++) {
|
||||||
int difference = abs(first_numbers[i] - second_numbers[i]);
|
for (int j = 0; j < lines; j++) {
|
||||||
sum += difference;
|
if (first_numbers[i] == second_numbers[j]) {
|
||||||
|
count++;
|
||||||
|
} else if (count != 0) {
|
||||||
|
sum += first_numbers[i] * count;
|
||||||
|
count = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("%d\n", sum);
|
printf("%d\n", sum);
|
||||||
|
|
@ -80,5 +88,5 @@ int count_lines(char *filename) {
|
||||||
}
|
}
|
||||||
|
|
||||||
int compare_ints(const void *a, const void *b) {
|
int compare_ints(const void *a, const void *b) {
|
||||||
return (*(int *)a - *(int *)b);
|
return (*(int *)a - *(int *)b);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue