#include #include #include #include void *read_file_contents(const char *fname, size_t *len) { FILE *f = fopen(fname, "r"); if (!f) { perror(fname); return NULL; } fseek(f, 0, SEEK_END); *len = ftell(f); rewind(f); void *contents = malloc(*len); if (!contents) { perror("malloc"); fclose(f); return NULL; } fread(contents, *len, 1, f); fclose(f); return contents; } void remove_dupes(char *mem, size_t len) { int found; char last_char; size_t last_char_pos; do { found = 0; last_char = '\0'; last_char_pos = 0; for (size_t i = 0; i < len; i++) { if (!mem[i]) continue; if (tolower(mem[i]) == tolower(last_char) && mem[i] != last_char) { mem[i] = mem[last_char_pos] = '\0'; found = 1; last_char_pos = 0; last_char = '\0'; } else { last_char_pos = i; last_char = mem[last_char_pos]; } } } while (found); } size_t strip_zeroes(char *mem, size_t len) { size_t new_len = len; char *current = mem + len - 1; while (len) { while (len && *current) {len--; current--;} if (!len) break; char *start = current; while (len && !*current) {len--; current--;} size_t diff = new_len - len - (start - current); memmove(current + 1, start + 1, diff); new_len = len + diff; } return new_len; } int main() { size_t string_len; char *string = read_file_contents("input", &string_len); if (!string) return 0; while (isspace(string[string_len - 1])) string[--string_len] = '\0'; puts("Removing dupes..."); remove_dupes(string, string_len); puts("Stripping zeroes..."); string_len = strip_zeroes(string, string_len); printf("Remaining polymers: %lu\n", string_len); free(string); return 0; }