aoc_omni/c/2018/5/problem_05.c

90 lines
1.9 KiB
C
Raw Normal View History

2025-11-30 21:22:21 -05:00
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
int part_1(FILE *input) {
rewind(input);
char polymer[50001];
fread(polymer, 50000, 1, input);
bool changed = true;
while(changed) {
changed = false;
for(int i = 0; i < 50000; i++) {
if(polymer[i] == ' ') continue;
for(int j = i + 1; j < 50000; j++) {
if(polymer[j] == ' ') continue;
if(polymer[i] == (polymer[j] + 'a' - 'A') || polymer[i] == (polymer[j] + 'A' - 'a') ) {
polymer[i] = ' ';
polymer[j] = ' ';
changed = true;
}
break;
}
}
}
int count = 0;
for(int i = 0; i < 50000; i++) {
if(polymer[i] != ' ') count++;
}
return count;
}
int part_2(FILE *input) {
char polymer[50001];
int best_count = 50000;
for(char to_remove = 'a'; to_remove <= 'z'; to_remove++) {
rewind(input);
fread(polymer, 50000, 1, input);
for(int i = 0; i < 50000; i++) {
if(polymer[i] == to_remove || polymer[i] == to_remove - 'a' + 'A') polymer[i] = ' ';
}
bool changed = true;
while(changed) {
changed = false;
for(int i = 0; i < 50000; i++) {
if(polymer[i] == ' ') continue;
for(int j = i + 1; j < 50000; j++) {
if(polymer[j] == ' ') continue;
if(polymer[i] == (polymer[j] + 'a' - 'A') || polymer[i] == (polymer[j] + 'A' - 'a') ) {
polymer[i] = ' ';
polymer[j] = ' ';
changed = true;
}
break;
}
}
}
int count = 0;
for(int i = 0; i < 50000; i++) {
if(polymer[i] != ' ') count++;
}
if(count < best_count) best_count = count;
}
return best_count;
}
int main() {
char *input_file_path = "../data/2018/5/input.txt";
FILE *input = fopen(input_file_path, "r");
if (input == NULL) {
printf("Can't open file %s\n", input_file_path);
return 1;
}
printf("Part 1: %d\n", part_1(input));
printf("Part 2: %d\n", part_2(input));
fclose(input);
}