将迭代函数转换为递归函数

Transform iterative function to recursive function

本文关键字:递归函数 转换 函数 迭代      更新时间:2023-10-16

我和一位同事讨论了如何将下面的迭代函数转换为严格递归函数。我们知道,所有迭代函数都可以转换为递归函数;然而,我的同事记得,这个特定的实现只使用了三个参数。我们无法重新解决这个问题。我们记错了吗?还是我们错过了一些简单的东西?

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

p.S在我发布我的答案后,我看到了你的编辑,尽管你在我回答之前10分钟编辑了你的问题,我可以看到你自己选择了一条与我的答案相似的路径。