Advertisement
hhoppe

Advent of code 2023 day 12 fast

Dec 16th, 2023 (edited)
705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. def day12(s0, *, part2=False):  # Dynamic programming, without numba.
  2.   total = 0
  3.  
  4.   for line in s0.splitlines():
  5.     s, right = line.split()
  6.     counts = tuple(map(int, right.split(',')))
  7.     if part2:
  8.       s = '?'.join([s] * 5)
  9.       counts *= 5
  10.  
  11.     s += '.'
  12.     # Dynamic programming over the string position and the counts position.
  13.     num_matches = np.zeros((len(s) + 1, len(counts) + 1), int)
  14.     num_matches[0, 0] = 1
  15.  
  16.     for s_index in range(len(s)):
  17.       for counts_index in range(len(counts) + 1):
  18.         if num := num_matches[s_index, counts_index]:
  19.           if s[s_index] != '#':
  20.             num_matches[s_index + 1, counts_index] += num
  21.           if counts_index < len(counts):
  22.             n = counts[counts_index]
  23.             if s[s_index : s_index + n].replace('?', '#') == '#' * n and s[s_index + n] != '#':
  24.               num_matches[s_index + n + 1, counts_index + 1] += num
  25.  
  26.     total += num_matches[-1, -1]
  27.  
  28.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement