73 lines
1.7 KiB
C
73 lines
1.7 KiB
C
#include <stdio.h>
|
|
#include <stdbool.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include "../lib/util.h"
|
|
|
|
char password_buffer[30] = {0};
|
|
|
|
bool is_valid_password_part_2(const char *password_line) {
|
|
int char_first, char_second;
|
|
char target_char;
|
|
|
|
sscanf(password_line, "%d-%d %c: %s", &char_first, &char_second, &target_char, password_buffer);
|
|
|
|
bool result = ((password_buffer[char_first - 1] == target_char) != (password_buffer[char_second - 1] == target_char));
|
|
|
|
// printf("%s: %s\n", password_line, result ? "valid" : "invalid");
|
|
return result;
|
|
}
|
|
|
|
bool is_valid_password_part_1(const char *password_line) {
|
|
int char_min, char_max;
|
|
char target_char;
|
|
char *password = password_buffer;
|
|
|
|
sscanf(password_line, "%d-%d %c: %s", &char_min, &char_max, &target_char, password_buffer);
|
|
while(*password > 0) {
|
|
if (*password == target_char) {
|
|
char_min--;
|
|
char_max--;
|
|
}
|
|
password++;
|
|
}
|
|
|
|
bool result = char_min <= 0 && char_max >= 0;
|
|
// printf("%s: %s\n", password_line, result ? "valid" : "invalid");
|
|
return result;
|
|
}
|
|
|
|
int count_passwords(bool (*validation_function)(const char *password)) {
|
|
char *data_buffer = load_input();
|
|
char *data = data_buffer;
|
|
|
|
int valid_passwords = 0;
|
|
int invalid_passwords = 0;
|
|
|
|
char *line = strtok(data, "\n");
|
|
do {
|
|
if (validation_function(line)) {
|
|
valid_passwords++;
|
|
} else {
|
|
invalid_passwords++;
|
|
}
|
|
} while (line = strtok(NULL, "\n"));
|
|
|
|
free(data_buffer);
|
|
return valid_passwords;
|
|
}
|
|
|
|
int part_1() {
|
|
return count_passwords(is_valid_password_part_1);
|
|
}
|
|
|
|
int part_2() {
|
|
return count_passwords(is_valid_password_part_2);
|
|
}
|
|
|
|
int main() {
|
|
printf("Part 1: %d\n", part_1());
|
|
printf("Part 2: %d\n", part_2());
|
|
return 0;
|
|
}
|