Advent of Code - Day 3

 read in about 2 minutes

Now that I have a template for these challenges things are going a bit faster. Maybe I’m just getting back into it now but this seemed easier than the past two.

Part 1

Here we need to create the largest number from a string of numbers representing the joltage of a battery in a bank of batteries. An example provided is, 987654321111111, you can make the largest joltage possible, 98, by turning on the first two batteries. This is done with a series of banks and the total is the answer to the puzzle.

For this part I chose to ignore the fact that a second part was coming and write the solution in a way that would definitely have to be reworked for part two. The moment when you’re writing a for loop next to another for loop that does the same thing is one that should give you pause.

Anyway, this inflexible setup worked fine for the first parts example and input text so I got away with this short sighted decision temporarily.

Part 2

This part expands the number of batteries you need to enable to 12 so completing it with the same sort of code would be a bit of a nightmare. So I kept some of what I had but the series of for loops had to go.

What I ended up creating is a for loop that determines the maximum number in the string but always ensures there are enough values remaining to the left so we can create a jolgate string of length 12.

for i in range(0, len(bank)-(JOLTAGE_LENGTH-len(joltage)-1)):
    if int(bank[i]) > int(max):
        max = bank[i]
        index = i
joltage += str(max)
new_bank = bank[index+1:len(bank)]
return highestJoltage(new_bank, joltage)

One nice thing about this solution is the global variable JOLTAGE_LENGTH which is set to 12 to solve this puzzle but could also be set to 2 to solve part 1. This is not always the case for these sorts of puzzles but if I wrote the first part the right way the first time part 2 would just be changing the value to this variable (and running it of course).

This solution runs in 0.02 seconds which I’m pretty happy with.

Listening to: Vulfpeck - 1612
Christopher Himes

I'm Christopher Himes (he⁠/⁠him), an accomplished tech professional living in Metro Detroit. I'm currently looking for work as a product owner or developer.

More about me

Interactions

@techhub.social/@everythingalsocan@gamepad.club/@Tipa@mastodon.world/@hamatti@adw99@mastodon.social@newsmast.community/@programming

Comments

This blog uses a Mastodon and webmentions for comments. You can comment by replying on Mastodon/ActivityPub/Fediverse account or webmention.

Related Posts

Recent Posts