当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Issues trying to recursively populate and print out all inductive functions of two sets

问题描述:

I am having trouble figuring out how to make my recursive functions work properly. The idea is that I have two sets A and B and I need to print all of the inductive functions of A to B. This is my recursive function for doing this however the output (listed below) is not accurate and I while I can see why the issue exists I am having trouble figuring out how to solve it...

Currently I have the correct number of outputs for A = {a,b,c} and B = {1,2,3,4} which is 24, but they contain functions with repeated numbers in them which is not acceptable. Also I lose the B[0] once I pass it and therefore lose the subset {2,1,3} for example...

Any guidance would be appreciated.

void nextFunction(vector<string> A,

vector<string> B,

vector<string> func,

int left,

mpq_class total,

int index) {

if (left == 0) {

print(func, A);

return;

}

for (int i = index; i < B.size(); ++i) {

func.push_back(B[i]);

nextFunction(A, B, func, left-1, total, index+1);

func.pop_back();

}

}

void print(vector<string> function, vector<string> A) {

for (int i = 0; i < (A.size()); ++i) {

cout << "(" << A[i] << "," << function[i] << ") ";

}

cout << endl;

}

Output:

(a,1) (b,2) (c,3)

(a,1) (b,2) (c,4)

(a,1) (b,3) (c,3)

(a,1) (b,3) (c,4)

(a,1) (b,4) (c,3)

(a,1) (b,4) (c,4)

(a,2) (b,2) (c,3)

(a,2) (b,2) (c,4)

(a,2) (b,3) (c,3)

(a,2) (b,3) (c,4)

(a,2) (b,4) (c,3)

(a,2) (b,4) (c,4)

(a,3) (b,2) (c,3)

(a,3) (b,2) (c,4)

(a,3) (b,3) (c,3)

(a,3) (b,3) (c,4)

(a,3) (b,4) (c,3)

(a,3) (b,4) (c,4)

(a,4) (b,2) (c,3)

(a,4) (b,2) (c,4)

(a,4) (b,3) (c,3)

(a,4) (b,3) (c,4)

(a,4) (b,4) (c,3)

(a,4) (b,4) (c,4)

网友答案:

Although I don't really think this problem is a good candidate for recursion, your algorithm might look something like the following:

PrintPossibleFunctions (range_values, already_chosen, fn_def):

    if fn_def.size() == domain.size():
       print elements in order, preceded by the corresponding domain element
       return

    for value in range_values:
        if value not in already_chosen:
           already_chosen.insert(value)
           fn_def.push(value)
           PrintPossibleFunctions(range_values, already_chosen, fn_def)
           fn_def.pop()
           already_chosen.remove(value)
分享给朋友:
您可能感兴趣的文章:
随机阅读: