簡體   English   中英

將返回 Console.WriteLine 的 void function 轉換為字符串 function?

[英]Converting a void function that returns Console.WriteLine into a string function?

我有一些遞歸問題要解決(經過一些斗爭我最終取得了勝利)我使函數(為它們計算結果)無效並且在遞歸 function 的每次迭代之后我調用“Console.WriteLine()”來打印行,在我繼續遞歸直到滿足某個條件之后,我將計算 function 調用到 Main function 中。現在我想嘗試將它們轉換為字符串並使它們更干凈,然后使用 Console.WriteLine 在 Main 中調用 function (). 例如下面的代碼。

public static void TowerOfHanoi(int n, char firstRod, char secondRod, char thirdRod)
{
    if (n == 0)
    {
        return;
    }

    TowerOfHanoi(n - 1, firstRod, thirdRod, secondRod);
    Console.WriteLine("From " + firstRod + " to " + secondRod);
    TowerOfHanoi(n - 1, thirdRod, secondRod, firstRod);
}

這是針對漢內塔問題,我必須使用中間桿 C 將一整疊圓盤從某個桿移動到另一個桿(在我的問題中從 A 到 B)。規則:我不能有圓盤大的放在小的上面,所以我做的每一步都必須讓小的圓盤在大的圓盤之上。

我嘗試將 function 從 void 更改為 string 並在其中添加一個新的空字符串,例如:

字符串結果=“”; 而不是 Console.WriteLine 我嘗試使用 result+= "From " + firstRod + " to " + secondRod + "\n"; 然后使用 Console.WriteLine 將 function 調用到 Main。 => 在這里我撞牆了。
這是我轉換它的失敗嘗試:如果我輸入 2 作為輸入,它應該返回:

從A到C 從A到B 從C到B。

但是由於我失敗的嘗試,它只返回從 A 到 B。我知道我應該有一個變量,我應該在每次遞歸后添加所有結果,但我似乎無法弄清楚

public static string TowerOfHanoi(int n, char firstRod, char secondRod, char thirdRod)
{
        if (n == 0)
        {
            return "";
        }

        TowerOfHanoi(n - 1, firstRod, thirdRod, secondRod);
        TowerOfHanoi(n - 1, thirdRod, secondRod, firstRod);

        return "From " + firstRod + " to " + secondRod + "\n";
    }

你對我如何解決這個問題有什么建議嗎? 先感謝您!

您更新后的代碼在兩個方面顯着改變了原始代碼的邏輯:

  1. “from...to”結果現在在兩個遞歸調用之后,而以前它兩個遞歸調用之間。
  2. 這些遞歸調用的結果被完全忽略 如果一個方法返回一個結果,而你想要那個結果,你必須以某種方式捕獲它。

例如:

var result = string.Empty;
if (n == 0)
{
    return result;
}

result += TowerOfHanoi(n - 1, firstRod, thirdRod, secondRod);
result += "From " + firstRod + " to " + secondRod + "\n";
result += TowerOfHanoi(n - 1, thirdRod, secondRod, firstRod);

return result;

然后,您可以開始使用StringBuilder而不是附加字符串來稍微改進功能:

if (n == 0)
{
    return string.Empty;
}

var result = new StringBuilder();
result.Append(TowerOfHanoi(n - 1, firstRod, thirdRod, secondRod));
result.Append("From " + firstRod + " to " + secondRod + "\n");
result.Append(TowerOfHanoi(n - 1, thirdRod, secondRod, firstRod));

return result.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM