Advertisement
illuminati229

Aoc 2022 Day 25

Dec 25th, 2022
1,093
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. from time import time
  2.  
  3. c_dict = {
  4.     2: "2",
  5.     1: '1',
  6.     0: '0',
  7.     -1: '-',
  8.     -2: '=',
  9. }
  10.  
  11. def timer_func(func):
  12.     # This function shows the execution time of
  13.     # the function object passed
  14.     def wrap_func(*args, **kwargs):
  15.         t1 = time()
  16.         result = func(*args, **kwargs)
  17.         t2 = time()
  18.         print(f'Function {func.__name__!r} executed in {(t2 - t1):.4f}s')
  19.         return result
  20.  
  21.     return wrap_func
  22.  
  23.  
  24. def snafu_to_dec(snafu: str) -> int:
  25.     if len(snafu) == 0 :
  26.         return 0
  27.     d = 0
  28.     for i, c in enumerate(snafu[::-1]):
  29.         if c == '-':
  30.             d += -1 * (5 ** i)
  31.         elif c == '=':
  32.             d += -2 * (5 ** i)
  33.         else:
  34.             d += int(c) * (5 ** i)
  35.     return d
  36.  
  37.  
  38. def dec_to_snafu(dec: int) -> str:
  39.     i = 0
  40.     snafu = ''
  41.     while True:
  42.         max_range = 2 * (5 ** i)
  43.         for j in range(i):
  44.             max_range += 2 * (5 ** j)
  45.         if max_range >= dec:
  46.             break
  47.         i += 1
  48.     other_center = 0
  49.     for n in range(i, -1, -1):
  50.         other_max = sum([2 * (5 ** j) for j in range(n)])
  51.         for c in c_dict.keys():
  52.             center = c * (5 ** n) + other_center
  53.             if n != 0:
  54.                 if center - other_max < dec <= center + other_max:
  55.                     snafu += c_dict[c]
  56.                     other_center = center
  57.                     break
  58.             else:
  59.                 if center + other_max == dec:
  60.                     snafu += c_dict[c]
  61.                     break
  62.  
  63.     return snafu
  64.  
  65.  
  66. @timer_func
  67. def day25(filepath, part2=False):
  68.     with open(filepath) as fin:
  69.         lines = [line.strip() for line in fin.readlines()]
  70.  
  71.     decs = [snafu_to_dec(x) for x in lines]
  72.     snafus = [dec_to_snafu(x) for x in decs]
  73.     for a, b, c in zip(decs, snafus, lines):
  74.         print(a, b, c)
  75.     dec_sum = sum(decs)
  76.     snafu_sum = dec_to_snafu(dec_sum)
  77.     return snafu_sum
  78.  
  79.  
  80. def main():
  81.     assert day25('test25') == '2=-1=0'
  82.     print(f"Part 1: {day25('input25')}")
  83.  
  84.     # assert day25('test25', True) == 1
  85.     # print(f"Part 2: {day25('input25', True)}")
  86.  
  87.  
  88. if __name__ == '__main__':
  89.     main()
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement