【问题标题】:C++ - Could any help me to translate this for loop to recursion function?C++ - 可以帮助我将这个 for 循环转换为递归函数吗?
【发布时间】:2020-02-25 22:02:52
【问题描述】:

我有一个数组,表格,有一些字符,a 和 b。 我想找到并用'a'替换'b',然后计算替换了多少。如何写一个相当于嵌套循环的递归函数?

    const int length = 4;
    char table[length][length] = {
        {'a','b','a','a'},
        {'a','a','a','b'},
        {'a','a','b','a'},
        {'b','b','a','a'}
    };

    int count = 0;
    for (int i = 0; i < length; i++) {
        for (int j = 0; j < length; j++) {
            if (table[i][j] == 'b') {
                count++;
                table[i][j] = 'a';
            }
        }
    }
    cout << "Count: " << count << endl;

这是我尝试过的:

int replace_char(char array[][length], int row, int col) {
    // base cases and recursive
    if (row+1 != length - 1)
        replace_char(array, row+1, col);
    if (col+1 != length - 1)
        replace_char(array, row, col+1);

    // do this
    if (array[row][col] == 'b') {
        array[row][col] = 'a';
        return 1 + replace_char(array, row, col);
    }
    return 0;
}

我的想法是,如果它不是 col 或 row 的末尾,那么去检查下 col 或 row。检查时,如果 char 是 b,则返回 1,并从停止的位置开始检查。 但它不起作用。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读the help pagesthe SO tour、阅读how to ask good questions,以及this question checklist。还请学习如何创建一个minimal reproducible example 以向我们展示您自己的尝试,并描述您遇到的问题。最后请注意,stackoverflow.com 不是免费的编码服务。
  • 为什么?这是一个家庭作业问题吗?你试过什么?
  • ⚠️ 小心!对于一张小桌子,这很好。对于较大的或动态的表,C++ 中的递归很容易超出堆栈限制,因为 C++(通常)不支持尾递归优化。
  • 是的,它来自家庭作业,我更新了我尝试过的代码。似乎递归永远不会停止。
  • @Eljay 在 -O2 和 -O3 尾递归应该被优化掉。至少对于 GCC。

标签: c++ arrays for-loop recursion nested-loops


【解决方案1】:

函数可以按照演示程序中所示的方式定义

#include <iostream>

size_t replace_count( char *s, size_t n, char c1 = 'b', char c2 = 'a' )
{
    return n == 0 ? 0 
                  : ( ( *s == c1 ? ( *s = c2, 1 ) : 0 ) + replace_count( s + 1, n - 1, c1, c2 ) );
}

int main() 
{
    const int length = 4;
    char table[length][length] = {
        {'a','b','a','a'},
        {'a','a','a','b'},
        {'a','a','b','a'},
        {'b','b','a','a'}
    };

    std::cout << replace_count( reinterpret_cast<char *>( table ), length * length )
              << '\n';

    return 0;
}

它的输出是

5

【讨论】:

    【解决方案2】:

    非常接近:

    int replace_char(char array[][length], int row, int col) {
        if (col == length) {
            return replace_char(array, row + 1, 0); // reach the end of a col increment the
                                                    // row by 1 and reset the col.
                                                    // We are over the end so return
        }
        if (row == length) {
            // Then we have passed the last row simply return.
            return 0;
        }
    
        // Now do the work.
        int count = 0;
        if (array[row][col] == 'b') {
            array[row][col] = 'a';
            count = 1;
        }
        // Once you have done the work
        // Make the recursive call.
        return count + replace_char(array, row, col + 1);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-01
      • 2015-06-25
      • 2013-05-31
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      相关资源
      最近更新 更多