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/bandfreak4life Dec 02 '20 edited Dec 02 '20

Tried with some Python with a little help from regex. I quickly realized part 2 was XOR. Putting my Computer Engineering degree to good use!:

import re 
with open('input.txt','r') as f:
    lines = [line.rstrip() for line in f]
    #Part 1 pswd policy 
    # entry: 1-3 a: abcde 
    #   1 is the min occurance of a letter needed 
    #   3 is the max occurance of a letter allowed 
    #   a is the letter these rules apply to 
    #   abcde is the password to check 
    number_valid = 0 
    for line in lines: 
        tmp_arr = re.split('-| |:',line) 
        minNum = int(tmp_arr[0]) 
        maxNum = int(tmp_arr[1]) 
        letter = tmp_arr[2] 
        pswd = tmp_arr[4]

        if pswd.count(letter) >= minNum and pswd.count(letter) <= maxNum:
            number_valid += 1
    print('{} valid passwords found according to policy 1'.format(number_valid))

    #Part 2 pswd policy
    # entry: 1-3 a: abcde
    #   1 and 3 are character positions of where a letter needs to appear     (but only in one of these positions)
    #   a is the letter these rules apply to
    #   abcde is the password to check
    number_valid = 0
    for line in lines:
        tmp_arr = re.split('-| |:',line)
        #position rules need to be offset by 1
        pos1 = int(tmp_arr[0])-1
        pos2 = int(tmp_arr[1])-1
        letter = tmp_arr[2]
        pswd = tmp_arr[4]

        if (pswd[pos1] == letter) ^ (pswd[pos2] == letter):
           number_valid += 1
    print('{} valid passwords found according to policy 2'.format(number_valid)

0

u/daggerdragon Dec 02 '20 edited Dec 02 '20

This code is really hard to read on old.reddit. Could you please edit it using old.reddit's four-spaces formatting instead of new.reddit's triple backticks? Note that if you're using the visual editor, you may have to "Switch to Markdown" to get Reddit to understand the formatting properly.

Post has been fixed! Thank you!

2

u/tslater2006 Dec 02 '20

And also ensure there is a blank line between non code and code. learned that one the hard way