Looping in a spiral

前端 未结 30 2399
独厮守ぢ
独厮守ぢ 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:26

    Haskell, take your pick:

    spiral x y = (0, 0) : concatMap ring [1 .. max x' y'] where
        ring n | n > x' = left x' n  ++ right x' (-n)
        ring n | n > y' = up   n  y' ++ down (-n) y'
        ring n          = up n n ++ left n n ++ down n n ++ right n n
        up    x y = [(x, n) | n <- [1-y .. y]]; down = (.) reverse . up
        right x y = [(n, y) | n <- [1-x .. x]]; left = (.) reverse . right
        (x', y') = (x `div` 2, y `div` 2)
    
    spiral x y = filter (\(x',y') -> 2*abs x' <= x && 2*abs y' <= y) .
                 scanl (\(a,b) (c,d) -> (a+c,b+d)) (0,0) $
                 concat [ (:) (1,0) . tail 
                        $ concatMap (replicate n) [(0,1),(-1,0),(0,-1),(1,0)]
                        | n <- [2,4..max x y] ]
    

提交回复
热议问题