Problem 215

completed February 11, 2021

Comments

This problem took me less than 30 minutes to complete. I used a depth first search along with memoization. Program runs in about 3 seconds.

Code

def memoize(fn):
    _cache = {}
    def wrap(*args):
        if args in _cache:
            return _cache[args]
        ret = fn(*args)
        _cache[args] = ret
        return ret
    return wrap

def solve(n, m):

    bricks = (2, 3)

    @memoize
    def _solve(i, row, prev):
        if i == m:
            return 1
        count = 0
        for b in bricks:
            crack = row[-1] + b
            if crack == n:
                count += _solve(i + 1, (0,), row + (crack,))
            elif crack in prev:
                continue
            elif crack < n - 1:
                count += _solve(i, row + (crack,), prev)
        return count

    return _solve(0, (0,), (0,))

if __name__ == '__main__':
    import sys
    n = eval(sys.argv[1])
    m = eval(sys.argv[2])
    print(solve(n, m))

Tests

import pytest
from problem import solve

_test_solve = (
        (9, 3, 8),
        (10, 4, 18),
        (11, 5, 46),
        (12, 6, 160),
        (13, 7, 960),
)

@pytest.mark.parametrize('n,m,expect', _test_solve)
def test_solve(n, m, expect):
    assert expect == solve(n, m)