This was so much easier than yesterday, since I wasn’t splitting my focus between trying to be clever and trying to write shitty code.

Day 03’s problem involved digging through a block of “corrupted code” to pull out important and usable data.  I ended up forcing myself to use the logical method here, and built a Regex string.  Despite that I write a lot of simple scripts to process and convert data for automation, I don’t really use Regex ever.  It’s been something I keep telling myself to do and use and learn better.  A lot of these challenges are actually greatly helped if you use Regex searches.

So that’s what I did.

I found this online Regex builder/tester, stuck the sample code into it, and went to work until I got what I intended out of it.  I learned two things. 

  • Adding a * to “find a digit of any size” only sometimes works, and in this case, using “+” was better.   
  • You can search on multiple strings using a pipe ( | )

Once I had the Regex working and I extracted all of the valid “mul(###,###)” instances, I used a second Regex search, mostly for practice, to extract the digits from each.

Then part two added an on off trigger.  Which was fairly simple to add in, except that I left my first Regex statement in the code, for posterity, but forgot to actually use the new one, so I was getting the same answer twice.

Anyway, here is the code.

import re
# https://www.w3schools.com/python/python_regex.asp
# https://regex101.com/

with open("Day03Input.txt") as file:
    data = file.read()

rxstring = "mul\(\d+,\d+\)"
rxstring2 = "mul\(\d+,\d+\)|do\(\)|don't\(\)"
total = 0
total2 = 0
enabler = True

def multiplier(a,b):
   return int(a)*int(b)

valid = re.findall(rxstring2,data)

for each in valid:
#   print(each)
   if "don't()" in each:
     enabler = False
   elif "do()" in each:
     enabler = True
   else:
     digits = re.findall('\d+',each)
     value = multiplier(digits[0],digits[1])
     total += value
     if enabler:
       total2 += value

print(total)
print(total2)

#Part1 - 179571322
#Part2 - 103811193

Comments are closed.