DEV Community

Discussion on: Daily Challenge #279 - Playing with Sandpiles

Collapse
 
masterroshan profile image
TJ Johnson

This is part of a solution using numpy and recursion, maybe I'll write the whole class later.

import numpy as np
overlays = np.array(
    [[-4, 1, 0, 1, 0, 0, 0, 0, 0],
     [1, -4, 1, 0, 1, 0, 0, 0, 0],
     [0, 1, -4, 0, 0, 1, 0, 0, 0],
     [1, 0, 0, -4, 1, 0, 1, 0, 0],
     [0, 1, 0, 1, -4, 1, 0, 1, 0],
     [0, 0, 1, 0, 1, -4, 0, 0, 1],
     [0, 0, 0, 1, 0, 0, -4, 1, 0],
     [0, 0, 0, 0, 1, 0, 1, -4, 1],
     [0, 0, 0, 0, 0, 1, 0, 1, -4]]
)

zero_overlay = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0])


def topple(piles):
    if not any(x > 3 for x in piles):
        return piles
    else:
        overlay = zero_overlay
        for i in range(len(piles)):
            if piles[i] > 3:
                overlay = overlay + overlays[i]
        return topple(piles + overlay)

from the example:

In [10]: topple(np.array([4,3,2,3,5,1,3,2,3]))
Out[10]: array([2, 3, 0, 3, 1, 1, 1, 2, 1])