Day 2: Advent of Code

Day 2: Advent of Code

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)
              
        

要查看或添加评论,请登录

Brodie Heginbotham的更多文章

  • Advent of Code Day 1

    Advent of Code Day 1

    This was a fun one! Took me around 40 minutes, but most of that time was getting more familiar with Python. One thing I…

社区洞察

其他会员也浏览了