java - 随机生成一个由对象及其父对象组成的树结构

标签 java random tree

我正在尝试随机生成对象的树结构,如下所示:

Branch parent = new Branch("Start");
Branch branch1 = new Branch(parent, "Branch 1");
Branch branch2 = new Branch(parent, "Branch 2");
Branch branch21 = new Branch(branch2, "Branch 2.1");
Branch branch22 = new Branch(branch2, "Branch 2.2");

我知道如何手动创建对象,以及如何生成随机数,并且我已经在随机生成节点上看到了一些用于创建分形的东西,但我突然迷失了方向,因为我从来没有这样做过之前以编程方式生成对象。

任何有关从哪里开始或使用什么技术的想法将不胜感激。

最佳答案

通常,在构建此类项目时,最好进行内部和外部设计。否则,您会发现自己必须支持许多应用程序方法才能支持预期结果。

希望这有帮助!

尝试以下操作:)

Branch start = new Branch();
CreateChildren(start);

const int ChildrenLimitCheck = 0;

private void CreateChildren(Branch parent) {

    //Use a limit variable so that you can decrease, and if it's equal to a sepcific number(usually 0) exit.
    int Limit = (int) (Math.random() * 5);
     //Call the function that's recursive, inside of a function that isn't recursive. This gives you a clean way to interface with the recursive function without excessive lines of code in other areas
     generateChildren(parent,Limit);

}

private void generateChildren(Branch parent,int limit) {

    //Check to see if we've hit our minimum. If so, exit out of the logic
    if(limit == ChildrenLimitCheck)
        return;

    //Specify the random number of branches created in this instance
    int numberOfBranches = (int) (Math.random() * 5);

    for (int i = 0; i < numberOfBranches; i++) {
        Branch child = new Branch(parent);
        parent.Children.Add(child);

        //Depending on what you want to do, either pass i or pass limit. If you don't use limit, you can remove it from this function :)
        //If you pass i, try doing:
        //for (int i = numberOfBranches; i > 0; i--)
        //So that you can eventually get down to 0, to automatically stop your recursive calls with the above return statement. 
        //Seems you just want to run a loop for xxx number of times. This will still grant that, but you won't have to guess the upper limit
        //of numberOfBranches to exit on, and you'll be able to exit cleanly
       //This may be what caused your stackoverflow error. For all recursive functions, you need an exit condition or it will run indefinately
        generateChildren(child,--limit);
        //generateChildren(child,i);
    }
}

关于java - 随机生成一个由对象及其父对象组成的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606830/

相关文章:

java - 带有 Gui Designer 的小程序

java - 数学密集型、基于计算的网站 - 我应该使用哪种语言?

javascript - 以随机顺序对数组进行排序

c - 在 C 中访问结构体中的结构体

java - BufferedReader 读取线

java - 通过我的桌面应用程序将系统与任何 http 站点的数据库连接

java - 在 Apache Commons Math 的程序流程中更改分布参数

javascript - 使用javascript在浏览器中显示数组中的一行随机图片

java - 如何使用 O(logN) 对具有 n 个元素的优先级队列进行排序?

python - BioPython 中系统发育树的子树