diff options
| author | Mistivia <i@mistivia.com> | 2025-12-20 03:53:05 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2025-12-20 03:53:05 +0800 |
| commit | 8f13f23b1cd9da6140ea391744416e9b3569c88b (patch) | |
| tree | daf8c7a391803c59c0cc6a4b07ea44c3b62e4027 /03 | |
| parent | 8f749b3839933c4b70494682a9710e05184465cf (diff) | |
day 3 part 2
Diffstat (limited to '03')
| -rw-r--r-- | 03/part1.c | 4 | ||||
| -rw-r--r-- | 03/part2.c | 68 |
2 files changed, 71 insertions, 1 deletions
@@ -11,7 +11,9 @@ void getlines(StringVector *lines) { if (line == NULL) { break; } - StringVector_push_back(lines, line); + char *nline = str_strip(line); + free(line); + StringVector_push_back(lines, nline); } } diff --git a/03/part2.c b/03/part2.c new file mode 100644 index 0000000..bd4bacd --- /dev/null +++ b/03/part2.c @@ -0,0 +1,68 @@ +#include <stdio.h> +#include <string.h> +#include <inttypes.h> + +#include <algds/str.h> +#include <algds/vec.h> + + +void getlines(StringVector *lines) { + while (1) { + char *line = fgetline(stdin); + if (line == NULL) { + break; + } + char *nline = str_strip(line); + free(line); + StringVector_push_back(lines, nline); + } +} + +void find_max_impl(const char *line, int len, int64_t *max, int d, int pos, int64_t res) { + if (d >= 12) { + if (res > *max) { + *max = res; + } + return; + } + int curmax = -1; + IntVector maxidx; + IntVector_init(&maxidx); + for (int i = pos + 1; i < len - (11-d); i++) { + int n = line[i] - '0'; + if (n > curmax) { + IntVector_free(&maxidx); + IntVector_init(&maxidx); + curmax = n; + IntVector_push_back(&maxidx, i); + } else if (n == curmax) { + IntVector_push_back(&maxidx, i); + } + } + Int *it = IntVector_begin(&maxidx); + for (; it < IntVector_end(&maxidx); it++) { + int i = *it; + find_max_impl(line, len, max, d + 1, i, res * 10 + curmax); + } +} + +int64_t find_max(const char *line) { + int64_t len = strlen(line); + int64_t max = 0; + find_max_impl(line, len, &max, 0, -1, 0); + return max; +} + + +int main() { + StringVector lines; + StringVector_init(&lines); + getlines(&lines); + String *it = StringVector_begin(&lines); + int64_t sum = 0; + for (; it != StringVector_end(&lines); it++) { + sum += find_max(*it); + } + printf("%"PRId64"\n", sum); + return 0; +}
\ No newline at end of file |
