Advertisement
Guest User

AoC 2020 Day 12 Part 2

a guest
Dec 12th, 2020
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.22 KB | None | 0 0
  1. import os
  2.  
  3. start = {"E": 0, "W": 0, "N": 0, "S": 0}
  4. waypoint = {"E": 10, "W": 0, "N": 1, "S": 0}
  5.  
  6.  
  7. def parse_input(filename):
  8.     dir_path = os.path.dirname(os.path.realpath(__file__))
  9.     f = open(dir_path + '/' + filename, 'r')
  10.     content = f.readlines()
  11.     output = []
  12.  
  13.     for command in content:
  14.         command = command.strip()
  15.         if command == "R270":
  16.             command = "L90"
  17.         if command == "L270":
  18.             command = "R90"
  19.  
  20.         output.append((command[:1], command[1:]))
  21.  
  22.     return output
  23.  
  24.  
  25. def rotate_coordinates(by, direction, obj):
  26.     rotated = {}
  27.  
  28.     if by == "180":
  29.         rotated["E"] = obj["W"]
  30.         rotated["W"] = obj["E"]
  31.         rotated["S"] = obj["N"]
  32.         rotated["N"] = obj["S"]
  33.     elif by == "90" and direction == "R":
  34.         rotated["S"] = obj["E"]
  35.         rotated["E"] = obj["N"]
  36.         rotated["W"] = obj["S"]
  37.         rotated["N"] = obj["W"]
  38.     else:
  39.         rotated["W"] = obj["N"]
  40.         rotated["S"] = obj["W"]
  41.         rotated["E"] = obj["S"]
  42.         rotated["N"] = obj["E"]
  43.    
  44.     return rotated
  45.  
  46.  
  47. def transform_coordinates(obj):
  48.     if obj["E"] >= obj["W"]:
  49.         obj["E"] = obj["E"] - obj["W"]
  50.         obj["W"] = 0
  51.     if obj["W"] > obj["E"]:
  52.         obj["W"] = obj["W"] - obj["E"]
  53.         obj["E"] = 0
  54.     if obj["N"] >= obj["S"]:
  55.         obj["N"] = obj["N"] - obj["S"]
  56.         obj["S"] = 0
  57.     if obj["S"] > obj["N"]:
  58.         obj["S"] = obj["S"] - obj["N"]
  59.         obj["N"] = 0
  60.     return obj
  61.  
  62.    
  63. def execute_move(wp, pos, command):
  64.     if command[0] in ["R", "L"]:
  65.         wp = rotate_coordinates(command[1], command[0], wp)
  66.        
  67.     if command[0] in ["E", "W", "S", "N"]:
  68.         wp[command[0]] += int(command[1])
  69.        
  70.     if command[0] == "F":
  71.         for coordinate in wp:
  72.             pos[coordinate] += int(command[1]) * wp[coordinate]
  73.    
  74.     return wp, pos
  75.    
  76.  
  77. if __name__ == "__main__":
  78.     data = parse_input('t1_input.txt')
  79.     output = 0
  80.    
  81.     for move in data:
  82.          current = execute_move(waypoint, start, move)
  83.          waypoint = current[0]
  84.          start = current[1]
  85.        
  86.     for key in transform_coordinates(start):
  87.         output += start[key]
  88.    
  89.     print(output)
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement