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

时间:2012-02-07 10:21:04

标签: java algorithm probability execution-time

我有一些事件,他们每个人都有可能发生,如果他们这样做,他们就会有重量。我想用相应的权重创建事件概率的所有可能组合。最后,我需要按重量顺序排序。这就像生成一个概率树,但我只关心生成的叶子,而不是它们获取它们的节点。我不需要在创建最终结果期间查找特定条目,只需创建所有值并按重量对它们进行排序。

只有大约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

2 个答案:

答案 0 :(得分:4)

选择合适的数据结构为50%,算法为50%。数据结构 - 我相信TreeBidiMap将为您带来魔力。您将需要实现2个比较器 - 1表示重量,另一个表示概率。 算法 - 琐碎。 祝你好运!

答案 1 :(得分:2)

尝试加速代码的一些技巧: - 尽量避免不必要的对象分配 - 尝试为您的集合使用正确的构造函数,在您的代码示例中,您似乎已经知道集合的大小,因此将其用作构造函数中的参数以防止无用集合调整大小(和gc调用) 您可以尝试使用Set而不是List来查看动态排序.....

HTH 杰罗姆