Advertisement
Guest User

Advent of Code 2021. Day 10 Python solution

a guest
Dec 13th, 2021
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. with open("2021_day13_input.txt", "r", encoding="utf-8") as ifile:
  2.     dots, instructions = map(str.splitlines, ifile.read().split("\n\n"))
  3.  
  4. dot_dict = dict(zip((dots := [(int((x := line.split(","))[0]), int(x[1])) for line in dots]), [True]*len(dots)))
  5. instructions = [((x := line.split()[2].split("="))[0], int(x[1])) for line in instructions]
  6. max_x, max_y = max([k[0] for k in dot_dict.keys()]), max([k[1] for k in dot_dict.keys()])
  7.  
  8.  
  9. def fold_vertically(after_line, dot_dict):
  10.     for y_add in range(1, max_y-after_line+1):
  11.         for x in range(max_x+1):
  12.             if (x, after_line+y_add, ) in dot_dict:
  13.                 dot_dict.pop((x, after_line+y_add, ))
  14.                 dot_dict[(x, after_line-y_add, )] = True
  15.  
  16.  
  17. def fold_horizontally(after_column, dot_dict):
  18.     for x_add in range(1, max_x-after_column+1):
  19.         for y in range(max_y+1):
  20.             if (after_column+x_add, y,) in dot_dict:
  21.                 dot_dict.pop((after_column+x_add, y,))
  22.                 dot_dict[(after_column-x_add, y,)] = True
  23.  
  24.  
  25. def print_doc_dict(dot_dict):
  26.     _max_x, _max_y = max([k[0] for k in dot_dict.keys()]), max([k[1] for k in dot_dict.keys()])
  27.     for y in range(_max_y+1):
  28.         line = ""
  29.         for x in range(max_x+1):
  30.             if (x, y,) in dot_dict:
  31.                 line += "X"
  32.             else:
  33.                 line += "."
  34.         print(line)
  35.  
  36.  
  37. for pos, instruction in enumerate(instructions):
  38.     match instruction[0]:
  39.         case "x":
  40.             fold_horizontally(instruction[1], dot_dict)
  41.         case "y":
  42.             fold_vertically(instruction[1], dot_dict)
  43.     if pos == 0:
  44.         print("Nr of dots after the first fold: {}".format(len(dot_dict)))
  45.  
  46. print_doc_dict(dot_dict)
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement