Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #requires an intersections.txt file generated from my code in Day 3, Part 1
- #and both wire files from Part 1
- #load the inputs into arrays
- file1 = open("intersections.txt", "r")
- input1 = open("wire1.txt", "r")
- input2 = open("wire2.txt", "r")
- intersections = file1.read()
- wire1 = input1.read() #reads the file into a variable as one long string
- wire2 = input2.read()
- intersections = intersections.split("\n")
- wire1 = wire1.split(",") #turns the string into an array of smaller strings
- wire2 = wire2.split(",")
- file1.close()
- input1.close()
- input2.close()
- shortStep = 100000000000000
- shortPos = ""
- def move(dir1): #function for moving the position by one, given an input direction
- if(dir1=="U"):
- pos[1] += 1
- elif(dir1=="D"):
- pos[1] -= 1
- elif(dir1=="L"):
- pos[0] -= 1
- elif(dir1=="R"):
- pos[0] += 1
- def toString(array1): #function to turn the position into a format that can be compared to the intersection
- value = str(array1[0]) + "," + str(array1[1])
- return value
- #for each intersection, run the plot for wire1 and keep running total
- #until it hits the intersection, then run the same thing for wire2.
- for a in intersections: #for each intersection
- pos = [0,0]
- stepCount = 0
- for b in range(len(wire1)-1): #for each instruction on wire1
- command = list(wire1[b])
- direction = command[0] #first character is the direction
- length = "" #remaining characters are the length
- for c in range(1,len(command)):
- length += command[c]
- length = int(length)
- for d in range(length): #move position one at a time and check
- move(direction)
- stepCount += 1
- if(a == toString(pos)): #once the position is reached,
- pos = [0,0] #reset position and run for wire2
- #keep stepCount
- for e in range(len(wire2)-1):
- command = list(wire2[e])
- direction = command[0]
- length = ""
- for f in range(1,len(command)):
- length += command[f]
- length = int(length)
- for g in range(length):
- move(direction)
- stepCount += 1
- if(a == toString(pos)):
- print("The intersection " + a + " is " + str(stepCount) + " steps away.")
- if(stepCount<shortStep):
- shortStep = stepCount
- shortPos = a
- print("The shortest step distance is " + str(shortStep) + " to intersection " + shortPos)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement