fast-abelian-sandpile/sandpile.py

41 lines
1.1 KiB
Python

"""This is the easy implementation, just applying the fireing rule repeateadly."""
import sys
def apply_gravity(terrain):
"""
$ python -m pyperf timeit --fast -s 'from examples.sandpile1 import main' 'main(10_000, False)'
...........
Mean +- std dev: 11.1 sec +- 0.2 sec
"""
while True:
width = len(terrain)
did_someting = False
for x in range(width):
for y in range(width):
if terrain[x][y] >= 4:
terrain[x][y] -= 4
terrain[x - 1][y] += 1
terrain[x + 1][y] += 1
terrain[x][y + 1] += 1
terrain[x][y - 1] += 1
did_someting = True
if not did_someting:
return
def main(height, show=True):
width = int(height ** .5) + 1
terrain = [[0] * width for _ in range(width)]
terrain[width // 2][width // 2] = height
apply_gravity(terrain)
if show:
import numpy
numpy.set_printoptions(threshold=sys.maxsize, linewidth=999)
print(numpy.array(terrain))
if __name__ == "__main__":
main(int(sys.argv[1]))