我需要採用兩個相互遞歸方法的程序,並修改程序,使其包含單個遞歸方法。根據我的理解,我需要將遞歸調用按照調用順序放置在單個方法中,以結合這兩種遞歸方法。問題是有4個整數通過方法傳遞,第一個方法調用第二個方法兩次,第二個方法調用第一個方法兩次。在java中將兩個相互遞歸的方法轉換爲單一的遞歸方法?
這是原來的代碼:
public void drawHorizontal(Graphics graphics, double xMid, double yMid, double length)
{
// find left endpoint
double x1 = xMid - (length/2);
double y1 = yMid;
// find right endpoint
double x2 = xMid + (length/2);
double y2 = yMid;
if (length > 5)
{
// draw a line from (x1,y1) to (x2,y2)
graphics.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
// draw a vertical line with left end of horizontal as midpoint of new line
drawVertical(graphics, x1, y1, (length));
// draw a vertical line with right endof horizontal as midpoint of new line
drawVertical(graphics, x2, y2, (length));
}
} // end drawHorizontal()
public void drawVertical(Graphics graphics, double xMid, double yMid, double length)
{
// find upper endpoint
double x1 = xMid;
double y1 = yMid - (length/2);
// right lower endpoint
double x2 = xMid;
double y2 = yMid + (length/2);
if (length > 5)
{
// draw a line from (x1,y1) to (x2,y2)
graphics.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
// draw a 1/2 size horizontal line with top end of vertical as midpoint of new line
drawHorizontal(graphics, x1, y1, (length/2));
// draw a 1/2 horizontal line with bottom end of vertical as midpoint of new line
drawHorizontal(graphics, x2, y2, (length/2));
}
} // end drawVertical()
下面是我最近修改的代碼。它的醜陋我知道,但我不知道如何獨立調整x和y座標。我試圖通過創建更多變量來解決這個問題,但我不禁覺得我只是在做更多的工作。我能找到的最接近的堆棧問題是this。我從11號開始就已經在這裏了,現在是4:15。向正確的方向微調將不勝感激,謝謝你的時間。
編輯*感謝您的快速回復,我很感激。我知道,以這種方式破解相互遞歸的方法似乎違反直覺,但我是編程和Java的新手,所以我正在探索解決問題的不同方法。這是我最終把它分解,並且運行良好。感謝您的時間。
修改後的代碼:
public void Total(Graphics graphics, boolean type, double xMid, double yMid, double length) {
double x1;
double y1;
// find right endpoint
double x2;
double y2;
if (type == false) {
// find left endpoint
x1 = xMid - (length/2);
y1 = yMid;
// find right endpoint
x2 = xMid + (length/2);
y2 = yMid;
if (length > 5) {
// draw a line from (x1,y1) to (x2,y2)
graphics.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
// draw a vertical line with left end of horizontal as midpoint of new line
Total(graphics, true, x1, y1, (length));
// draw a vertical line with right endof horizontal as midpoint of new line
Total(graphics, true, x2, y2, (length));
}
} else {
// find upper endpoint
x1 = xMid;
y1 = yMid - (length/2);
// right lower endpoint
x2 = xMid;
y2 = yMid + (length/2);
if (length > 5) {
// draw a line from (x1,y1) to (x2,y2)
graphics.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
// draw a 1/2 size horizontal line with top end of vertical as midpoint of new line
Total(graphics, false, x1, y1, (length/2));
// draw a 1/2 horizontal line with bottom end of vertical as midpoint of new line
Total(graphics, false, x2, y2, (length/2));
}
}
}
爲什麼你需要*來做到這一點?我真的不明白它給了什麼優勢;你的方法非常明確。 –