c - 使用递归判断两个数组是否相互排列

标签 c arrays recursion permutation

我在编写代码来通过使用递归来确定两个未排序的数组是否彼此排列时遇到一些困难。 我知道如何通过非递归代码使用排序来确定它 - 但我不知道如何通过使用递归来确定它。

到目前为止,我还没有任何真正的想法......

int CheckPermutation(int arr1[], int arr2[], int size) {
    if (size == 0) 
        return 1;
    if (size == 1)   
       return (arr1[0] > arr2[0]);
}   

这就是我尝试过的,我发现从那时起很难继续

最佳答案

这是一个使用递归来比较两个未排序数组而不修改它们的实现:

#include <stdio.h>

// count occurrences of value in an array using recursion
int rcount(int value, const int *a, int size) {
    return size == 0 ? 0 : (value == *a) + rcount(value, a + 1, size - 1);
}

// check if all entries in a have the same number of occurrences in a and b
int check_perm(const int *a, const int *b, int size) {
    for (int i = 0; i < size; i++) {
        if (rcount(a[i], a, size) != rcount(a[i], b, size))
            return 0;
    }
    return 1;
}

int main(void) {
    int a[] = { 1, 2, 3, 3, 4, 4, 4, 5, 6, };
    int b[] = { 1, 3, 2, 4, 5, 4, 4, 6, 3, };
    int c[] = { 1, 3, 2, 4, 5, 4, 4, 6, 6, };

    if (check_perm(a, b, sizeof(a) / sizeof(*a)))
        printf("arrays a and b match\n");

    if (!check_perm(a, c, sizeof(a) / sizeof(*a)))
        printf("arrays a and c do not match\n");

    if (!check_perm(b, c, sizeof(b) / sizeof(*b)))
        printf("arrays b and c do not match\n");

    return 0;
}

编辑:

这是一个具有单个递归函数的解决方案。两个数组都可能被修改。如果确实 check_perm() 返回非零,则两个数组都已排序:

int check_perm(const int *a, const int *b, int size) {
    if (size > 1) {
        for (int i = 1; i < size; i++) {
            if (a[0] > a[i]) {
                int temp = a[0];
                a[0] = a[i];
                a[i] = temp;
            }
            if (b[0] > b[i]) {
                int temp = b[0];
                b[0] = b[i];
                b[i] = temp;
            }
        }
        return (a[0] == b[0]) && check_perm(a + 1, b + 1, size - 1);
    }
    return 1;
}

关于c - 使用递归判断两个数组是否相互排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924559/

相关文章:

c - 获取给定成员定义地址的成员定义名称?

c - C 语言 gcc 编译器中前后增量的意外行为

c - 取消引用指针错误

php - 用 0 替换未指定的数组值

arrays - 使用 Swift 排序时数组排序不正确(按 :) method

c - 递归 FloodFill 算法的段错误

Node.js:异步函数中的尾部调用是否有优化?

algorithm - 如何递归解决移动受限的汉诺塔?

c - 运行c程序的linux脚本

python - 从 numpy 数组中删除子数组