Day 2. Password Philosophy
Problem statement
https://adventofcode.com/2020/day/2 (mirror)My solution
Nothing exciting here.
We analyze input line by line, parse each line with a regular expression.
Example line: 5-11 t: glhbttzvzttkdx
Regular expression: ^(\d+)-(\d+) (\w): (.*?)$
, which in readable terms means: (first number)-(second number) (single policy character): (password till the end of line)
.
Then, depending on the part:
in Part A, we check if frequency of the policy character in the password is the range specified by first and second numbers; there is a silent assumption that first number is smaller than the second one.
in Part B, we check the characters at indexes specified by the first and second numbers (remembering that in C# indexes are zero-based, and in our input indexes are one-based), and then flip the bool variable if there is a match with the policy character – we start with
false
; if exactly one character is a match, then we flip once and end withtrue
; if both characters are matches, we flip twice and end withfalse
.
bool passwordIsValid = false;
if (policyPassword[firstIndex - 1] == policyCharacter)
{
passwordIsValid = !passwordIsValid;
}
if (policyPassword[secondIndex - 1] == policyCharacter)
{
passwordIsValid = !passwordIsValid;
}