Riddle 3: Shocking!
We need to create yet another input read function:
#reading3
with open(argv[1]) as f:
banks : [[int]] = [ [int(char) for char in line.rstrip('\n')] for line in f.readlines() ]
A function to find the highest joltage needn't be hard:
#findjoltage
def find_joltage(bank):
first = -1
place = -1
last = -1
for i in range(len(bank)-1):
if bank[i] > first:
place = i
first = bank[i]
for i in range(place+1,len(bank)):
if last < bank[i]:
last = bank[i]
return first*10+last
Calculating the answer
file: 3a.py
<<headers>>
<<reading3>>
<<findjoltage>>
joltages = [find_joltage(bank) for bank in banks]
with open("docs/output/3a.txt","w") as f:
f.write(f"{sum(joltages)}")
Which gives us the answer:
Answer 3a
17524
Part 2: overloading joltage
Now we have to find joltage with 12 numbers, that calls for some recursion:
#joltagerecursion
def find_joltage(bank, number = 11):
if number == -1:
return 0
first = -1
place = -1
for i in range(len(bank)-number):
if bank[i] > first:
place = i
first = bank[i]
return first*10**number + find_joltage(bank[place+1:],number = number-1)
Lets execute it:
file: 3b.py
<<headers>>
<<reading3>>
<<joltagerecursion>>
joltages = [find_joltage(bank) for bank in banks]
with open("docs/output/3b.txt","w") as f:
f.write(f"{sum(joltages)}")
Which gives us the answer:
Answer 3b
173848577117276