#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);
}
我的代码的要点是它匹配 arr[]
的每个值到 bee[]
并将匹配的索引作为数字放在 匹配
数组并打印。
例如 arr[0]
中的值 3 与 bee[5]
中的值 3 相匹配,所以 matches[0]
将为 5。
如何将其转换为递归函数?
我尝试保留外部 for 循环并在内部调用递归函数来运行外部循环,但我不知道如何设置变量等。
最佳答案
双重递归,在两个数组上——见评论:
// 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);
}
}
关于将嵌套的 for 循环转换为 C 中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111823/