Advertisement
dbarrera

Advent Of Code Day 3 Part 1 v2

Dec 5th, 2019
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2.  
  3.  
  4. def trace(l, direction, steps):
  5.     if steps == 0:
  6.         return l
  7.     else:
  8.         if direction == 'U':
  9.             while steps > 0:
  10.                 new_coord = (l[-1][0], l[-1][1] + 1)
  11.                 l.append(new_coord)
  12.                 steps -= 1
  13.             return l
  14.         elif direction == 'D':
  15.             while steps > 0:
  16.                 new_coord = (l[-1][0], l[-1][1] - 1)
  17.                 l.append(new_coord)
  18.                 steps -= 1
  19.             return l
  20.         elif direction == 'R':
  21.             while steps > 0:
  22.                 new_coord = (l[-1][0] + 1, l[-1][1])
  23.                 l.append(new_coord)
  24.                 steps -= 1
  25.             return l
  26.         elif direction == 'L':
  27.             while steps > 0:
  28.                 new_coord = (l[-1][0] - 1, l[-1][1])
  29.                 l.append(new_coord)
  30.                 steps -= 1
  31.             return l
  32.  
  33.  
  34. f = open('input.txt', 'r')
  35. instructions1, instructions2 = f.readlines()
  36. f.close()
  37. instructions1 = instructions1.split(',')
  38. instructions2 = instructions2.split(',')
  39.  
  40. # test case 1
  41. # instructions1 = ['R75', 'D30', 'R83', 'U83', 'L12', 'D49', 'R71', 'U7', 'L72']
  42. # instructions2 = ['U62', 'R66', 'U55', 'R34', 'D71', 'R55', 'D58', 'R83']
  43.  
  44. # test case 2
  45. # instructions1 = ['R98', 'U47', 'R26', 'D63', 'R33', 'U87', 'L62', 'D20', 'R33', 'U53', 'R51']
  46. # instructions2 = ['U98', 'R91', 'D20', 'R16', 'D67', 'R40', 'U7', 'R15', 'U6', 'R7']
  47.  
  48. coords1 = [(0, 0)]
  49. for instruction in instructions1:
  50.     coords1 = trace(coords1, instruction[0], int(instruction[1:]))
  51. coords2 = [(0, 0)]
  52. for instruction in instructions2:
  53.     coords2 = trace(coords2, instruction[0], int(instruction[1:]))
  54.  
  55. crossings = set(coords1) & set(coords2)
  56.  
  57. print(crossings)
  58. for x in crossings:
  59.     print(x[0] + x[1])
  60.  
  61. plt.scatter(*zip(*crossings))
  62. plt.plot(*zip(*coords1), 'r-')
  63. plt.plot(*zip(*coords2), 'b-')
  64. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement