From e70ab44a91e6016d84bfaba5d297b02d830571bc Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Tue, 6 Dec 2022 15:01:51 +0000 Subject: Solve puzzle 6 part 2 --- 6.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 11 deletions(-) diff --git a/6.c b/6.c index f36c934..5a9bb1f 100644 --- a/6.c +++ b/6.c @@ -1,31 +1,75 @@ #include +#include +#include int -main() +main(int argc, char ** argv) { - char buf[4]; - int c, n = 0; + char buf[32]; + int len = 4, c, n = 0; - while ((c = fgetc(stdin)) != EOF) { - buf[n % 4] = c; - ++n; + while ((c = getopt(argc, argv, "p:l:")) != -1) { + switch (c) { + case 'p': + if (optarg[0] == '1') + len = 4; + else if (optarg[0] == '2') + len = 14; + else { + fprintf(stderr, "Unexpected part %s\n", optarg); + return -1; + } + break; - if (n >= 4 - && buf[0] != buf[1] && buf[0] != buf[2] && buf[0] != buf[3] - && buf[1] != buf[2] && buf[1] != buf[3] && buf[2] != buf[3]) - { + case 'l': + len = atoi(optarg); + if (len < 2 || len > 32) { + fprintf(stderr, "Unexpected marker length: %d\n", len); + return -1; + } break; + + default: + return -1; } } + while ((c = fgetc(stdin)) != EOF + && c >= 'a' && c <= 'z') + { + unsigned int t = 0; + int i; + + buf[n % len] = c; + ++n; + + if (n < len) + continue; + + // All input chars are between 'a' and 'z'. + // Check for repeats with a bit field. + for (i = 0; i < len; ++i) { + unsigned int b = 1u << (buf[i] - 'a'); + if (t & b) + break; + t |= b; + } + if (i == len) // No repeats + break; + } + if (c == EOF) { printf("No marker read in %d bytes\n", n); return 1; } + if (c < 'a' || c > 'z') { + printf("Unexpected input after %d bytes\n", n); + return 1; + } - printf("Marker read after %d bytes\n", n); + printf("Marker of length %d read after %d bytes\n", len, n); return 0; } -- cgit v1.2.1