from array import array
import sys


def show_terrain(terrain, width):
    for x in range(width):
        for y in range(width):
            print(" ·●⬤"[terrain[x * width + y]], end="")
        print()


def apply_gravity(terrain, width):
    """
    $ python -m pyperf timeit --fast -s 'from examples.sandpile_array import main' 'main(10_000, False)'
    ...........
    Mean +- std dev: 3.05 sec +- 0.12 sec
    """
    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:
            return


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:
        show_terrain(terrain, width)


if __name__ == "__main__":
    main(int(sys.argv[1]))
