c - 将嵌套的 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 循环并在内部使用递归函数调用运行外部,但我不知道如何设置变量等。
解决方案
在两个数组上进行双重递归 - 请参阅评论:
// 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);
}
}
推荐阅读
- javascript - For ... in 不让步的方法
- ios - 如何在带有 XCode 12.2 的 Swift 中使用 Objective-C 扩展函数?
- javascript - 我的 Discord 机器人不会用我制作的 Embed 回复
- java - 返回相同返回类型的对象会产生语法错误
- powershell - 将递归运行应用于 $com.GetDetailsOf 以获取长度参数
- django - 为什么Django可以处理多个请求?
- c++ - 我想知道如何填充基类然后派生类 C++
- javascript - 为什么 PHP 部分 Javascript 不能在 PHP 部分工作,但在 Html 部分工作正常?
- python - 使python输出打印并消失?
- r - 使用 R dplyr 汇总数据