簡體   English   中英

將迭代函數轉換為遞歸函數

[英]Transform iterative function to recursive function

我正在與一位同事討論如何將以下迭代函數轉換為嚴格的遞歸函數。 我們知道,所有迭代函數都可以轉換為遞歸函數。 但是,我的同事記得這個特定的實現只使用了三個參數。 我們無法解決這個問題。 我們記錯了嗎? 還是我們缺少一些簡單的東西?

void iterative_function (char a, char b, int width) {
  int i = width;
  while (i > 0) {
    cout << string(i, a) << string(width-i, b) << endl;
    i -= 2;
  }
  i = width % 2;
  while (i <= width) {
    cout << string(i, a) << string(width-i, b) << endl;
    i += 2;
  }
}

當調用iterative_function('X', '-', 5)時,輸出如下所示。

XXXXX
XXX--
X----
XXX--
XXXXX

編輯:這是遞歸版本可能看起來像的一個小骨架:

void recursive_function (char a, char b, int width) {
  if (width > -1) {
    cout << string(width, a) << endl;
    recursive(a, b, width - 2);
    cout << string(width, a) << endl;
  }
}

除了這里的問題之外,在右側填充了連字符。

這是遞歸函數,我只是向您在這里可以看到的函數中添加另一個len ,它的輸出與此處代碼的輸出完全一樣。

#include <iostream>
using namespace std;

void i_f(char a, char b, int width,int len) {

  if(len <0 || width < 0)
    return;
  cout <<string(width, a) << string(len, b) << endl;
  i_f(a,b,width-2,len+2);
  cout <<string(width, a) << string(len, b) << endl;
}

int main() {
    i_f('X', '-', 5,0);
    return 0;
}

您的代碼輸出:

XXXXX
XXX--
X----
X----
XXX--
XXXXX

我的代碼輸出:

XXXXX
XXX--
X----
X----
XXX--
XXXXX

言:我發布答案后,盡管您在回答前10分鍾編輯了問題,但我看到了您的修改,並且可以看到您自己選擇了類似答案的路徑。

暫無
暫無

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

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