2011-12-09 70 views
0

我的程序有一個問題(我的編程語言是java): 我有一個Douglas-Peucker對象,它是一個Point數組,我有一個算法Douglas-Peucker算法。我想直接在這個Points數組上工作,這裏的問題就開始了。這是道格拉斯 - 普克算法:用void方法遞歸?

protected Point[] coinImage; 

//我的構造

public Peucker(Point [] tab) { 
    coinImage = new Point[tab.length]; 
    for(int i = 0; i < coinImage.length; i++) { 
     coinImage[i] = new Point(tab[i].x, tab[i].y); 
    } 
} 
public Point[] algoDouglasPeucker() { 
    return douglasPeuckerAux(0,coinImage.length - 1); 
} 

public Point[] douglasPeuckerAux(int startIndex, int endIndex) { 
    double dmax = 0; 
    int index = 0; 
    for(int i = startIndex + 1; i < endIndex; i++) { 
     double distance = this.distancePointSegment(this.coinImage[i], this.coinImage[startIndex], this.coinImage[endIndex]); 
     if(distance > dmax) { 
      index = i; 
      dmax = distance; 
     } 
    } *** 
    if(dmax >= this.epsilon) { 
     Point[] recResult1 = douglasPeuckerAux(startIndex,index); 
     Point[] recResult2 = douglasPeuckerAux(index,endIndex); 
     Point [] result = this.unionTabPoint(recResult1, recResult2); 
     return result; 
    } 
    else { 
     return new Point[] { coinImage[0],coinImage[endIndex] }; 
     } 
} 

*** my problem is here : both methods have a specific type of return : array of Point or I want to change this because I want to work directly on my attribut (coinImage). 

如何在這個空方法改變? 請幫助我! 對不起,我忘了一個方法:我也想改變這個方法的類型:

public Point[] unionTabPoint(Point [] P1,Point [] P2) { 
    Point[] res = new Point[P1.length + P2.length]; 
    for(int i = 0; i < P1.length;i++) { 
     res[i] = new Point(P1[i].x,P1[i].y); 
    } 
    int k = 0; 
    for(int j = P1.length; j < res.length; j++) { 
     res[j] = new Point(P2[k].x,P2[k].y); 
     k++; 
    } 
    return res; 
} 

她返回兩個數組,但沒有特定的順序工會。

+0

什麼無效的方法? –

+0

我想更改三種方法:algoDouglasPeucker,DouglasPeuckerAux和unionTabPoint以void方法。我想在對象中工作,但在這裏並不是這樣。但是如何在void中改變這三種方法呢?因爲其中一個是遞歸的... – afk

回答

3

好了無效遞歸方法的基本佈局是這樣的:

int i = 0; 
public void recursive(){ 
    if(i == 6){ 
     return; 
    } 
    i++; 
    recursive(); 
} 

可以不斷循環的方法,因爲它會返回下一行,調用它的方法。在這種情況下,返回值將到達'}'並在方法結束時終止。

希望我幫助:D

+0

感謝大家的回答! :) – afk

+0

除非你想溢出你的堆棧,否則'i> = 6'可能是一個更好的主意,也可能傳遞'i'作爲參數,這可能與OP的問題更密切相關。 – AusCBloke

+0

沒錯。感謝您指出:D – Matt

1

Java正在通過引用進行調用。可以使用結果的本地實例和/或在參數列表中使用它,例如method(x, y, Point[]),並強制該方法作爲結果,您的方法調用是什麼。像:

public void doSome(x,y) { x==0 ? return : doSome(x-1, y-1); } 
0

我希望這是你在尋找什麼......(如果不是請澄清更多)

public void douglasPeuckerAux(int startIndex, int endIndex) { 
    ... 
    Point[] newCoinImage = new Point[] { coinImage[0],coinImage[endIndex] }; 
    coinImage = newCoinImage; 
} 

public void unionTabPoint(Point [] P1,Point [] P2) { 
    ... 
    coinImage = res; 
}