gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:39:37 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com