Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #load the wire input into arrays for processing
- input1 = open("wire1.txt", "r")
- input2 = open("wire2.txt", "r")
- wire1 = input1.read() #reads the file into a variable as one long string
- wire2 = input2.read()
- wire1 = wire1.split(",") #turns the string into an array of smaller strings
- wire2 = wire2.split(",")
- input1.close()
- input2.close()
- pos = [0,0] #set initial position
- 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
- else:
- print("unknown direction")
- def toCenter(num1, num2): #function for finding the distance from [0,0]
- distance = abs(num1) + abs(num2)
- return distance
- #plot the first wire
- plot1 = open("plot1.txt", "w")
- for i in range(len(wire1)-1): #one loop iteration per instruction
- command = list(wire1[i])
- direction = command[0] #first character is the direction
- length = "" #remaining characters are the length
- for i in range(1,len(command)):
- length += command[i]
- length = int(length)
- for i in range(length): #move position one at a time and log it
- move(direction)
- plot1.write(str(pos[0]) + "," + str(pos[1]) + "\n")
- plot1.close()
- pos = [0,0]
- #plot the second wire
- plot2 = open("plot2.txt", "w")
- for i in range(len(wire2)-1):
- command = list(wire2[i])
- direction = command[0]
- length = ""
- for i in range(1,len(command)):
- length += command[i]
- length = int(length)
- for i in range(length):
- move(direction)
- plot2.write(str(pos[0]) + "," + str(pos[1]) + "\n")
- plot2.close()
- #load the resulting plots back into arrays to be processed
- check1 = open("plot1.txt", "r")
- check2 = open("plot2.txt", "r")
- plot1 = check1.read() #reuse the plot variables since they're no longer in use
- plot2 = check2.read()
- plot1 = plot1.split("\n")
- plot2 = plot2.split("\n")
- low = 10000000000 #a ridiculously high standard to find the lowest distance to (0,0)
- #loop through both files and see how many positions are equal
- #these will be the intercepts
- for x in range(len(plot1)-2):
- for y in range(len(plot2)-2):
- if (plot1[x] == plot2[y]): #if the positions are equal
- print("The wires cross at position " + plot1[x])
- cross = plot1[x].split(",")
- dist = toCenter(int(cross[0]), int(cross[1])) #get the distance and compare to the current low
- if(dist < low):
- low = dist
- lowPos = plot1[x]
- print("The closest intercept to the center is at " + lowPos + " at a distance of " + str(low))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement