14.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. lines = []
  2. with open("14.input") as f:
  3. for line in f.readlines():
  4. lines.append(line.strip())
  5. andmask = ormask = 0
  6. mask = ""
  7. mem = {}
  8. for line in lines:
  9. if line[0:4] == "mask":
  10. mask = line.split(" ")[2]
  11. andmask = int(mask.replace("X", "1"), 2)
  12. ormask = int(mask.replace("X", "0"), 2)
  13. else:
  14. line = line.split(" ")
  15. addr = int(line[0][4:-1])
  16. val_orig = int(line[2])
  17. val = (val_orig & andmask) | ormask
  18. mem[addr] = val
  19. print("Answer 1: {}".format(sum(mem.values())))
  20. mem = {}
  21. floating = []
  22. for line in lines:
  23. if line[0:4] == "mask":
  24. mask = line.split(" ")[2]
  25. ormask = int(mask.replace("X", "0"), 2)
  26. floating = []
  27. for (i, c) in enumerate(mask):
  28. if c == 'X':
  29. floating.append(35 - i)
  30. else:
  31. line = line.split(" ")
  32. addr = int(line[0][4:-1])
  33. addr |= ormask
  34. val = int(line[2])
  35. for num in range(0, 2 ** len(floating)):
  36. my_addr = addr
  37. for (j, index) in enumerate(floating):
  38. if (num >> j) & 1:
  39. my_addr |= 1 << index
  40. else:
  41. my_addr &= (0xFFFFFFFFF ^ (1 << index))
  42. mem[my_addr] = val
  43. print("Answer 2: {}".format(sum(mem.values())))