2013-03-02 37 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字典序上升,爲了打印出結果。