#include #include #include #include #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= 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; }