Advertisement
nairby

2022 Day 13

Dec 13th, 2022
1,197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.11 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import sys
  3. from typing import List
  4. from typing import Tuple
  5. from itertools import zip_longest
  6. from functools import cmp_to_key
  7.  
  8. RAN_OUT = -9999999999
  9.  
  10. def get_data1(filename: str) -> List[str]:
  11.     with open(filename,'r') as f:
  12.         lines = f.read()
  13.     lines = lines.split("\n\n")
  14.     return lines
  15.  
  16. def get_data2(filename: str) -> List[str]:
  17.     with open(filename,'r') as f:
  18.         lines = f.read().splitlines()
  19.     return [l for l in lines if l != '']
  20.  
  21. def compare_packets(p1,p2) -> int:
  22.     for v1,v2 in zip_longest(p1,p2,fillvalue=RAN_OUT):
  23.         if v1 == RAN_OUT: return -1
  24.         if v2 == RAN_OUT: return +1
  25.         if type(v1) == int and type(v2) == int:
  26.             if v1 < v2: return -1
  27.             if v1 > v2: return +1
  28.         elif type(v1) == list and type(v2) == list:
  29.             outcome = compare_packets(v1,v2)
  30.             if outcome is not None: return outcome
  31.         elif type(v1) == list and type(v2) == int:
  32.             outcome = compare_packets(v1,[v2])
  33.             if outcome is not None: return outcome
  34.         elif type(v1) == int and type(v2) == list:
  35.             outcome = compare_packets([v1],v2)
  36.             if outcome is not None: return outcome
  37.         else:
  38.             quit(f"Error: Unknown types: v1={type(v1)}, v2={type(v2)}")
  39.  
  40. def main():
  41.  
  42.     # Part 1
  43.     input = get_data1(sys.argv[1])
  44.     part1 = 0
  45.     for ix,pair in enumerate(input):
  46.         parts = pair.split("\n")
  47.         first,second = parts[0], parts[1]
  48.  
  49.         first  = eval(first)
  50.         second = eval(second)
  51.  
  52.         if compare_packets(first,second) == -1:
  53.             part1 += ix + 1
  54.  
  55.     print(f"Part 1: {part1}") # 5760
  56.  
  57.     # Part 2
  58.     input = get_data2(sys.argv[1])
  59.     input.append("[[2]]")
  60.     input.append("[[6]]")
  61.     packets = [eval(p) for p in input]
  62.     packets = sorted(packets, key=cmp_to_key(compare_packets))
  63.    
  64.     part2 = 1
  65.     for ix,packet in enumerate(packets):
  66.         if packet == [[2]]: part2 *= (ix+1)
  67.         if packet == [[6]]: part2 *= (ix+1)
  68.     print(f"Part 2: {part2}") # 26670
  69.  
  70.  
  71. if __name__=="__main__":
  72.     main()
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement