illuminati229

AoC 2023 Day 13

Dec 13th, 2023 (edited)
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. from time import time
  2. import numpy as np
  3.  
  4.  
  5. def timer_func(func):
  6.     # This function shows the execution time of
  7.     # the function object passed
  8.     def wrap_func(*args, **kwargs):
  9.         t1 = time()
  10.         result = func(*args, **kwargs)
  11.         t2 = time()
  12.         print(f'Function {func.__name__!r} executed in {(t2 - t1):.4f}s')
  13.         return result
  14.  
  15.     return wrap_func
  16.  
  17.  
  18. def score_map(m, smudge=False):
  19.     m = np.array([np.array([*x]) for x in m])
  20.     m = m == '#'
  21.     # searching columns first
  22.     for i in range(1, m.shape[1]):
  23.         # left slice
  24.         m_l = m[:, 0:i]
  25.         # right slice
  26.         m_r = m[:, i:]
  27.         # find the min width
  28.         w = min(m_l.shape[1], m_r.shape[1])
  29.         # reduce left and right to the same wide
  30.         m_l = m_l[:, -w:]
  31.         m_r = m_r[:, :w]
  32.         # flip the right side
  33.         m_r = m_r[:, ::-1]
  34.         if not smudge:
  35.             if (m_l == m_r).all():
  36.                 return i
  37.         else:
  38.             if (~(m_l == m_r)).sum() == 1:
  39.                 return i
  40.     for i in range(1, m.shape[0]):
  41.         m_u = m[0:i]
  42.         m_d = m[i:]
  43.         h = min(m_u.shape[0], m_d.shape[0])
  44.         m_u = m_u[-h:]
  45.         m_d = m_d[:h]
  46.         m_d = m_d[::-1]
  47.         if not smudge:
  48.             if (m_u == m_d).all():
  49.                 return i * 100
  50.         else:
  51.             if (~(m_u == m_d)).sum() == 1:
  52.                 return i * 100
  53.     return 0
  54.  
  55.  
  56. @timer_func
  57. def day13(filepath, part2=False):
  58.     with open(filepath) as fin:
  59.         maps = [[line.strip() for line in group.split('\n')] for group in fin.read().split('\n\n')]
  60.  
  61.     score = 0
  62.     for m in maps:
  63.         score += score_map(m, part2)
  64.  
  65.     return score
  66.  
  67.  
  68. def main():
  69.     assert day13('test13') == 405
  70.     print(f"Part 1: {day13('input13')}")
  71.  
  72.     assert day13('test13', True) == 400
  73.     print(f"Part 2: {day13('input13', True)}")
  74.  
  75.  
  76. if __name__ == '__main__':
  77.     main()
  78.  
Advertisement
Add Comment
Please, Sign In to add comment