2013-03-02 32 views
0

如何按逆时针顺序打印数组?我知道着名的“按螺旋顺序打印数组”的算法,但看到如何以逆时针方式打印它会很有趣按逆时针顺序打印2d数组

+2

你在说什么这个“着名”的? – 2013-03-02 07:20:09

+0

您是否试过向后运行所有的循环? – 2013-03-02 06:31:04

+0

如在?对不起,我是编程新手。 – 2013-03-02 06:47:03

回答

0

假设您想到2d坐标的数组...

基本上,你必须按照y和x坐标的商的atn对你的数组排序,并按顺序打印它们。正确地迎合极点并签名改变,同时避免昂贵且数字不稳定的算术使得实现复杂化。下面的伪代码用于说明原理。

点集被分成9个类别,编号为0到8.#0包含点(0,0)将首先打印,#1,3,5,7包含正y轴上的点,负x轴,负y轴和正x轴。在这些类别中的每个类别中,点将按照距离原点越来越远的顺序打印。分类#2,4,6,8分别包含来自第二,第三,第四和第一象限的点。在每个类别中,点将被逆时针打印。位于原点相同矢量上的任何点将按照距离原点越远的顺序打印。

a:array of point(x:number,y:number)成为你的数组。定义f:array of (f1:number, f2:number, f3:number)分量地为

f[i].f1 := 
    let x := a[i].x, y := a[i].y; 
    if x=0 then 
     if y=0 then 
      0 
     else 
      if y>0 then 1 else 5 
     endif 
    else 
     if y=0 then 
      if x>0 then 7 else 3 
     else 
      if x>0 and y>0 then 
       8 
      elsif x>0 and y<0 then 
       6 
      elsif x<0 and y<0 then 
       4 
      else 
       2 
      endif 
     endif 
    endif; 

f[i].f2 := 
    let x := a[i].x, y := a[i].y, h := f[i].f1; 
    if odd(h) then 
     abs(x) + abs(y) 
    else 
     if h=0 then 
      0 
     elsif h=2 then 
      -x/y 
     elsif h=4 then 
      y/x 
     elsif h=6 then 
      -x/y 
     else 
      y/x 
     endif 
    endif; 

f[i].f3 := 
    a[i].x * a[i].x + a[i].y * a[i].y; 

用自己喜欢的排序算法订购af.f1, f.f2, f.f3字典序上升,为了打印出结果。