螺旋运行的时间

时间:2016-12-02 03:20:06

标签: haskell

这是一个我在制作方面遇到一些困难的问题,但我会尽力解释一下。

想象一下,这是方桌的共同点

(0,0) (1,0) (2,0) (3,0) (4,0)

(0,1) (1,1) (2,1) (3,1) (4,1)

(0,2) (1,2) (2,2) (3,2) (4,2)

(0,3) (1,3) (2,3) (3,3) (4,3)

(0,4) (1,4) (2,4) (3,4) (4,4)

现在我有2个Ints

  

d =方形表的维度

     

t => 0且t< = d ^ 2

我需要找到一种方法来计算我将在t时刻填充的坐标,我需要用螺旋填充它,如下例所示:

t=(n^2) -> (0,0)

t=(n^2)-1 -> (1,0)

...

t=((n^2)-n)+1 -> (4,0)

t=((n^2)-n) -> (4,1)

t=((n^2)-n)-1 -> (4,2)

...


t=0 -> (2,2)

所以我想解释的是我需要按顺序访问表格:

(0,0) > (1,0) > (2,0) > (3,0) > (4,0) > (4,1) > ... > (4,4) > (3,4) > ... > (0,4) > (0,3) > (0,2) > (0,1) > (1,1) > (2,1) > (3,1) > (3,2) > (3,3) > (2,3) > (1,3) > (1,2) > (2,2)

有人可以仅使用计算我需要编辑的t=moment的{​​{1}}和d=dimension来提供有关如何构建函数的建议吗?

对不起英文错误和令人困惑的问题。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

module Spiral where

import Data.List (transpose)

type Time = Int
type Dimension = Int
type Coordinate = (Int,Int)

spiral :: Dimension -> [Coordinate]
spiral d | d <= 0    = error "Dimension must be a positive number."
         | otherwise = let square = [[(x,y)|x <- [0..(d-1)]]|y <- [0..(d-1)]]
                           rotate = reverse . transpose
                           spiral' :: [[a]] -> [a]
                           spiral' []     = []
                           spiral' (x:xs) = spiral' (rotate xs) ++ reverse x
                        in spiral' square

spiralTime :: Dimension -> Time -> Coordinate
spiralTime d t | 0 <= t && t < d*d = spiral d !! t
               | otherwise         = error $ "Time must be in [0,"++show (d*d)++")"

请注意,此函数可用作getCoordinateAtTime以获取您所描述的功能。

$> ghci stover.hs
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /home/epsilonhalbe/.ghc/ghci.conf
[1 of 1] Compiling Spiral           ( stover.hs, interpreted )
Ok, modules loaded: Spiral.
*Spiral> spiral (-1)
*** Exception: Dimension must be a positive number.
CallStack (from HasCallStack):
  error, called at stover.hs:10:24 in main:Spiral
*Spiral> spiralTime 5 25
*** Exception: Time must be in [0,25)
CallStack (from HasCallStack):
  error, called at stover.hs:20:38 in main:Spiral
*Spiral> let getCoordinateAtTime = spiralTime 5
*Spiral> getCoordinateAtTime 0
(2,2)
*Spiral> getCoordinateAtTime 24
(0,0)
*Spiral> getCoordinateAtTime 11
(0,3)