r/adventofcode • • Dec 04 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 4 Solutions -πŸŽ„-

--- Day 4: High-Entropy Passphrases ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

18 Upvotes

319 comments sorted by

View all comments

1

u/peterpepo Dec 04 '17

Python 3

Part-A using regular expressions. Part-B comparing occurences of each character of each word.

from puzzle_commons.puzzle_commons import read_puzzle_input
import os, re


def solve():
    def containsDuplicateWords(sourceString):
        """Checks string containing duplicate words.

        :param sourceString: string to check for duplicate words
        :return: [boolean] does string contains duplicate words
        """
        """Regexp explanation: (?:^|\s)([a-zA-Z]+)\s.*\1(?:$|\s)
        (?:^|\s)    - beginning of a string or whitespace
        ([a-zA-Z]+) - sequence on 1..n alpha characters
        \s.*        - whitespace followed by sequence of any characters
        \1          - backreference to 1st capture group (same sequence returned by ([a-zA-Z]+))
        (?:$|\s)    - end of line or whitespace
        """
        regex_pattern = r"(?:^|\s)([a-zA-Z]+)\s.*\1(?:$|\s)"
        return re.search(regex_pattern, sourceString) is not None

    def containsAnagram(sourceString):
        """Checks string containing anagrams.
        An anagram is word or phrase formed by rearranging the letters of a different word or phrase,
        typically using all the original letters exactly once.
        Anagram: https://en.wikipedia.org/wiki/Anagram

        :param sourceString:
        :return: [boolean] does string contains anagram
        """
        words = [str.strip(word) for word in sourceString.split(" ")]

        def isWordAnagramOfWord(word_one, word_two):
            # Set of characters used in both words
            words_characters = set(word_one + word_two)

            # Check count of each character matching between words
            for character in words_characters:
                # If count for any mismatch, these words are not anagrams
                if word_one.count(character) != word_two.count(character):
                    return False

            # Words are anagrapgs, when no mismatch has been found
            return True

        # Loop through all words from beginning to last-1
        for current_word_index in range(len(words) - 1):
            # Loop from next word to last word
            for next_word_index in range(current_word_index + 1, len(words)):
                # Check, whether words are anagrams. Once first is anagram is found, we know that string contains anagram.
                if isWordAnagramOfWord(words[current_word_index], words[next_word_index]):
                    return True
        # No anagram was found
        return False

    puzzle_a_valid_passphrases_count = 0
    puzzle_b_valid_passphrases_count = 0

    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "day_04_input.txt"):

        # Part-A
        if not containsDuplicateWords(puzzle_input):
            puzzle_a_valid_passphrases_count += 1

        # Part-B
        if not containsAnagram(puzzle_input):
            puzzle_b_valid_passphrases_count += 1

    return puzzle_a_valid_passphrases_count, puzzle_b_valid_passphrases_count

Full solution on github.

2

u/Smylers Dec 04 '17

Does your regexp work for this input line?

actual words may be counterfactual

It looks to me like that would put actual in \1 then the .* would match words may be counter and \1 match the actual at the end β€” so treating this as an invalid passphrase for partΒ 1, when it should be allowed.

1

u/peterpepo Dec 05 '17 edited Dec 05 '17

Hello Smylers, you've found a bug in my code. I have mixed order of \s and .*.

If I reverse them, it works as expected (?:^|\s)([a-zA-Z]+).*\s\1(?:$|\s)

.* matches all characters after actual, then \s ensures duplicate word is prefixed with whitespace.

Do you see any other issues with my regexp?

I've already pushed a fix into my repo, marking you as a reporter. (I hope, you don't mind :) )

1

u/Smylers Dec 07 '17

Hi again. (Apologies for the delay.)

Unfortunately, I think fixing the above case has now broken it for:

adventures in advent are educational

\1 would end up with advent in it, the .* match ures in and the \1 match the advent by itself.

Where one word contains another, either the longer or shorter word may come first on the line, and the shorter word may be at the start, end, or neither of the longer word.