fast-abelian-sandpile/sandpile_array.py

36 lines
951 B
Python

"""Try using Python's arrays instead of lists."""
from array import array
import sys
def apply_gravity(terrain, width):
while True:
did_someting = False
for x in range(width ** 2):
if terrain[x] >= 4:
div, terrain[x] = divmod(terrain[x], 4)
terrain[x - 1] += div
terrain[x + 1] += div
terrain[x - width] += div
terrain[x + width] += div
did_someting = True
if not did_someting:
break
def main(height, show=True):
width = int(height ** .5) + 1
terrain = array("Q", [0] * width ** 2)
terrain[width // 2 * width + width // 2] = height
apply_gravity(terrain, width)
if show:
import numpy
numpy.set_printoptions(threshold=sys.maxsize, linewidth=999)
print(numpy.array(terrain).reshape((width, width)))
if __name__ == "__main__":
main(int(sys.argv[1]))