Iterate over 2d array in an expanding circular spiral

前端 未结 7 590
自闭症患者
自闭症患者 2020-12-23 14:39

Given an n by n matrix M, at row i and column j, I\'d like to iterate over all the neighboring values in a c

相关标签:
7条回答
  • 2020-12-23 15:26

    Since it was mentioned that the order of the points do not matter, I've simply ordered them by the angle (arctan2) in which they appear at a given radius. Change N to get more points.

    from numpy import *
    N = 8
    
    # Find the unique distances
    X,Y = meshgrid(arange(N),arange(N))
    G = sqrt(X**2+Y**2)
    U = unique(G)
    
    # Identify these coordinates
    blocks = [[pair for pair in zip(*where(G==idx))] for idx in U if idx<N/2]
    
    # Permute along the different orthogonal directions
    directions = array([[1,1],[-1,1],[1,-1],[-1,-1]])
    
    all_R = []
    for b in blocks:
        R = set()
        for item in b:
            for x in item*directions:
                R.add(tuple(x))
    
        R = array(list(R))
    
        # Sort by angle
        T = array([arctan2(*x) for x in R])
        R = R[argsort(T)]
        all_R.append(R)
    
    # Display the output
    from pylab import *
    colors = ['r','k','b','y','g']*10
    for c,R in zip(colors,all_R):
        X,Y = map(list,zip(*R))
    
        # Connect last point
        X = X + [X[0],]
        Y = Y + [Y[0],]
        scatter(X,Y,c=c,s=150)
        plot(X,Y,color=c)
    
    axis('equal')
    show()
    

    Gives for N=8:

    enter image description here

    More points N=16 (sorry for the colorblind):

    enter image description here

    This clearly approaches a circle and hits every grid point in order of increasing radius.

    enter image description here

    0 讨论(0)
提交回复
热议问题