r/adventofcode • • Dec 02 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-

--- Day 2: Password Philosophy ---


Advent of Code 2020: Gettin' Crafty With It


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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

EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!

99 Upvotes

1.2k comments sorted by

View all comments

1

u/AJs_Sandshrew Dec 02 '20

Python.

Just found out about this competition yesterday and I'm looking forward to practicing my skills

infile = "./02_input.txt"

with open(infile, 'r') as f:
    data = f.readlines()
    data = [i.strip() for i in data]

def parse_line(line):
    parts = line.split(" ")
    nums = parts[0].split("-")
    min = int(nums[0])
    max = int(nums[1])
    letter = parts[1][0]
    string = parts[2]
    return min, max, letter, string

def count_valid(data):
    valid = 0
    for i in data:
        min, max, letter, string = parse_line(i)
        letter_count = string.count(letter)
        if letter_count >= min and letter_count <= max:
            valid += 1
    return valid

def count_valid_2(data):
    valid = 0
    for i in data:
        pos1 = False
        pos2 = False
        min, max, letter, string = parse_line(i)
        index1 = min - 1
        index2 = max - 1
        if string[index1] == letter:
            pos1 = True
        if string[index2] == letter:
            pos2 = True
        if pos1 != pos2:
            valid += 1
    return valid
    
print(count_valid(data))
print(count_valid_2(data))

1

u/daggerdragon Dec 02 '20

Just found out about this competition yesterday and I'm looking forward to practicing my skills

Welcome to Advent of Code! We hope you have fun while practicing those skills :D