Advent of Code: Day 3 Solution

Still pretty straight-forward

Day 3 changed a little bit from the last two days, and is still pretty straight forward. Today asked to determine whether a list of three integers would make a possible triangle.

A possible triangle is one where any two sides add up to be larger than any single side.

As always, my code is available on Github.

Part 1:

# Read in the input file.
with open ("input.txt", "r") as myfile:  

validCount = 0  
for line in data:  
    sides = line.split()
    print sides
    valid = ((int(sides[0]) + int(sides[1]) > int(sides[2])) and (int(sides[1]) + int(sides[2]) > int(sides[0])) and (int(sides[0]) + int(sides[2]) > int(sides[1])))
    if valid:
        validCount += 1

print validCount  

This code is actually pretty simple. The algorithm is:

  • read in the input file
  • iterate over each line
  • split each line into its 3 sides of a triangle
  • determine if this is valid using the logic of a triangle

Part 2:

# Read in the input file.
with open ("input.txt", "r") as myfile:  

validCount = 0  
i = 0  
while i < len(data):  
    line1 = data[i]
    line2 = data[i + 1]
    line3 = data[i + 2]

    sides1 = line1.split()
    sides2 = line2.split()
    sides3 = line3.split()

    valid1 = ((int(sides1[0]) + int(sides2[0]) > int(sides3[0])) and (int(sides1[0]) + int(sides3[0]) > int(sides2[0])) and (int(sides3[0]) + int(sides2[0]) > int(sides1[0])))
    valid2 = ((int(sides1[1]) + int(sides2[1]) > int(sides3[1])) and (int(sides1[1]) + int(sides3[1]) > int(sides2[1])) and (int(sides3[1]) + int(sides2[1]) > int(sides1[1])))
    valid3 = ((int(sides1[2]) + int(sides2[2]) > int(sides3[2])) and (int(sides1[2]) + int(sides3[2]) > int(sides2[2])) and (int(sides3[2]) + int(sides2[2]) > int(sides1[2])))

    if valid1:
        validCount += 1
    if valid2:
        validCount += 1
    if valid3:
        validCount += 1

    i += 3

print validCount  

The code for part two is very similar to the code for part one. The only difference is the part two algorithm iterates over the file in chunks of three lines. This is because the triangles are vertically defined for part two.

For reference, my input file is available here and the answers I came up with were:

  • Part 1: 917
  • Part 2: 1649

Also on a side note, Day 3 was the first day I got points toward the leaderboard! Hoping to make it onto to the leaderboard by the end of the month!