gpt4 book ai didi

java - 生成概率树然后对结果进行排序的时间高效实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:14:45 25 4
gpt4 key购买 nike

我有一些事件,其中每个事件都有发生的概率,如果发生则有一个权重。我想创建事件概率的所有可能组合,并具有相应的权重。最后,我需要按重量顺序对它们进行排序。这就像生成一棵概率树,但我只关心生成的叶子,而不关心得到它们需要哪些节点。我不需要在创建最终结果的过程中查找特定条目,只需创建所有值并按权重对它们进行排序。

只有大约 5-15 个事件,但是由于 n 个事件有 2^n 种结果的可能性,而且这是经常做的,我不希望它花费不必要的时间。速度比使用的存储量重要得多。

我提出的解决方案有效但速度很慢。有没有关于更快解决方案或改进想法的想法?

   class ProbWeight {
double prob;
double eventWeight;

public ProbWeight(double aProb, double aeventWeight) {
prob = aProb;
eventWeight = aeventWeight;
}

public ProbWeight(ProbWeight aCellProb) {
prob = aCellProb.getProb();
eventWeight = aCellProb.geteventWeight();
}

public double getProb(){
return prob;
}
public double geteventWeight(){
return eventWeight;
}

public void doesHappen(ProbWeight aProb) {
prob*=aProb.getProb();
eventWeight += aProb.geteventWeight();
}

public void doesNotHappen(ProbWeight aProb) {
prob*=(1-aProb.getProb());
}

}

//Data generation for testing
List<ProbWeight> dataList = new ArrayList<ProbWeight>();
for (int i =0; i<5; i++){
ProbWeight prob = new ProbWeight(Math.random(), 10*Math.random(), i);
dataList.add(prob);
}

//The list where the results will end up
List<ProbWeight> resultingProbList = new ArrayList<ProbWeight>();
// a temporaty list to avoid modifying a list while looping through it
List<ProbWeight> tempList = new ArrayList<ProbWeight>();

resultingProbList.add(dataList.remove(0));
for (ProbWeight data : dataList){ //for each event
//go through the already created event combinations and create two new for each
for(ProbWeight listed: resultingProbList){
ProbWeight firstPossibility = new ProbWeight(listed);
ProbWeight secondPossibility = new ProbWeight(listed);
firstPossibility.doesHappen(data);
secondPossibility.doesNotHappen(data);
tempList.add(firstPossibility);
tempList.add(secondPossibility);
}
resultingProbList = new ArrayList<ProbWeight>(tempList);
}
// Then sort the list by weight using sort and a comparator

最佳答案

选择合适的数据结构占50%,算法占50%。数据结构-我相信TreeBidiMap会为你施展魔法。您将需要实现 2 个比较器 - 1 个用于权重,另一个用于概率。算法 - 微不足道。祝你好运!

关于java - 生成概率树然后对结果进行排序的时间高效实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9174489/

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