【问题标题】:Converting an iterative function to recursive将迭代函数转换为递归函数
【发布时间】:2015-05-30 01:11:38
【问题描述】:

我正在尝试将迭代函数转换为递归。 但是一旦我尝试这样做,它就会像无限循环一样连续运行。

这是我的迭代代码

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 代码递归。 使用我当前的代码,我只得到输出为this,但我希望它为tree structure

请提出建议。

【问题讨论】:

  • once I tried to do that it is runnning continuously like an infinite loop,你试过什么?
  • 我已经在该代码中发表了评论。(branch.add(g, currentsplit.attr_value.get(val).toString(), buildModelTree(args));)
  • 我的建议是“无处”进行更改。如果这是为了课堂作业,或者你想自己学习递归是如何工作的,好的。但在现实生活中,将迭代代码转换为递归代码几乎没有任何好处。

标签: java recursion iteration


【解决方案1】:

递归算法必须有以下内容

1.每次函数调用自己,问题的大小都必须减小。

(即如果假设您首先调用大小为 n 的数组的函数,那么下一次它必须小于 n。

  1. 基本情况 - 返回语句的条件。

(比如数组大小为0则返回)

在您的代码中,这两个缺失。

您继续以相同大小的数组调用函数。这就是问题所在。

谢谢

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多