diff options
| author | Mistivia <i@mistivia.com> | 2025-12-21 21:26:24 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2025-12-21 21:26:24 +0800 |
| commit | 5eb6bd32ca4102bf29c7fabd26984c1c7c351c1e (patch) | |
| tree | f0eadead0bf078761d9cb0c13263fbc0ca1339ec /05/part1.c | |
| parent | ee1a1d291e822723202bd2e23612d6f65cfc20fc (diff) | |
day 5 part1
Diffstat (limited to '05/part1.c')
| -rw-r--r-- | 05/part1.c | 136 |
1 files changed, 136 insertions, 0 deletions
diff --git a/05/part1.c b/05/part1.c new file mode 100644 index 0000000..0ad59b8 --- /dev/null +++ b/05/part1.c @@ -0,0 +1,136 @@ +#include <ctype.h> +#include <stdio.h> +#include <assert.h> +#include <errno.h> + +#include <algds/vec.h> +#include <algds/str.h> + +#define PANIC do { \ + fprintf(stderr, "panic at %s:%d\n", __FILE__, __LINE__); \ + abort(); \ +} while (0) + +void expect_char(char e) { + int c = fpeek(stdin); + if (c != e) { + PANIC; + } + fgetc(stdin); +} + +void skip_space() { + while (1) { + int c = fpeek(stdin); + if (c == EOF) return; + if (isspace(c)) { + fgetc(stdin); + } else { + return; + } + } +} + +bool string2long(const char *s, long *num) { + char *end; + errno = 0; + *num = strtol(s, &end, 10); + if (end == s) { + return false; + } + if (errno != 0) { + return false; + } + return true; +} + +int64_t parse_integer() { + long ret; + StrBuilder sb; + StrBuilder_init(&sb); + while (1) { + int c = fpeek(stdin); + if (isdigit(c)) { + fgetc(stdin); + StrBuilder_append_char(&sb, c); + } else { + break; + } + } + if (strlen(sb.buf) == 0) { + PANIC; + } + StrBuilder_append_char(&sb, '\0'); + if (!string2long(sb.buf, &ret)) { + PANIC; + } + free(sb.buf); + return ret; +} + +typedef struct { + int64_t start; + int64_t end; +} Range; + +void Range_show(Range self, FILE *fp) { + fprintf(fp, "%ld-%ld", self.start, self.end); +} + +VECTOR_DEF(Range) +VECTOR_IMPL(Range) + +Range parse_range() { + Range ret; + ret.start = parse_integer(); + expect_char('-'); + ret.end = parse_integer(); + expect_char('\n'); + return ret; +} + +int main() { + RangeVector ranges; + RangeVector_init(&ranges); + int c; + while (1) { + c = fpeek(stdin); + if (c == '\n') { + break; + } else if (isdigit(c)) { + Range r = parse_range(); + RangeVector_push_back(&ranges, r); + } else { + PANIC; + } + } + expect_char('\n'); + LongVector ids; + LongVector_init(&ids); + while (1) { + c = fpeek(stdin); + if (isdigit(c)) { + long id = parse_integer(); + LongVector_push_back(&ids, id); + c = fpeek(stdin); + if (c == EOF) break; + expect_char('\n'); + } + } + int count = 0; + for (int i = 0; i < LongVector_len(&ids); i++) { + long n = ids.buffer[i]; + for (int j = 0; j < RangeVector_len(&ranges); j++) { + Range r = ranges.buffer[j]; + if (n >= r.start && n <= r.end) { + count++; + break; + } + } + } + printf("%d\n", count); + + RangeVector_free(&ranges); + LongVector_free(&ids); + return 0; +}
\ No newline at end of file |
