Advertisement
bob_f

AOC2021Day14.py

Sep 29th, 2023 (edited)
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1.  
  2. template = ''
  3. pairRules = {}
  4.  
  5. def getPuzzleData():
  6.     template = ''
  7.     pairRules = {}
  8.  
  9.     with open('AOC2021D14.txt') as INFILE:
  10.         lines = INFILE.read().split('\n')
  11.  
  12.     template = lines[0]
  13.  
  14.     for line in range(2, len(lines)):
  15.         lineElems = lines[line].split(' -> ')
  16.         pairRules[lineElems[0]] = lineElems[1]
  17.  
  18.     return template, pairRules
  19.  
  20.  
  21. def doStep(aTemplate, aPairRules):
  22.     lTemplate = ''
  23.     lOldPairs = []
  24.     lNewPairs = []
  25.  
  26.     for pairStartPos in range(len(aTemplate) - 1):
  27.         lOldPairs.append(aTemplate[pairStartPos:pairStartPos+2])
  28.  
  29.     for lOldPair in lOldPairs:
  30.         if lOldPair in aPairRules:
  31.             lNewPairs.append(lOldPair[0] + aPairRules[lOldPair] + lOldPair[1])
  32.  
  33.     lTemplate = lNewPairs[0]
  34.    
  35.     for lNewPairIdx in range(1, len(lNewPairs)):
  36.         if lTemplate[-1] == lNewPairs[lNewPairIdx][0]:
  37.             lTemplate += lNewPairs[lNewPairIdx][1:]
  38.         else:
  39.             lTemplate += lNewPairs[lNewPairIdx]
  40.        
  41.    
  42.     return lTemplate
  43.  
  44. def getElementQuantities(aTemplate):
  45.     lElementQuantitites = {}
  46.  
  47.     for element in aTemplate:
  48.         lElementQuantitites.setdefault(element, 0)
  49.         lElementQuantitites[element] += 1
  50.  
  51.     lElementQuantitites = sorted(lElementQuantitites.items(), key=lambda item: item[1])
  52.     return lElementQuantitites
  53.  
  54. #
  55. # Main program
  56. #
  57.  
  58. STEPS=10
  59. template, pairRules = getPuzzleData()        
  60. print(f'{template=}')
  61. print(f'{pairRules=}')
  62.  
  63. for step, _ in enumerate(range(STEPS), start=1):
  64.     template = doStep(template, pairRules)
  65.     print(f'After {step=}: {len(template)=}')
  66.  
  67. elementQuantities = getElementQuantities(template)
  68. print(f'{elementQuantities}')
  69. print(f'{elementQuantities[0][1]}')
  70. print(f'{elementQuantities[-1][1] - elementQuantities[0][1]}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement