【发布时间】:2012-02-07 10:21:03
【问题描述】:
我有一些事件,其中每个事件都有发生的概率,如果发生的话,还有权重。我想用相应的权重创建事件概率的所有可能组合。最后,我需要按重量顺序对它们进行排序。这就像生成一个概率树,但我只关心生成的叶子,而不关心获取它们需要哪些节点。在创建最终结果的过程中,我不需要查找特定条目,只需创建所有值并按权重排序即可。
只有大约 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
【问题讨论】:
标签: java algorithm probability execution-time