Looping in a spiral

前端 未结 30 2674
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:16

    I have an open source library, pixelscan, that is a python library that provides functions to scan pixels on a grid in a variety of spatial patterns. Spatial patterns included are circular, rings, grids, snakes, and random walks. There are also various transformations (e.g., clip, swap, rotate, translate). The original OP problem can be solved as follows

    for x, y in clip(swap(ringscan(0, 0, 0, 2)), miny=-1, maxy=1):
        print x, y
    

    which yields the points

    (0,0) (1,0) (1,1) (0,1) (-1,1) (-1,0) (-1,-1) (0,-1) (1,-1) (2,0) (2,1) (-2,1) (-2,0)
    (-2,-1) (2,-1)
    

    The libraries generators and transformations can be chained to change the points in a wide variety of orders and spatial patterns.

提交回复
热议问题