Advent of Code 2020 - Day 2


Advent of Code 2020 - Day 2

If you’re like Linus Torvalds, and you just want me to show you the code, check it out here!

Intro

This one requires some string searching to find out if a given character appears in the correct position.

Day 2

My plan here was to break the raw string into semantic parts (lower bound, target character, password) and then utilize helper functions to do the validation.

The two functions below do most of the work. count_chars() does what it sounds like - counts the number of times a char appears. The main outer loop then compares that count to the boundaries, updating the total if necessary.

is_valid_password() determines whether a given string meets the requirement to have a specific character in one (and only one) of two positions. I’m using an exclusive-or for this. I’ll admit, it could be more readable.

I could improve count_chars() by having it accept the boundaries and exit early, avoiding some unneccessary work.

Overall, this one was pretty straightforward as well. I did get hung up for a little while on the second part - I misread the instructions and was pretty sure that my implementation was correct. It would have been, if the instructions were slightly different! :)

def count_chars(string: str, char: str) -> int:
    """
    Counts the number of times a character appears in a string.
    """
    found_char = 0
    for letter in string:
        if char == letter:
            found_char += 1

    return found_char


def is_valid_password(lower: int, upper: int, string: str, char: str) -> bool:
    """
    Determines whether a string contains a given character within the specified
    range.
    """
    # XOR
    return (string[lower-1] == char) != (string[upper-1] == char)

As always, see the full repo here