一对一递归函数

时间:2015-04-12 05:54:55

标签: c++ c recursion

我试图做我的硬件,然后卡住了。

这是我的问题:

我有两套:让set1 {a b c}和set2 {1 2 3 4 5}

我需要做1-1功能。意味着Set1中的每个元素都需要映射到set2中的一个元素我的程序给了我正确的答案但是只有第一组中只有3个元素才有用,如果有4个或5个怎么办?我需要创建递归函数,但我并不确定如何。

Enter number of elements in sets(separated by space): 3 5   
Enter set A (separated by space): a b c
Enter set B (separated by space): 1 2 3 4 5
The 1-1 function has 60 elements.
{(a,1), (b,2), (c,3)}
{(a,1), (b,2), (c,4)}
{(a,1), (b,2), (c,5)}
{(a,1), (b,3), (c,2)}
{(a,1), (b,3), (c,4)}
{(a,1), (b,3), (c,5)}
.......
{(a,5), (b,2), (c,1)}
{(a,5), (b,2), (c,3)}
{(a,5), (b,2), (c,4)}
{(a,5), (b,3), (c,1)}
{(a,5), (b,3), (c,2)}
{(a,5), (b,3), (c,4)}
{(a,5), (b,4), (c,1)}
{(a,5), (b,4), (c,2)}
{(a,5), (b,4), (c,3)}

我在c ++中进行元素分发的函数

void getOneToOne(vector <string> &oneTone, vector <string> set1, vector <string> set2){

for (size_t i = 0; i < set2.size(); i++)
{
    for (size_t k = 0; k < set2.size(); k++)
    {
        if (k != i)
        {
        for (size_t j = 0; j < set2.size(); j++)
            {
                if (j != i && k != j)
                {
                    string temp;
                    temp = "{(" + set1[0] + "," + set2[i] + "), (" + set1[1] + "," + set2[k] + "), (" + set1[2] + "," + set2[j] + ")}";
                    oneTone.push_back(temp);
                }
            }
        }
    }

}

}

2 个答案:

答案 0 :(得分:0)

简单的递归。您可以根据需要更改n1和n2。阅读此Link

#include<iostream>
#include<string>
using namespace std;
void swap(char *a, char *b){char c = *a;*a=*b;*b=c;}
void permute( char *a, char *b, int i, int n1, int n2)
{
    if ( i == n1) 
    {
        cout << "{";
        for( int k=0; k<n1; k++)
        cout << "("<< a[k] << "," << b[k]<<")";
        cout <<"}"<< endl;
    }
    else
    {
        for( int j=i; j < n2; j++) {
            swap( (b+i), (b+j) );
            permute(a,b,i+1,n1,n2);
            swap( (b+i), (b+j) );
        }
    }
}
int main()
{
    char a[] = "abc";
    char b[] = "12345";
    permute(a,b,0,3,5);
    return 0;
}

答案 1 :(得分:0)

非常感谢&#34; Cereal_Killer&#34;,现在一切顺利。 我不得不从char更改为String

#include<iostream>
#include<string>
using namespace std;
void swap(string *a, string *b)
{
string c = *a;
*a = *b; 
*b = c; }
void permute(string *a, string *b, int i, int n1, int n2)
{
    if (i == n1)
    {
        cout << "{";
        for (int k = 0; k<n1; k++)
            cout << "(" << a[k] << "," << b[k] << ")";
        cout << "}" << endl;
    }
    else
    {
        for (int j = i; j < n2; j++) {
            swap((b + i), (b + j));
            permute(a, b, i + 1, n1, n2);
            swap((b + i), (b + j));
        }
    }
}
int main()
{
    string a[] = { "a", "b", "c" };
    string b[] = { "1", "2", "3", "4","5" };
    permute(a, b, 0, 3, 5);
    return 0;
}