Snippets

Steve Adams Advent of Code - Day 5

Created by Steve Adams last modified
'''
http://adventofcode.com/day/5

--- Day 5: Doesn't He Have Intern-Elves For This? ---

Santa needs help figuring out which strings in his text file are naughty or nice.

A nice string is one with all of the following properties:

- It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
- It contains at least one letter that appears twice in a row, like xx,
  abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
- It does not contain the strings ab, cd, pq, or xy, even if they are
  part of one of the other requirements.

For example:

- ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings.
- aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap.
- jchzalrnumimnmhp is naughty because it has no double letter.
- haegwjzuvuyypxyu is naughty because it contains the string xy.
- dvszwmarrgswjxmb is naughty because it contains only one vowel.

How many strings are nice?
'''

import string

with open("naughty-strings.txt", "r") as strings:
    strings = strings.readlines()

vowels       = ['a', 'e', 'i', 'o', 'u']
naughtyPairs = ['ab', 'cd', 'pq', 'xy']
niceCount    = 0

def isNice(string):
    lastChar = None
    vowelCount = 0
    containsDouble = False

    for char in string:
        if (char in vowels):
            vowelCount += 1;

        if lastChar:
            if (lastChar + char) in naughtyPairs:
                return False;

            if lastChar == char:
                containsDouble = True

        lastChar = char

    return (containsDouble and (vowelCount >= 3));

for string in strings:
    if isNice(string):
        niceCount += 1

print("There are " + str(niceCount) + " nice strings.")

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.