|
| 1 | +""" |
| 2 | +Project Euler Problem 164: https://projecteuler.net/problem=164 |
| 3 | +
|
| 4 | +Three Consecutive Digital Sum Limit |
| 5 | +
|
| 6 | +How many 20 digit numbers n (without any leading zero) exist such that no three |
| 7 | +consecutive digits of n have a sum greater than 9? |
| 8 | +
|
| 9 | +Brute-force recursive solution with caching of intermediate results. |
| 10 | +
|
| 11 | +>>> solution(10) |
| 12 | +21838806 |
| 13 | +""" |
| 14 | + |
| 15 | + |
| 16 | +def solve( |
| 17 | + digit: int, prev: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int] |
| 18 | +) -> int: |
| 19 | + """ |
| 20 | + Solve for remaining 'digit' digits, with previous 'prev' number, and |
| 21 | + previous-previous 'prev2' number, total sum of 'sum_max'. |
| 22 | + Pass around 'cache' to store/reuse intermediate results. |
| 23 | +
|
| 24 | + >>> solve(1, 0, 0, 9, True, {}) |
| 25 | + 9 |
| 26 | + >>> solve(1, 0, 0, 9, False, {}) |
| 27 | + 10 |
| 28 | + """ |
| 29 | + if digit == 0: |
| 30 | + return 1 |
| 31 | + comb = 0 |
| 32 | + cache_str = f"{digit},{prev},{prev2}" |
| 33 | + if cache_str in cache: |
| 34 | + return cache[cache_str] |
| 35 | + for v in range(sum_max - prev - prev2 + 1): |
| 36 | + if first and v == 0: |
| 37 | + continue |
| 38 | + comb += solve(digit - 1, v, prev, sum_max, False, cache) |
| 39 | + cache[cache_str] = comb |
| 40 | + return comb |
| 41 | + |
| 42 | + |
| 43 | +def solution(n_digits: int = 20) -> int: |
| 44 | + """ |
| 45 | + Solves the problem for n_digits number of digits. |
| 46 | +
|
| 47 | + >>> solution(2) |
| 48 | + 45 |
| 49 | + """ |
| 50 | + sum_max = 9 |
| 51 | + cache: dict[str, int] = {} |
| 52 | + ans = solve(n_digits, 0, 0, sum_max, True, cache) |
| 53 | + |
| 54 | + return ans |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + print(f"{solution(10) = }") |
0 commit comments