Day 2: Advent of Code
Brodie Heginbotham
Impact-driven Revenue Ops Professional and Software nerd | Certified Salesforce Administrator and Apex+Javascript Programmer
This one was much harder, in my opinion. But that's partly because I added some challenges to myself.
For one, I decided to use the Advent of Code API to fetch my data. I built a module that I can use to input whatever day I'm on, and it returns me my input data.
And beyond that, I wanted to try doing some OOP in Python for this one. So I created a class with different methods for the various problem cases. This code is not perfect, and for part 2 of the problem, I didn't ever get to the exact right answer. My solution misses arrays that "zigzag," meaning that [77, 76, 77, 76, 74] is considered "safe" in my code, because each difference is in a safe range. I'm not totally sure how to solve for that, but there were only three instances of it in my data and so I could visually see them and remove them to find the right answer.
领英推荐
How would you solve for that problem?
import getInputData
import numpy as np
inputData = getInputData.getTodaysData(2)
class CheckSafe:
def __init__(self, safety=False) -> None:
if (safety == True): self.safety = True
else: self.safety = False
def checkSafeIncreasing(self, array):
difference = 0
unsafeCount = 0
for index, number in enumerate(array):
if(index==0): continue
difference = (number - array[(index - 1)])
if(difference > 3 or difference < 1): unsafeCount += 1
if (self.safety and unsafeCount < 2):
if(unsafeCount > 0):
print(array)
return True
elif (unsafeCount == 0): return True
return False
def checkSafeDecreasing(self, array):
difference = 0
unsafeCount = 0
for index, number in enumerate(array):
if(index==0): continue
difference = (array[(index - 1)] - number)
if(difference > 3 or difference < 1): unsafeCount += 1
if (self.safety and unsafeCount < 2):
if(unsafeCount > 0):
print(array)
return True
elif (unsafeCount == 0): return True
return False
def makeNestedArray(data):
nestedArray = []
dataLines = data.splitlines()
for line in dataLines:
lineList = list(map(int, line.split()))
nestedArray.append(lineList)
return nestedArray
nestedArray = makeNestedArray(inputData)
numSafeRows = 0
safeRowChecker = CheckSafe(True)
for row in nestedArray:
diffs = np.diff(row)
averageDiff = np.average(diffs)
if(averageDiff > 0):
# Increasing Number path
if(safeRowChecker.checkSafeIncreasing(row) == True):
numSafeRows += 1
else:
# Decreasing Number path
if(safeRowChecker.checkSafeDecreasing(row) == True):
numSafeRows += 1
print(numSafeRows)