August 15, 2024

Solution for Advent of Code 2017 - Day 4: High-Entropy Passphrases

Link to the puzzle text

Part 1

In this puzzle, we are given a list of passphrases to validate. A passphrases consists of multiple words and is valid, when there is no duplicate word.

We iterate over all lines in the input and convert the word list into a word set to get rid of duplicates. If the number of elements in this set is still the same as the list before, we have no duplicates and the passphrase is valid.

num_valid = 0
for line in lines:
words = line.split(" ")
if len(words) == len(set(words)):
num_valid += 1

Part 2

In part 2, there is an additional condition. For a passphrase to be valid, each word should not be an anagram of another word in the same phrase.

To implement this condition, we reuse the code from part 1. Before converting the word list into a set, we sort each word alphabetically. This creates a canonical representation for each possible anagram and we can get rid of anagrams this way.

num_valid = 0
for line in lines:
words = line.split(" ")
new_words = []
for word in words:
word = "".join(sorted(word))
new_words.append(word)
if len(words) == len(set(new_words)):
num_valid += 1

Link to my solutions

No comments:

Post a Comment