Advertisement
hhoppe

Advent of code 2023 day 12 fastest

Dec 16th, 2023
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. @numba.njit
  2. def day12_num_matches(s, counts):
  3.   num_matches = np.zeros((len(s) + 1, len(counts) + 1), np.int64)
  4.   num_matches[0, 0] = 1
  5.  
  6.   for s_index in range(len(s)):
  7.     for counts_index in range(len(counts) + 1):
  8.       num = num_matches[s_index, counts_index]
  9.       if num:
  10.         if s[s_index] != ord('#'):
  11.           num_matches[s_index + 1, counts_index] += num
  12.         if counts_index < len(counts):
  13.           n = counts[counts_index]
  14.           if s_index + n < len(s) and s[s_index + n] != ord('#'):
  15.             matches_word = True
  16.             for i in range(s_index, s_index + n):
  17.               if s[i] == ord('.'):
  18.                 matches_word = False
  19.                 break
  20.             if matches_word:
  21.               num_matches[s_index + n + 1, counts_index + 1] += num
  22.  
  23.   return num_matches[-1, -1]
  24.  
  25.  
  26. def day12(s0, *, part2=False):
  27.   total = 0
  28.   for line in s0.splitlines():
  29.     s, right = line.split()
  30.     counts = tuple(map(int, right.split(',')))
  31.     if part2:
  32.       s = '?'.join([s] * 5)
  33.       counts *= 5
  34.     s_array = np.array([ord(ch) for ch in list(s + '.')], np.uint8)
  35.     total += day12_num_matches(s_array, np.array(counts))
  36.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement