Advent of Code 2018
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.
 
 
 

91 lines
2.0 KiB

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
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;
}