首页 > 解决方案 > 将嵌套的 for 循环转换为 C 中的递归

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
          //  0  1  2  3  4  5  6  7
int arr[] = { 3, 6, 1, 2, 6, 7, 8, 4};
int bee[] = { 6, 8, 1, 4, 2, 6, 3, 7};
int i = 0;
int j = 0;
int matches[120] = {0};
int length1 = 8;

void find_matches(int *arr, int *bee, int*matches);

void find_matches(int *arr, int *bee, int *matches)
{
    for (i = 0; i<length1; i++)
    {
        for (j = 0; j < length1; j++)
        {
            if (arr[i]==bee[j])
            {
                matches[i] = j;
            }
        }
    }

    for (int z = 0; z<8; z++)
    {
        printf("%d\n", matches[z]);
    }
}

int main()
{
    find_matches(arr, bee, matches);
}

我的代码的要点是它匹配 to 的每个值,arr[]并将bee[]匹配的索引作为数字放入matches数组和打印中。

例如,值 3 in 与值 3 inarr[0]匹配,bee[5]因此 的值matches[0]将为 5。

我怎样才能把它变成一个递归函数?

我尝试保留外部 for 循环并在内部使用递归函数调用运行外部,但我不知道如何设置变量等。

标签: c

解决方案


在两个数组上进行双重递归 - 请参阅评论:

// recursives
void find_matches(int *arr, int *bee, int *matches, int current_position_in_arr);
void find_matches_in_bee(int *arr, int *bee, int *matches, int current_position_in_arr, int current_position_in_bee);

// wrapper
void find_matches(int *arr, int *bee, int *matches) {
    find_matches(arr, bee, matches, 0);
}

// outer loop : iterate over 'arr'
void find_matches(int *arr, int *bee, int *matches, int current_position_in_arr) {
    // check where arr[current_position_in_arr] is present in bee
    find_matches_in_bee(arr, bee, matches, current_position_in_arr, 0);

    // "next iteration of loop" - we check the next element in arr
    if (current_position_in_arr + 1 < length) {
        find_matches(arr, bee, matches, current_position_in_arr + 1);
    }
}

// inner loop : iterate over 'bee'
void find_matches_in_bee(int *arr, int *bee, int *matches, int current_position_in_arr, int current_position_in_bee) {
    // do your business magic
    if (arr[current_position_in_arr] == bee[current_position_in_bee]) {
       ....
    }

    // "next iteration of loop" - we check the next element in bee
    if (current_position_in_bee + 1 < length) {
        find_matches_in_bee(arr, bee, matches, current_position_in_arr, current_position_in_bee + 1);
    }
}

调用方式与之前相同:

find_matches(arr, bee, matches);

这里的教训是您可以替换以下内容:

int *array;

for (int i = 0; i < LEN; ++i) {
  f(array[i]);
}

void f(int *array) {
  f_inner(array, 0);
}

void f_inner(int *array, int position) {
  // business logic on array[position]

  // iteration step
  if (position + 1 < LEN) {
    f_inner(array, position + 1);
  }
}

推荐阅读