summaryrefslogtreecommitdiff
path: root/6.c
blob: 5a9bb1f99e38e6133840289c60976d880c6b41a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


int
main(int argc, char ** argv)
{
	char buf[32];
	int len = 4, c, n = 0;

	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;

		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 of length %d read after %d bytes\n", len, n);

	return 0;
}