diff options
author | Adam Spragg <adam@spra.gg> | 2022-12-06 15:01:51 +0000 |
---|---|---|
committer | Adam Spragg <adam@spra.gg> | 2022-12-06 15:01:51 +0000 |
commit | e70ab44a91e6016d84bfaba5d297b02d830571bc (patch) | |
tree | 3202e9c0797687010c0819c64f611f3235ddc143 | |
parent | 3d74618a696287e2aec6352894b9c75e04cf7817 (diff) |
Solve puzzle 6 part 2
-rw-r--r-- | 6.c | 66 |
1 files changed, 55 insertions, 11 deletions
@@ -1,31 +1,75 @@ #include <stdio.h> +#include <stdlib.h> +#include <unistd.h> 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; } |