Java 将迭代函数转换为递归函数
我试图将迭代函数转换为递归。 但一旦我尝试这样做,它就会像一个无限循环一样持续运行 这是我的迭代代码Java 将迭代函数转换为递归函数,java,recursion,iteration,Java,Recursion,Iteration,我试图将迭代函数转换为递归。 但一旦我尝试这样做,它就会像一个无限循环一样持续运行 这是我的迭代代码 private static Node buildModelTree(String[] args) { // TODO Auto-generated method stub String clsIndex = args[3]; splitted.add(currentsplit); double entropy = 0;
private static Node buildModelTree(String[] args) {
// TODO Auto-generated method stub
String clsIndex = args[3];
splitted.add(currentsplit);
double entropy = 0;
int total_attributes = (Integer.parseInt(clsIndex));// class index
int split_size = splitted.size();
GainRatio gainObj = new GainRatio();
while (split_size > current_index) { //iterate through all distinct pair for building children
currentsplit = (SplitInfo) splitted.get(current_index);
System.out.println("After currentsplit --->" + currentsplit);
gainObj = new GainRatio();
int res = 0;
res = ToolRunner.run(new Configuration(),new CopyOfFunID3Driver(), args);
gainObj.getcount(current_index);
entropy = gainObj.currNodeEntophy();
clsIndex = gainObj.majorityLabel();
currentsplit.classIndex = clsIndex;
if (entropy != 0.0 && currentsplit.attr_index.size() != total_attributes) { //calculate gain ration
bestGain(total_attributes,entropy,gainObj);
} else {
//When entropy is zero build tree
Node branch = new Node();
String rule = "";
Gson gson = new Gson();
int temp_size = currentsplit.attr_index.size();
for (int val = 0; val < temp_size; val++) {
int g = 0;
g = (Integer) currentsplit.attr_index.get(val);
if (val == 0) {
rule = g + " " + currentsplit.attr_value.get(val);
//JSON
// branch.add(g, currentsplit.attr_value.get(val).toString(), new Node(currentsplit.classIndex, true));
} else {
rule = rule + " " + g + " "+ currentsplit.attr_value.get(val);
//branch.add(g, currentsplit.attr_value.get(val).toString(), buildModelTree(args));
}
}
rule = rule + " " + currentsplit.classIndex;
}
split_size = splitted.size();
current_index++;
}
}
我应该在哪里换钱?
我正在努力建造一棵树。因此,为了得到树结构,我试图使id3代码递归。
在我当前的代码中,我只得到作为的输出,但我希望它作为
请建议。递归算法必须具有以下特性 1.每次函数调用自身时,问题的大小都必须减小 例如,如果假设您首先使用大小为n的数组调用函数,那么下次它必须小于n 基本大小写-返回语句的条件。 例如,如果数组大小为0,则返回 在您的代码中,缺少这两个 您将继续使用相同大小的数组调用函数。这就是问题所在
感谢一旦我尝试这样做,它就会像一个无限循环一样连续运行,您尝试了什么?我已经在代码中进行了注释。branch.addg,currentsplit.attr_value.getval.toString,buildModelTreeargs;我的建议是不做任何改变。如果这是一个类赋值,或者您正试图自己学习递归是如何工作的,好的。但在现实生活中,将迭代代码转换为递归代码几乎没有任何好处。