Posts

Advent of Code Day 2

Dec 2, 2020 | 2 minutes to read

Tags: geeky, software

Today is day two of the Advent of Code. See yesterday’s post for an explanation.

Today’s challenge was, as expected, a little harder than yesterday’s, but not much really. I have 4 stars now!

Here is the code I wrote for puzzle 1 today:

# Advent of Code day 2 part 1 - How many passwords are valid according to their policies?
with open("c:\\git\\advent-2020\\2.txt", "r") as f:
    passwords = f.read().splitlines() 
count = 0
for line in passwords:
    # example line:  8-9 x: xxxxxxxrk
    posNum = line.find(" ")
    dashPos = line.find("-")
    numValid = line[0:posNum]
    firstValid = numValid[0:dashPos]
    lastValid = numValid[dashPos+1:posNum]
    charValid = line[posNum+1:posNum+2]
    passwd = line[posNum+4:]
    validCharCount = 0
    for ch in passwd:
        if ch == charValid:
            validCharCount += 1
    print (firstValid + "-"+ lastValid +  "-" + charValid + "-" + passwd + "-" + str(validCharCount))
    if validCharCount >= int(firstValid) and validCharCount <= int(lastValid):
        count += 1
    # print (line)
    print("count = " + str(count))
print("There are " + str(len(passwords)) + " passwords in the file, of which, " + str(count) + " are valid passwords.")

And here is the code for puzzle 2:

# Advent of Code day 2 part 2 
with open("c:\\git\\advent-2020\\2.txt", "r") as f:
    passwords = f.read().splitlines() 
count = 0
ctr = 20
for line in passwords:
    # example line:  8-9 x: xxxxxxxrk
    spacePos = line.find(" ")
    dashPos = line.find("-")
    numValid = line[0:spacePos]
    firstValid = numValid[0:dashPos]
    lastValid = numValid[dashPos+1:spacePos]
    charValid = line[spacePos+1:spacePos+2]
    passwd = line[spacePos+4:]
    validCharCount = 0
    chCnt = 1
    for ch in passwd:
        if chCnt == int(firstValid) or chCnt == int(lastValid):
            if ch == charValid:
                validCharCount += 1
        chCnt += 1
    print (firstValid + "-"+ lastValid +  "-" + charValid + "-" + passwd + "-" + str(validCharCount))
    if validCharCount == 1:
        count += 1
    # print (line)
    print("count = " + str(count))        
print("There are " + str(len(passwords)) + " passwords in the file, of which, " + str(count) + " are valid passwords.")

If anyone reads this and has ideas on how I could write more efficient or “pythonic” code, please let me know!

Cheers!


You can leave a comment on this post here.