blob: 72f8aa5c8e487669a6e1e903b2b638dec5f66c4f (
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#if 0
#define PFILE "sample.txt"
#else
#define PFILE "input.txt"
#endif
size_t valid_passwds1;
size_t valid_passwds2;
void Parts()
{
char ch;
FILE *fp;
fp = fopen(PFILE, "r");
if(fp == NULL) assert(0);
size_t passwd_cap = 100;
size_t tstr_cap = 4;
int num1 = 0;
int num2 = 0;
char passwd_char;
char password[passwd_cap]; size_t passwd_sz = 0;
char temp_str1[tstr_cap]; size_t i_tstr1 = 0;
char temp_str2[tstr_cap]; size_t i_tstr2 = 0;
char temp_str3[passwd_cap]; size_t i_tstr3 = 0;
int mode = 0; // 0-read nums; 1-read num2; 2-read char; 3-read pass
while((ch = fgetc(fp)) != EOF)
{
// Parse
if(mode == 0)
{
if(ch == '-') { i_tstr1 = 0; mode = 1; continue; }
temp_str1[i_tstr1] = ch;
i_tstr1 += 1;
assert(i_tstr1 < tstr_cap);
}
else if(mode == 1)
{
if(ch == ' ') { i_tstr2 = 0; mode = 2; continue; }
temp_str2[i_tstr2] = ch;
i_tstr2 += 1;
assert(i_tstr2 < tstr_cap);
}
else if(mode == 2)
{
if(ch == ':') continue;
if(ch == ' ') { mode = 3; continue; };
passwd_char = ch;
}
else if(mode == 3)
{
if(ch != '\n')
{
temp_str3[i_tstr3] = ch;
i_tstr3 += 1;
assert(i_tstr3 < passwd_cap);
}
else
{
passwd_sz= i_tstr3;
i_tstr3 = 0;
mode = 0;
}
}
if(ch == '\n')
{
temp_str1[tstr_cap - 1] = '\0';
temp_str2[tstr_cap - 1] = '\0';
temp_str3[passwd_sz] = '\0';
num1 = atoi(temp_str1);
num2 = atoi(temp_str2);
strcpy(password, temp_str3);
// reset all vars
memset(temp_str1, 0, sizeof(char)*tstr_cap);
memset(temp_str2, 0, sizeof(char)*tstr_cap);
memset(temp_str3, 0, sizeof(char)*passwd_cap);
// ## Part 1 ##
// check password validity
size_t seen_char = 0;
for(int i=0; i<passwd_sz; i++)
if(password[i] == passwd_char) seen_char += 1;
if(seen_char >= num1 && seen_char <= num2) valid_passwds1 += 1;
// ## Part 2 ##
if(!(password[num1-1] == passwd_char) != !(password[num2-1] == passwd_char)) //XOR !a != !b
valid_passwds2 += 1;
}
}
fclose(fp);
printf("RESULT-1: %d\n", valid_passwds1);
printf("RESULT-2: %d\n", valid_passwds2);
}
int main()
{
Parts();
return 0;
}
|